@fuzionx/framework 0.1.29 → 0.1.31

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 (63) hide show
  1. package/cli/index.js +230 -114
  2. package/cli/templates/{app/fuzionx → make/app}/controllers/HomeController.js +1 -0
  3. package/cli/templates/{app/tester → make/app}/views/default/errors/404.html +0 -4
  4. package/cli/templates/{app/fuzionx/views/default/errors/404.html → make/app/views/default/errors/500.html} +1 -2
  5. package/cli/templates/make/app/views/default/pages/home.html +11 -0
  6. package/index.js +3 -0
  7. package/lib/core/Application.js +31 -6
  8. package/lib/core/Context.js +30 -1
  9. package/lib/helpers/I18nHelper.js +10 -6
  10. package/lib/middleware/apiAuth.js +79 -0
  11. package/lib/middleware/auth.js +42 -0
  12. package/lib/middleware/bodyParser.js +19 -0
  13. package/lib/middleware/cors.js +47 -0
  14. package/lib/middleware/csrf.js +32 -0
  15. package/lib/middleware/index.js +8 -277
  16. package/lib/middleware/session.js +27 -0
  17. package/lib/middleware/theme.js +20 -0
  18. package/lib/schedule/Job.js +4 -0
  19. package/lib/schedule/Queue.js +20 -8
  20. package/lib/schedule/Scheduler.js +84 -75
  21. package/lib/utilities/ArrUtil.js +112 -0
  22. package/lib/utilities/DateUtil.js +98 -0
  23. package/lib/utilities/FunctionUtil.js +119 -0
  24. package/lib/utilities/NumUtil.js +75 -0
  25. package/lib/utilities/ObjectUtil.js +170 -0
  26. package/lib/utilities/PaginationUtil.js +81 -0
  27. package/lib/utilities/StrUtil.js +105 -0
  28. package/lib/utilities/index.js +18 -0
  29. package/package.json +2 -2
  30. package/cli/templates/app/.env.example.tpl +0 -14
  31. package/cli/templates/app/.gitignore.tpl +0 -4
  32. package/cli/templates/app/app.js.tpl +0 -6
  33. package/cli/templates/app/database/models/User.js +0 -9
  34. package/cli/templates/app/fuzionx/views/default/errors/500.html +0 -14
  35. package/cli/templates/app/fuzionx/views/default/pages/home.html +0 -188
  36. package/cli/templates/app/fuzionx.yaml.tpl +0 -202
  37. package/cli/templates/app/locales/en.json +0 -52
  38. package/cli/templates/app/locales/ko.json +0 -52
  39. package/cli/templates/app/package.json.tpl +0 -16
  40. package/cli/templates/app/shared/events/userEvents.js +0 -10
  41. package/cli/templates/app/shared/jobs/CleanupJob.js +0 -18
  42. package/cli/templates/app/shared/jobs/EmailTask.js +0 -17
  43. package/cli/templates/app/shared/jobs/VideoPreviewTask.js +0 -47
  44. package/cli/templates/app/shared/workers/heavy.js +0 -18
  45. package/cli/templates/app/tester/controllers/FileController.js +0 -288
  46. package/cli/templates/app/tester/controllers/HomeController.js +0 -36
  47. package/cli/templates/app/tester/controllers/UserController.js +0 -43
  48. package/cli/templates/app/tester/middleware/RequestLogger.js +0 -13
  49. package/cli/templates/app/tester/routes/api.js +0 -397
  50. package/cli/templates/app/tester/routes/web.js +0 -8
  51. package/cli/templates/app/tester/services/UserService.js +0 -52
  52. package/cli/templates/app/tester/views/default/errors/500.html +0 -14
  53. package/cli/templates/app/tester/views/default/layouts/main.html +0 -82
  54. package/cli/templates/app/tester/views/default/pages/home.html +0 -56
  55. package/cli/templates/app/tester/views/default/pages/i18n.html +0 -104
  56. package/cli/templates/app/tester/views/default/pages/upload.html +0 -149
  57. package/cli/templates/app/tester/views/default/pages/websocket.html +0 -239
  58. package/cli/templates/app/tester/views/default/partials/footer.html +0 -8
  59. package/cli/templates/app/tester/views/default/partials/header.html +0 -20
  60. package/cli/templates/app/tester/ws/ChatHandler.js +0 -98
  61. /package/cli/templates/{app/fuzionx/routes/api.js.tpl → make/app/routes/api.js} +0 -0
  62. /package/cli/templates/{app/fuzionx/routes/web.js.tpl → make/app/routes/web.js} +0 -0
  63. /package/cli/templates/{app/fuzionx → make/app}/views/default/layouts/main.html +0 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * apiAuth — JWT Bearer 토큰 인증 미들웨어
3
+ *
4
+ * Authorization: Bearer <token> → 검증 → ctx.user
5
+ *
6
+ * @see docs/framework/14-authentication.md
7
+ *
8
+ * @param {object} [opts]
9
+ * @param {string} [opts.secret] - JWT 시크릿
10
+ * @param {string} [opts.model='User']
11
+ */
12
+ import { createHmac, timingSafeEqual } from 'node:crypto';
13
+
14
+ export function apiAuth(opts = {}) {
15
+ const modelName = opts.model || 'User';
16
+
17
+ return async (ctx, next) => {
18
+ const authHeader = ctx.get('authorization') || '';
19
+
20
+ if (!authHeader.startsWith('Bearer ')) {
21
+ ctx.status(401).json({ error: { message: 'Token required', status: 401 } });
22
+ return;
23
+ }
24
+
25
+ const token = authHeader.slice(7);
26
+
27
+ try {
28
+ const secret = opts.secret || ctx.app?.config?.get('app.auth.secret', 'fuzionx');
29
+ const payload = decodeJwtPayload(token, secret);
30
+
31
+ if (!payload || !payload.sub) {
32
+ ctx.status(401).json({ error: { message: 'Invalid token', status: 401 } });
33
+ return;
34
+ }
35
+
36
+ if (ctx.app?.db?.[modelName]) {
37
+ ctx.user = await ctx.app.db[modelName].find(payload.sub);
38
+ } else {
39
+ ctx.user = { id: payload.sub, ...payload };
40
+ }
41
+ } catch {
42
+ ctx.status(401).json({ error: { message: 'Invalid token', status: 401 } });
43
+ return;
44
+ }
45
+
46
+ await next();
47
+ };
48
+ }
49
+
50
+ /**
51
+ * JWT 디코드 + HMAC-SHA256 서명 검증
52
+ * @private
53
+ */
54
+ function decodeJwtPayload(token, secret) {
55
+ try {
56
+ const parts = token.split('.');
57
+ if (parts.length !== 3) return null;
58
+
59
+ const [headerB64, payloadB64, signatureB64] = parts;
60
+
61
+ const signingInput = `${headerB64}.${payloadB64}`;
62
+ const expectedSig = createHmac('sha256', secret)
63
+ .update(signingInput)
64
+ .digest();
65
+
66
+ const actualSig = Buffer.from(signatureB64, 'base64url');
67
+ if (expectedSig.length !== actualSig.length) return null;
68
+ if (!timingSafeEqual(expectedSig, actualSig)) return null;
69
+
70
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
71
+
72
+ if (payload.exp !== undefined && Date.now() / 1000 > payload.exp) return null;
73
+ if (payload.nbf !== undefined && Date.now() / 1000 < payload.nbf) return null;
74
+
75
+ return payload;
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * auth — 세션 인증 미들웨어
3
+ *
4
+ * ctx.session.userId → db.User.find() → ctx.user
5
+ *
6
+ * @see docs/framework/14-authentication.md
7
+ *
8
+ * @param {object} [opts]
9
+ * @param {string} [opts.sessionKey='userId']
10
+ * @param {string} [opts.model='User']
11
+ * @param {string} [opts.redirectTo='/login']
12
+ */
13
+ export function auth(opts = {}) {
14
+ const sessionKey = opts.sessionKey || 'userId';
15
+ const modelName = opts.model || 'User';
16
+ const redirectTo = opts.redirectTo || null;
17
+
18
+ return async (ctx, next) => {
19
+ const userId = ctx._rawSession?.[sessionKey] || ctx.get('x-test-user-id');
20
+
21
+ if (!userId) {
22
+ if (redirectTo) {
23
+ ctx.redirect(redirectTo);
24
+ } else {
25
+ ctx.status(401).json({ error: { message: 'Unauthorized', status: 401 } });
26
+ }
27
+ return;
28
+ }
29
+
30
+ if (ctx.app?.db?.[modelName]) {
31
+ try {
32
+ ctx.user = await ctx.app.db[modelName].find(userId);
33
+ } catch {
34
+ ctx.user = { id: userId };
35
+ }
36
+ } else {
37
+ ctx.user = { id: userId };
38
+ }
39
+
40
+ await next();
41
+ };
42
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * bodyParser — JSON/Form body 파싱 미들웨어
3
+ *
4
+ * Bridge가 이미 파싱한 body를 보장.
5
+ * 추가 파싱이 필요한 경우 처리.
6
+ *
7
+ * @see docs/framework/12-middleware.md
8
+ */
9
+ export function bodyParser() {
10
+ return async (ctx, next) => {
11
+ if (typeof ctx.body === 'string' && ctx.body) {
12
+ const ct = ctx.get('content-type') || '';
13
+ if (ct.includes('application/json')) {
14
+ try { ctx.body = JSON.parse(ctx.body); } catch {}
15
+ }
16
+ }
17
+ await next();
18
+ };
19
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * cors — CORS 미들웨어
3
+ *
4
+ * @see docs/framework/12-middleware.md
5
+ *
6
+ * @param {object} [opts]
7
+ * @param {string|string[]} [opts.origin='*']
8
+ * @param {string} [opts.methods='GET,POST,PUT,PATCH,DELETE,OPTIONS']
9
+ * @param {string} [opts.headers='Content-Type,Authorization']
10
+ * @param {boolean} [opts.credentials=false]
11
+ * @param {number} [opts.maxAge=86400]
12
+ */
13
+ export function cors(opts = {}) {
14
+ const origin = opts.origin || '*';
15
+ const methods = opts.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
16
+ const headers = opts.headers || 'Content-Type,Authorization';
17
+ const credentials = opts.credentials || false;
18
+ const maxAge = opts.maxAge || 86400;
19
+
20
+ return async (ctx, next) => {
21
+ const reqOrigin = ctx.get('origin') || '*';
22
+ let allowOrigin;
23
+
24
+ if (credentials && origin === '*') {
25
+ allowOrigin = reqOrigin !== '*' ? reqOrigin : '';
26
+ } else {
27
+ allowOrigin = origin === '*' ? '*' : (
28
+ Array.isArray(origin)
29
+ ? (origin.includes(reqOrigin) ? reqOrigin : origin[0])
30
+ : origin
31
+ );
32
+ }
33
+
34
+ ctx.header('Access-Control-Allow-Origin', allowOrigin);
35
+ ctx.header('Access-Control-Allow-Methods', methods);
36
+ ctx.header('Access-Control-Allow-Headers', headers);
37
+ if (credentials) ctx.header('Access-Control-Allow-Credentials', 'true');
38
+
39
+ if (ctx.method === 'OPTIONS') {
40
+ ctx.header('Access-Control-Max-Age', String(maxAge));
41
+ ctx.status(204).end();
42
+ return;
43
+ }
44
+
45
+ await next();
46
+ };
47
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * csrf — CSRF 보호 미들웨어
3
+ *
4
+ * GET/HEAD/OPTIONS 는 통과, 나머지는 토큰 검증.
5
+ *
6
+ * @see docs/framework/12-middleware.md
7
+ *
8
+ * @param {object} [opts]
9
+ * @param {string} [opts.headerName='x-csrf-token']
10
+ * @param {string} [opts.sessionKey='_csrfToken']
11
+ */
12
+ export function csrf(opts = {}) {
13
+ const headerName = opts.headerName || 'x-csrf-token';
14
+ const sessionKey = opts.sessionKey || '_csrfToken';
15
+
16
+ return async (ctx, next) => {
17
+ if (['GET', 'HEAD', 'OPTIONS'].includes(ctx.method)) {
18
+ await next();
19
+ return;
20
+ }
21
+
22
+ const token = ctx.get(headerName);
23
+ const expected = ctx._rawSession?.[sessionKey];
24
+
25
+ if (!token || !expected || token !== expected) {
26
+ ctx.status(403).json({ error: { message: 'CSRF token mismatch', status: 403 } });
27
+ return;
28
+ }
29
+
30
+ await next();
31
+ };
32
+ }
@@ -1,282 +1,13 @@
1
1
  /**
2
- * 내장 미들웨어 — bodyParser, cors, auth, apiAuth, csrf
2
+ * 내장 미들웨어 — 배럴 re-export
3
3
  *
4
4
  * @see docs/framework/12-middleware.md
5
5
  * @see docs/framework/14-authentication.md
6
6
  */
7
- import { createHmac, timingSafeEqual } from 'node:crypto';
8
-
9
- /**
10
- * JSON/Form body 파싱 미들웨어
11
- * Bridge가 이미 파싱한 body를 보장. 추가 파싱이 필요한 경우 처리.
12
- */
13
- export function bodyParser() {
14
- return async (ctx, next) => {
15
- // Bridge가 body를 이미 파싱했으므로 ctx.body는 rawReq.body에서 가져옴
16
- // 추가 파싱이 필요하면 여기서 처리
17
- if (typeof ctx.body === 'string' && ctx.body) {
18
- const ct = ctx.get('content-type') || '';
19
- if (ct.includes('application/json')) {
20
- try { ctx.body = JSON.parse(ctx.body); } catch {}
21
- }
22
- }
23
- await next();
24
- };
25
- }
26
-
27
- /**
28
- * CORS 미들웨어
29
- * @param {object} [opts]
30
- * @param {string|string[]} [opts.origin='*']
31
- * @param {string} [opts.methods='GET,POST,PUT,PATCH,DELETE,OPTIONS']
32
- * @param {string} [opts.headers='Content-Type,Authorization']
33
- * @param {boolean} [opts.credentials=false]
34
- * @param {number} [opts.maxAge=86400]
35
- */
36
- export function cors(opts = {}) {
37
- const origin = opts.origin || '*';
38
- const methods = opts.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
39
- const headers = opts.headers || 'Content-Type,Authorization';
40
- const credentials = opts.credentials || false;
41
- const maxAge = opts.maxAge || 86400;
42
-
43
- return async (ctx, next) => {
44
- const reqOrigin = ctx.get('origin') || '*';
45
- let allowOrigin;
46
-
47
- if (credentials && origin === '*') {
48
- // W3C 스펙: credentials:true일 때 origin:'*' 사용 불가 → request origin 미러링
49
- allowOrigin = reqOrigin !== '*' ? reqOrigin : '';
50
- } else {
51
- allowOrigin = origin === '*' ? '*' : (
52
- Array.isArray(origin)
53
- ? (origin.includes(reqOrigin) ? reqOrigin : origin[0])
54
- : origin
55
- );
56
- }
57
-
58
- ctx.header('Access-Control-Allow-Origin', allowOrigin);
59
- ctx.header('Access-Control-Allow-Methods', methods);
60
- ctx.header('Access-Control-Allow-Headers', headers);
61
- if (credentials) ctx.header('Access-Control-Allow-Credentials', 'true');
62
-
63
- // Preflight OPTIONS
64
- if (ctx.method === 'OPTIONS') {
65
- ctx.header('Access-Control-Max-Age', String(maxAge));
66
- ctx.status(204).end();
67
- return;
68
- }
69
-
70
- await next();
71
- };
72
- }
73
-
74
- /**
75
- * 세션 인증 미들웨어
76
- * ctx.session.userId → db.User.find() → ctx.user
77
- * @param {object} [opts]
78
- * @param {string} [opts.sessionKey='userId']
79
- * @param {string} [opts.model='User']
80
- * @param {string} [opts.redirectTo='/login']
81
- */
82
- export function auth(opts = {}) {
83
- const sessionKey = opts.sessionKey || 'userId';
84
- const modelName = opts.model || 'User';
85
- const redirectTo = opts.redirectTo || null;
86
-
87
- return async (ctx, next) => {
88
- const userId = ctx._rawSession?.[sessionKey] || ctx.get('x-test-user-id');
89
-
90
- if (!userId) {
91
- if (redirectTo) {
92
- ctx.redirect(redirectTo);
93
- } else {
94
- ctx.status(401).json({ error: { message: 'Unauthorized', status: 401 } });
95
- }
96
- return;
97
- }
98
-
99
- // DB 조회 (ModelRegistry 사용)
100
- if (ctx.app?.db?.[modelName]) {
101
- try {
102
- ctx.user = await ctx.app.db[modelName].find(userId);
103
- } catch {
104
- ctx.user = { id: userId };
105
- }
106
- } else {
107
- ctx.user = { id: userId };
108
- }
109
-
110
- await next();
111
- };
112
- }
113
-
114
- /**
115
- * JWT Bearer 토큰 인증 미들웨어
116
- * Authorization: Bearer <token> → 검증 → ctx.user
117
- * @param {object} [opts]
118
- * @param {string} [opts.secret] - JWT 시크릿 (config에서도 읽음)
119
- * @param {string} [opts.model='User']
120
- */
121
- export function apiAuth(opts = {}) {
122
- const modelName = opts.model || 'User';
123
-
124
- return async (ctx, next) => {
125
- const authHeader = ctx.get('authorization') || '';
126
-
127
- if (!authHeader.startsWith('Bearer ')) {
128
- ctx.status(401).json({ error: { message: 'Token required', status: 401 } });
129
- return;
130
- }
131
-
132
- const token = authHeader.slice(7);
133
-
134
- // JWT 검증 — Bridge crypto 사용 가능 시 위임
135
- try {
136
- const secret = opts.secret || ctx.app?.config?.get('app.auth.secret', 'fuzionx');
137
- const payload = decodeJwtPayload(token, secret);
138
-
139
- if (!payload || !payload.sub) {
140
- ctx.status(401).json({ error: { message: 'Invalid token', status: 401 } });
141
- return;
142
- }
143
-
144
- // DB에서 유저 조회
145
- if (ctx.app?.db?.[modelName]) {
146
- ctx.user = await ctx.app.db[modelName].find(payload.sub);
147
- } else {
148
- ctx.user = { id: payload.sub, ...payload };
149
- }
150
- } catch {
151
- ctx.status(401).json({ error: { message: 'Invalid token', status: 401 } });
152
- return;
153
- }
154
-
155
- await next();
156
- };
157
- }
158
-
159
- /**
160
- * CSRF 보호 미들웨어
161
- * GET/HEAD/OPTIONS 는 통과, 나머지는 토큰 검증
162
- * @param {object} [opts]
163
- * @param {string} [opts.headerName='x-csrf-token']
164
- * @param {string} [opts.sessionKey='_csrfToken']
165
- */
166
- export function csrf(opts = {}) {
167
- const headerName = opts.headerName || 'x-csrf-token';
168
- const sessionKey = opts.sessionKey || '_csrfToken';
169
-
170
- return async (ctx, next) => {
171
- // 안전한 메서드는 통과
172
- if (['GET', 'HEAD', 'OPTIONS'].includes(ctx.method)) {
173
- await next();
174
- return;
175
- }
176
-
177
- const token = ctx.get(headerName);
178
- const expected = ctx._rawSession?.[sessionKey];
179
-
180
- if (!token || !expected || token !== expected) {
181
- ctx.status(403).json({ error: { message: 'CSRF token mismatch', status: 403 } });
182
- return;
183
- }
184
-
185
- await next();
186
- };
187
- }
188
-
189
- /**
190
- * JWT 디코드 + HMAC-SHA256 서명 검증
191
- * @param {string} token - JWT 토큰
192
- * @param {string} secret - HMAC 시크릿 키
193
- * @returns {object|null} - 검증된 payload 또는 null
194
- * @private
195
- */
196
- function decodeJwtPayload(token, secret) {
197
- try {
198
- const parts = token.split('.');
199
- if (parts.length !== 3) return null;
200
-
201
- const [headerB64, payloadB64, signatureB64] = parts;
202
-
203
- // ── HMAC-SHA256 서명 검증 ──
204
- const signingInput = `${headerB64}.${payloadB64}`;
205
- const expectedSig = createHmac('sha256', secret)
206
- .update(signingInput)
207
- .digest();
208
-
209
- // base64url → Buffer
210
- const actualSig = Buffer.from(signatureB64, 'base64url');
211
-
212
- // 길이 불일치 시 즉시 거부 (timingSafeEqual은 길이 같아야 함)
213
- if (expectedSig.length !== actualSig.length) return null;
214
- if (!timingSafeEqual(expectedSig, actualSig)) return null;
215
-
216
- // ── payload 디코드 ──
217
- const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
218
-
219
- // 만료 체크
220
- if (payload.exp !== undefined && Date.now() / 1000 > payload.exp) return null;
221
-
222
- // nbf (Not Before) 체크
223
- if (payload.nbf !== undefined && Date.now() / 1000 < payload.nbf) return null;
224
-
225
- return payload;
226
- } catch {
227
- return null;
228
- }
229
- }
230
-
231
- /**
232
- * 세션 로드/저장 미들웨어
233
- * Bridge sessionGet/sessionSet 사용.
234
- *
235
- * @see docs/framework/12-middleware.md — "session: 세션 로드/저장"
236
- */
237
- export function session(opts = {}) {
238
- return async (ctx, next) => {
239
- // Session은 Context 생성 시 rawReq.session에서 이미 로드됨
240
- // Bridge가 rawReq에 session 데이터를 포함하여 전달
241
-
242
- await next();
243
-
244
- // 요청 완료 후 — 소비된 flash 데이터 정리
245
- // flash는 getFlash() 호출 시 로컬에서 삭제되지만,
246
- // Bridge 세션 저장소에서도 제거해야 함
247
- const bridge = ctx.app?._bridge;
248
- const sessionId = ctx._sessionId;
249
- if (sessionId && bridge?.sessionSet && ctx._rawSession) {
250
- // _flash가 비었으면 세션에서 제거
251
- if (ctx._rawSession._flash && Object.keys(ctx._rawSession._flash).length === 0) {
252
- delete ctx._rawSession._flash;
253
- }
254
- try {
255
- bridge.sessionSet(sessionId, ctx._rawSession);
256
- } catch {}
257
- }
258
- };
259
- }
260
-
261
- /**
262
- * 테마 미들웨어 — 도메인 → 테마 매핑
263
- *
264
- * @see docs/framework/03-views-templates.md
265
- * @see docs/framework/12-middleware.md — "theme: 도메인 → 테마 매핑"
266
- *
267
- * @param {object} [opts]
268
- * @param {string} [opts.default='default'] - 기본 테마
269
- * @param {object} [opts.mapping] - { 'domain.com': 'theme1' }
270
- */
271
- export function theme(opts = {}) {
272
- const defaultTheme = opts.default || 'default';
273
-
274
- return async (ctx, next) => {
275
- // 앱별 테마 결정 — 도메인→앱 라우팅은 Application._resolveApp()에서 처리
276
- const configDefault = ctx.app?.config?.get('app.themes.default') || defaultTheme;
277
- ctx.theme = configDefault;
278
-
279
- await next();
280
- };
281
- }
282
-
7
+ export { bodyParser } from './bodyParser.js';
8
+ export { cors } from './cors.js';
9
+ export { auth } from './auth.js';
10
+ export { apiAuth } from './apiAuth.js';
11
+ export { csrf } from './csrf.js';
12
+ export { session } from './session.js';
13
+ export { theme } from './theme.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * session — 세션 로드/저장 미들웨어
3
+ *
4
+ * Bridge sessionGet/sessionSet 사용.
5
+ *
6
+ * @see docs/framework/12-middleware.md — "session: 세션 로드/저장"
7
+ */
8
+ export function session(opts = {}) {
9
+ return async (ctx, next) => {
10
+ // Session은 Context 생성 시 rawReq.session에서 이미 로드됨
11
+ // Bridge가 rawReq에 session 데이터를 포함하여 전달
12
+
13
+ await next();
14
+
15
+ // 요청 완료 후 — 소비된 flash 데이터 정리
16
+ const bridge = ctx.app?._bridge;
17
+ const sessionId = ctx._sessionId;
18
+ if (sessionId && bridge?.sessionSet && ctx._rawSession) {
19
+ if (ctx._rawSession._flash && Object.keys(ctx._rawSession._flash).length === 0) {
20
+ delete ctx._rawSession._flash;
21
+ }
22
+ try {
23
+ bridge.sessionSet(sessionId, ctx._rawSession);
24
+ } catch {}
25
+ }
26
+ };
27
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * theme — 도메인 → 테마 매핑 미들웨어
3
+ *
4
+ * @see docs/framework/03-views-templates.md
5
+ * @see docs/framework/12-middleware.md — "theme: 도메인 → 테마 매핑"
6
+ *
7
+ * @param {object} [opts]
8
+ * @param {string} [opts.default='default'] - 기본 테마
9
+ * @param {object} [opts.mapping] - { 'domain.com': 'theme1' }
10
+ */
11
+ export function theme(opts = {}) {
12
+ const defaultTheme = opts.default || 'default';
13
+
14
+ return async (ctx, next) => {
15
+ const configDefault = ctx.app?.config?.get('app.themes.default') || defaultTheme;
16
+ ctx.theme = configDefault;
17
+
18
+ await next();
19
+ };
20
+ }
@@ -18,6 +18,10 @@ export default class Job extends Base {
18
18
 
19
19
  /**
20
20
  * Job 실행 (서브클래스에서 오버라이드)
21
+ *
22
+ * 메인 스레드에서 실행되므로 this.db, this.service() 등 접근 가능.
23
+ * CPU-intensive 작업은 this.worker.run() 또는 this.worker.exec()으로 위임.
24
+ *
21
25
  * @returns {Promise<void>}
22
26
  */
23
27
  async handle() {
@@ -1,20 +1,26 @@
1
1
  /**
2
2
  * Queue — Task 큐 관리 (Memory/Redis)
3
3
  *
4
+ * AutoLoader가 shared/jobs/ 에서 Task 클래스를 자동 스캔·등록.
5
+ * handle(data)은 메인 스레드에서 실행되므로 this.db, this.service() 등
6
+ * 앱 컨텍스트에 접근 가능합니다.
7
+ *
8
+ * CPU-intensive 작업은 handle() 내에서 this.worker.run()으로 위임.
9
+ *
4
10
  * @see docs/framework/10-scheduler-queue.md
5
- * @see docs/framework/class-design.mm.md (Queue)
11
+ * @see lib/schedule/WorkerPool.js
6
12
  */
7
13
  export default class Queue {
8
14
  /**
9
- * @param {import('./Application.js').default} app
15
+ * @param {import('../core/Application.js').default} app
10
16
  * @param {object} [opts]
11
17
  * @param {string} [opts.driver='memory'] - 'memory' | 'redis'
12
18
  */
13
19
  constructor(app, opts = {}) {
14
20
  this.app = app;
15
21
  this.driver = opts.driver || 'memory';
16
- this._tasks = new Map(); // 등록된 Task 클래스
17
- this._queue = []; // 메모리 큐
22
+ this._tasks = new Map(); // name TaskClass
23
+ this._queue = [];
18
24
  this._processing = false;
19
25
  }
20
26
 
@@ -55,24 +61,30 @@ export default class Queue {
55
61
  const TaskClass = this._tasks.get(job.name);
56
62
 
57
63
  if (!TaskClass) {
58
- this.app?.logger?.error?.(`Task '${job.name}' not registered`);
64
+ this.app?.logger?.error?.(`[Queue] Task '${job.name}' not registered`);
59
65
  continue;
60
66
  }
61
67
 
68
+ const timeout = TaskClass.timeout || 30000;
62
69
  const task = new TaskClass(this.app);
70
+
63
71
  try {
64
- await task.handle(job.data);
72
+ await Promise.race([
73
+ task.handle(job.data),
74
+ new Promise((_, reject) =>
75
+ setTimeout(() => reject(new Error(`Task timeout (${timeout}ms)`)), timeout)
76
+ ),
77
+ ]);
65
78
  } catch (err) {
66
79
  job.retries++;
67
80
  if (job.retries < (TaskClass.retries || 3)) {
68
- // 재시도
69
81
  const delay = TaskClass.retryDelay || 1000;
70
82
  setTimeout(() => {
71
83
  this._queue.push(job);
72
84
  if (!this._processing) this._process();
73
85
  }, delay);
74
86
  } else {
75
- await task.failed(job.data, err);
87
+ try { await task.failed(job.data, err); } catch {}
76
88
  }
77
89
  }
78
90
  }