create-fuzionx 0.1.31 → 0.1.32

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 (123) hide show
  1. package/index.js +84 -79
  2. package/package.json +1 -1
  3. package/templates/{fuzionx.yaml.tpl → common/fuzionx.yaml.tpl} +3 -1
  4. package/templates/{package.json.tpl → common/package.json.tpl} +2 -2
  5. package/templates/spa/controllers/AuthController.js +114 -0
  6. package/templates/spa/controllers/HomeController.js +68 -0
  7. package/templates/spa/controllers/PostController.js +191 -0
  8. package/templates/spa/controllers/UserController.js +43 -0
  9. package/templates/spa/meta.json +24 -0
  10. package/templates/spa/routes/api.js +31 -0
  11. package/templates/spa/routes/web.js +19 -0
  12. package/templates/spa/services/AuthService.js +48 -0
  13. package/templates/spa/services/PostService.js +372 -0
  14. package/templates/spa/services/UserService.js +48 -0
  15. package/templates/spa/views/default/errors/404.html +11 -0
  16. package/templates/spa/views/default/errors/500.html +11 -0
  17. package/templates/spa/views/default/layouts/main.html +34 -0
  18. package/templates/spa/views/default/pages/home.html +22 -0
  19. package/templates/spa/views/default/spa/index.html +13 -0
  20. package/templates/spa/views/default/spa/package.json +20 -0
  21. package/templates/spa/views/default/spa/src/App.vue +41 -0
  22. package/templates/spa/views/default/spa/src/assets/landing.css +220 -0
  23. package/templates/spa/views/default/spa/src/assets/style.css +1156 -0
  24. package/templates/spa/views/default/spa/src/components/AlertDialog.vue +179 -0
  25. package/templates/spa/views/default/spa/src/components/CodeBlock.vue +33 -0
  26. package/templates/spa/views/default/spa/src/components/EditorToolbar.vue +54 -0
  27. package/templates/spa/views/default/spa/src/components/FileUpload.vue +161 -0
  28. package/templates/spa/views/default/spa/src/components/FlashMessage.vue +39 -0
  29. package/templates/spa/views/default/spa/src/components/LanguageSwitcher.vue +108 -0
  30. package/templates/spa/views/default/spa/src/components/Lightbox.vue +62 -0
  31. package/templates/spa/views/default/spa/src/components/Navbar.vue +68 -0
  32. package/templates/spa/views/default/spa/src/components/Pagination.vue +166 -0
  33. package/templates/spa/views/default/spa/src/components/ToastContainer.vue +135 -0
  34. package/templates/spa/views/default/spa/src/composables/useApi.js +129 -0
  35. package/templates/spa/views/default/spa/src/composables/useClipboard.js +44 -0
  36. package/templates/spa/views/default/spa/src/composables/useDate.js +73 -0
  37. package/templates/spa/views/default/spa/src/composables/useDebounce.js +59 -0
  38. package/templates/spa/views/default/spa/src/composables/useFlash.js +46 -0
  39. package/templates/spa/views/default/spa/src/composables/useHeartbeat.js +45 -0
  40. package/templates/spa/views/default/spa/src/composables/useLocalStorage.js +43 -0
  41. package/templates/spa/views/default/spa/src/composables/useLocale.js +79 -0
  42. package/templates/spa/views/default/spa/src/composables/useWebSocket.js +93 -0
  43. package/templates/spa/views/default/spa/src/main.js +108 -0
  44. package/templates/spa/views/default/spa/src/plugins/alert.js +96 -0
  45. package/templates/spa/views/default/spa/src/plugins/toast.js +79 -0
  46. package/templates/spa/views/default/spa/src/router/index.js +29 -0
  47. package/templates/spa/views/default/spa/src/stores/auth.js +58 -0
  48. package/templates/spa/views/default/spa/src/views/BoardDetail.vue +169 -0
  49. package/templates/spa/views/default/spa/src/views/BoardForm.vue +192 -0
  50. package/templates/spa/views/default/spa/src/views/BoardList.vue +129 -0
  51. package/templates/spa/views/default/spa/src/views/ChatView.vue +327 -0
  52. package/templates/spa/views/default/spa/src/views/FeaturesView.vue +242 -0
  53. package/templates/spa/views/default/spa/src/views/HomeView.vue +215 -0
  54. package/templates/spa/views/default/spa/src/views/Login.vue +82 -0
  55. package/templates/spa/views/default/spa/src/views/Profile.vue +85 -0
  56. package/templates/spa/views/default/spa/src/views/Register.vue +84 -0
  57. package/templates/spa/views/default/spa/vite.config.js +28 -0
  58. package/templates/spa/views/default/spa/yarn.lock +633 -0
  59. package/templates/spa/ws/ChatHandler.js +7 -0
  60. package/templates/ssr/controllers/AuthController.js +119 -0
  61. package/templates/ssr/controllers/ChatController.js +15 -0
  62. package/templates/ssr/controllers/FeaturesController.js +15 -0
  63. package/templates/ssr/controllers/HomeController.js +21 -0
  64. package/templates/ssr/controllers/PostController.js +214 -0
  65. package/templates/ssr/controllers/UserController.js +48 -0
  66. package/templates/ssr/meta.json +11 -0
  67. package/templates/ssr/public/css/fx-ui.css +43 -0
  68. package/templates/ssr/public/css/landing.css +220 -0
  69. package/templates/ssr/public/css/style.css +1011 -0
  70. package/templates/ssr/public/js/fx-ui.js +124 -0
  71. package/templates/ssr/routes/web.js +46 -0
  72. package/templates/ssr/services/AuthService.js +48 -0
  73. package/templates/ssr/services/PostService.js +372 -0
  74. package/templates/ssr/services/UserService.js +48 -0
  75. package/templates/ssr/views/default/errors/404.html +11 -0
  76. package/templates/ssr/views/default/errors/500.html +48 -0
  77. package/templates/ssr/views/default/layouts/main.html +93 -0
  78. package/templates/ssr/views/default/pages/board/form.html +240 -0
  79. package/templates/ssr/views/default/pages/board/index.html +73 -0
  80. package/templates/ssr/views/default/pages/board/show.html +148 -0
  81. package/templates/ssr/views/default/pages/chat.html +288 -0
  82. package/templates/ssr/views/default/pages/features.html +373 -0
  83. package/templates/ssr/views/default/pages/home.html +258 -0
  84. package/templates/ssr/views/default/pages/login.html +27 -0
  85. package/templates/ssr/views/default/pages/profile.html +36 -0
  86. package/templates/ssr/views/default/pages/register.html +35 -0
  87. package/templates/ssr/views/default/partials/pagination.html +75 -0
  88. package/templates/ssr/ws/ChatHandler.js +138 -0
  89. package/templates/.env.example.tpl +0 -14
  90. package/templates/.gitignore.tpl +0 -5
  91. package/templates/fuzionx/controllers/HomeController.js +0 -13
  92. package/templates/fuzionx/routes/api.js.tpl +0 -7
  93. package/templates/fuzionx/routes/web.js.tpl +0 -5
  94. package/templates/fuzionx/views/default/layouts/main.html +0 -22
  95. package/templates/fuzionx/views/default/pages/home.html +0 -188
  96. package/templates/tester/views/default/errors/404.html +0 -15
  97. package/templates/tester/views/default/errors/500.html +0 -14
  98. /package/templates/{app.js.tpl → common/app.js.tpl} +0 -0
  99. /package/templates/{database → common/database}/models/User.js +0 -0
  100. /package/templates/{locales → common/locales}/en.json +0 -0
  101. /package/templates/{locales → common/locales}/ko.json +0 -0
  102. /package/templates/{shared → common/shared}/events/userEvents.js +0 -0
  103. /package/templates/{shared → common/shared}/jobs/CleanupJob.js +0 -0
  104. /package/templates/{shared → common/shared}/jobs/EmailTask.js +0 -0
  105. /package/templates/{shared → common/shared}/jobs/VideoPreviewTask.js +0 -0
  106. /package/templates/{shared → common/shared}/workers/heavy.js +0 -0
  107. /package/templates/{tester → common/tester}/controllers/FileController.js +0 -0
  108. /package/templates/{tester → common/tester}/controllers/HomeController.js +0 -0
  109. /package/templates/{tester → common/tester}/controllers/UserController.js +0 -0
  110. /package/templates/{tester → common/tester}/middleware/RequestLogger.js +0 -0
  111. /package/templates/{tester → common/tester}/routes/api.js +0 -0
  112. /package/templates/{tester → common/tester}/routes/web.js +0 -0
  113. /package/templates/{tester → common/tester}/services/UserService.js +0 -0
  114. /package/templates/{fuzionx → common/tester}/views/default/errors/404.html +0 -0
  115. /package/templates/{fuzionx → common/tester}/views/default/errors/500.html +0 -0
  116. /package/templates/{tester → common/tester}/views/default/layouts/main.html +0 -0
  117. /package/templates/{tester → common/tester}/views/default/pages/home.html +0 -0
  118. /package/templates/{tester → common/tester}/views/default/pages/i18n.html +0 -0
  119. /package/templates/{tester → common/tester}/views/default/pages/upload.html +0 -0
  120. /package/templates/{tester → common/tester}/views/default/pages/websocket.html +0 -0
  121. /package/templates/{tester → common/tester}/views/default/partials/footer.html +0 -0
  122. /package/templates/{tester → common/tester}/views/default/partials/header.html +0 -0
  123. /package/templates/{tester → common/tester}/ws/ChatHandler.js +0 -0
package/index.js CHANGED
@@ -25,51 +25,37 @@ async function loadTemplate(relPath, vars) {
25
25
  return render(raw, vars);
26
26
  }
27
27
 
28
- /** 디렉토리 재귀 복사 */
29
- async function copyDirRecursive(src, dst) {
28
+ /** 디렉토리 재귀 복사 — .tpl 파일은 변수 치환 */
29
+ async function copyDirRecursive(src, dst, vars = {}) {
30
30
  await fs.mkdir(dst, { recursive: true });
31
31
  const entries = await fs.readdir(src, { withFileTypes: true });
32
32
  for (const entry of entries) {
33
33
  const srcPath = path.join(src, entry.name);
34
34
  const dstPath = path.join(dst, entry.name);
35
35
  if (entry.isDirectory()) {
36
- await copyDirRecursive(srcPath, dstPath);
36
+ await copyDirRecursive(srcPath, dstPath, vars);
37
+ } else if (entry.name === 'meta.json') {
38
+ // meta.json은 스캐폴딩에 포함하지 않음
39
+ continue;
40
+ } else if (entry.name.endsWith('.tpl')) {
41
+ // .tpl 파일은 변수 치환 후 확장자 제거
42
+ const content = await fs.readFile(srcPath, 'utf-8');
43
+ const rendered = render(content, vars);
44
+ const destName = entry.name.replace(/\.tpl$/, '');
45
+ await fs.writeFile(path.join(dst, destName), rendered);
37
46
  } else {
38
47
  await fs.copyFile(srcPath, dstPath);
39
48
  }
40
49
  }
41
50
  }
42
51
 
43
- // ── 스캐폴딩 파일 목록 (fuzionx + tester 2-app 구조) ──
52
+ // ── 디렉토리 (.gitkeep 포함) ──
44
53
 
45
- const APP_FILES = [
46
- { tpl: 'package.json.tpl', dest: 'package.json' },
47
- { tpl: 'fuzionx.yaml.tpl', dest: 'fuzionx.yaml' },
48
- { tpl: 'app.js.tpl', dest: 'app.js' },
49
- { tpl: '.env.example.tpl', dest: '.env.example' },
50
- { tpl: '.env.example.tpl', dest: '.env' },
51
- { tpl: '.gitignore.tpl', dest: '.gitignore' },
52
- ];
53
-
54
- /** fuzionx 앱 — .tpl 파일 (치환 필요) */
55
- const FUZIONX_TPL_FILES = [
56
- { tpl: 'fuzionx/routes/web.js.tpl', dest: 'app/fuzionx/routes/web.js' },
57
- { tpl: 'fuzionx/routes/api.js.tpl', dest: 'app/fuzionx/routes/api.js' },
58
- ];
59
-
60
- /** 빈 디렉토리 (.gitkeep 포함) */
61
- const APP_DIRS = [
62
- // fuzionx 앱
63
- 'app/fuzionx/services',
64
- 'app/fuzionx/middleware',
65
- 'app/fuzionx/ws',
66
- // 인프라
54
+ const EMPTY_DIRS = [
67
55
  'database/migrations',
68
56
  'database/seeds',
69
57
  'storage/logs',
70
58
  'storage/uploads',
71
- 'public/css',
72
- 'public/js',
73
59
  'tests',
74
60
  ];
75
61
 
@@ -77,14 +63,24 @@ const APP_DIRS = [
77
63
 
78
64
  async function createApp(name, targetDir, type = 'spa') {
79
65
  const dir = targetDir || path.resolve(name);
80
- const appName = type; // 앱 이름은 타입에 따라 고정
66
+ const appName = type; // 앱 디렉토리명은 타입과 동일
81
67
  const vars = {
82
68
  name,
83
69
  dbName: name.replace(/-/g, '_'),
84
70
  };
85
71
 
86
- // 디렉토리 생성 (.gitkeep 포함)
87
- for (const d of APP_DIRS) {
72
+ const commonDir = path.join(TPL_DIR, 'common');
73
+ const typeDir = path.join(TPL_DIR, type);
74
+
75
+ // meta.json 로드
76
+ let meta = {};
77
+ try {
78
+ const metaRaw = await fs.readFile(path.join(typeDir, 'meta.json'), 'utf-8');
79
+ meta = JSON.parse(metaRaw);
80
+ } catch { /* meta.json 없어도 진행 */ }
81
+
82
+ // 1. 빈 디렉토리 생성
83
+ for (const d of EMPTY_DIRS) {
88
84
  const fullDir = path.join(dir, d);
89
85
  await fs.mkdir(fullDir, { recursive: true });
90
86
  const files = await fs.readdir(fullDir).catch(() => []);
@@ -93,57 +89,64 @@ async function createApp(name, targetDir, type = 'spa') {
93
89
  }
94
90
  }
95
91
 
96
- // 루트 템플릿 파일 생성 (.tpl 치환)
97
- for (const { tpl, dest } of APP_FILES) {
98
- const content = await loadTemplate(tpl, vars);
99
- const fullPath = path.join(dir, dest);
100
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
101
- await fs.writeFile(fullPath, content);
92
+ // 전용 디렉토리
93
+ for (const d of ['services', 'middleware', 'ws']) {
94
+ const fullDir = path.join(dir, `app/${appName}`, d);
95
+ await fs.mkdir(fullDir, { recursive: true });
96
+ const files = await fs.readdir(fullDir).catch(() => []);
97
+ if (files.length === 0) {
98
+ await fs.writeFile(path.join(fullDir, '.gitkeep'), '');
99
+ }
100
+ }
101
+
102
+ // 2. common/ 루트 .tpl 파일 → 프로젝트 루트
103
+ const commonEntries = await fs.readdir(commonDir, { withFileTypes: true });
104
+ for (const entry of commonEntries) {
105
+ if (entry.isFile() && entry.name.endsWith('.tpl')) {
106
+ const content = await fs.readFile(path.join(commonDir, entry.name), 'utf-8');
107
+ const rendered = render(content, vars);
108
+ const destName = entry.name.replace(/\.tpl$/, '');
109
+ await fs.writeFile(path.join(dir, destName), rendered);
110
+ }
111
+ }
112
+
113
+ // 3. common/ 하위 디렉토리 복사 (database, locales, shared)
114
+ for (const entry of commonEntries) {
115
+ if (!entry.isDirectory()) continue;
116
+ if (entry.name === 'tester') continue; // tester는 별도 처리
117
+ await copyDirRecursive(
118
+ path.join(commonDir, entry.name),
119
+ path.join(dir, entry.name),
120
+ vars,
121
+ );
102
122
  }
103
123
 
104
- // fuzionx .tpl 파일 (치환 필요)
105
- for (const { tpl, dest } of FUZIONX_TPL_FILES) {
106
- const content = await loadTemplate(tpl, vars);
107
- const actualDest = dest.replace('app/fuzionx/', `app/${appName}/`);
108
- const fullPath = path.join(dir, actualDest);
109
- await fs.mkdir(path.dirname(fullPath), { recursive: true });
110
- await fs.writeFile(fullPath, content);
124
+ // 4. tester 복사 (common/tester/ app/tester/)
125
+ const testerSrc = path.join(commonDir, 'tester');
126
+ try {
127
+ await fs.access(testerSrc);
128
+ await copyDirRecursive(testerSrc, path.join(dir, 'app/tester'), vars);
129
+ } catch { /* tester 없으면 스킵 */ }
130
+
131
+ // 5. 타입별 템플릿 복사 → app/{type}/
132
+ // controllers, services, middleware, routes, ws, views
133
+ const typeEntries = await fs.readdir(typeDir, { withFileTypes: true });
134
+ for (const entry of typeEntries) {
135
+ if (!entry.isDirectory()) continue;
136
+ if (entry.name === 'public') continue; // public은 프로젝트 루트로 복사
137
+ await copyDirRecursive(
138
+ path.join(typeDir, entry.name),
139
+ path.join(dir, `app/${appName}`, entry.name),
140
+ vars,
141
+ );
111
142
  }
112
143
 
113
- // fuzionx 직접 복사 (controllers, views)
114
- const fuzionxSrc = path.join(TPL_DIR, 'fuzionx');
115
- await copyDirRecursive(
116
- path.join(fuzionxSrc, 'controllers'),
117
- path.join(dir, `app/${appName}/controllers`),
118
- );
119
- await copyDirRecursive(
120
- path.join(fuzionxSrc, 'views'),
121
- path.join(dir, `app/${appName}/views`),
122
- );
123
-
124
- // tester 앱 — 전체 복사
125
- await copyDirRecursive(
126
- path.join(TPL_DIR, 'tester'),
127
- path.join(dir, 'app/tester'),
128
- );
129
-
130
- // shared — 전체 복사
131
- await copyDirRecursive(
132
- path.join(TPL_DIR, 'shared'),
133
- path.join(dir, 'shared'),
134
- );
135
-
136
- // database/models — 복사
137
- await copyDirRecursive(
138
- path.join(TPL_DIR, 'database'),
139
- path.join(dir, 'database'),
140
- );
141
-
142
- // locales — 복사
143
- await copyDirRecursive(
144
- path.join(TPL_DIR, 'locales'),
145
- path.join(dir, 'locales'),
146
- );
144
+ // 6. public/ 디렉토리 복사 (SSR의 경우 CSS/JS assets)
145
+ const publicSrc = path.join(typeDir, 'public');
146
+ try {
147
+ await fs.access(publicSrc);
148
+ await copyDirRecursive(publicSrc, path.join(dir, 'public'), vars);
149
+ } catch { /* public 없으면 스킵 */ }
147
150
 
148
151
  return dir;
149
152
  }
@@ -175,6 +178,7 @@ if (!validTypes.includes(type)) {
175
178
 
176
179
  try {
177
180
  const dir = await createApp(name, null, type);
181
+ const nextCmd = type === 'spa' ? 'npx fx dev:spa' : 'npx fx dev';
178
182
  console.log(`
179
183
  ✅ Created ${name} at ${dir} (type: ${type})
180
184
 
@@ -182,7 +186,8 @@ try {
182
186
 
183
187
  cd ${name}
184
188
  npm install
185
- npx fx dev${type === 'spa' ? ':spa' : ''}
189
+ ${type === 'spa' ? `cd app/spa/views/default/spa && npm install && cd ../../../../..
190
+ ` : ''}${nextCmd}
186
191
  `);
187
192
  } catch (err) {
188
193
  console.error(`❌ Failed to create app: ${err.message}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-fuzionx",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
4
4
  "description": "Create a new FuzionX application — npx create-fuzionx my-app",
5
5
  "type": "module",
6
6
  "bin": {
@@ -87,6 +87,8 @@ bridge:
87
87
  static:
88
88
  - url: /public
89
89
  path: ./public
90
+ - url: /wasm
91
+ path: ./node_modules/@fuzionx/client
90
92
 
91
93
  # ── 로깅 ──
92
94
  logging:
@@ -125,7 +127,7 @@ bridge:
125
127
 
126
128
  # ── ASP 암호화 ──
127
129
  asp:
128
- enabled: false
130
+ enabled: true
129
131
  master_secret: "${ASP_SECRET:change-me-in-production}"
130
132
  header_signal: Ruxy-Enc-Mode
131
133
 
@@ -9,8 +9,8 @@
9
9
  "test": "vitest run"
10
10
  },
11
11
  "dependencies": {
12
- "@fuzionx/framework": "^0.1.31",
13
- "@fuzionx/client": "^0.1.30",
12
+ "@fuzionx/framework": "^0.1.32",
13
+ "@fuzionx/client": "^0.1.32",
14
14
  "joi": "^18.1.1"
15
15
  },
16
16
  "devDependencies": {
@@ -0,0 +1,114 @@
1
+ import { Controller } from '@fuzionx/framework';
2
+
3
+ /**
4
+ * SPA AuthController — JSON API 전용 인증
5
+ *
6
+ * 모든 페이지는 Vue에서 렌더링. 서버는 API만 제공.
7
+ * 세션 기반 인증. JSON 요청/응답.
8
+ */
9
+ export default class AuthController extends Controller {
10
+ /** @type {import('@fuzionx/framework').RouteHandler} 로그인 API */
11
+ static login;
12
+ /** @type {import('@fuzionx/framework').RouteHandler} 회원가입 API */
13
+ static register;
14
+ /** @type {import('@fuzionx/framework').RouteHandler} 로그아웃 API */
15
+ static logout;
16
+ /** @type {import('@fuzionx/framework').RouteHandler} 인증 상태 확인 API */
17
+ static check;
18
+ /** @type {import('@fuzionx/framework').RouteHandler} 하트비트 (세션 연장) */
19
+ static heartbeat;
20
+
21
+ /**
22
+ * POST /api/auth/login — 로그인
23
+ *
24
+ * email/password 검증 후 세션에 userId 저장.
25
+ * 성공 → { user }, 실패 → 401 { error }.
26
+ *
27
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
28
+ * @returns {void}
29
+ */
30
+ async login(ctx) {
31
+ const { email, password } = ctx.body;
32
+ const user = await this.service('AuthService').login({ email, password });
33
+
34
+ if (!user) {
35
+ return ctx.status(401).json({ error: ctx.t('auth.login_failed') });
36
+ }
37
+
38
+ ctx.session.set('userId', user.id);
39
+ ctx.json({ user: { id: user.id, name: user.name, email: user.email, role: user.role } });
40
+ }
41
+
42
+ /**
43
+ * POST /api/auth/register — 회원가입
44
+ *
45
+ * name/email/password/password_confirm 검증.
46
+ * 성공 → 201 { user }, 실패 → 400 { error }.
47
+ *
48
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
49
+ * @returns {void}
50
+ */
51
+ async register(ctx) {
52
+ const { name, email, password, password_confirm } = ctx.body;
53
+
54
+ if (password !== password_confirm) {
55
+ return ctx.status(400).json({ error: ctx.t('auth.password_mismatch') });
56
+ }
57
+
58
+ try {
59
+ const user = await this.service('AuthService').register({ name, email, password });
60
+ ctx.session.set('userId', user.id);
61
+ ctx.status(201).json({ user: { id: user.id, name: user.name, email: user.email } });
62
+ } catch (e) {
63
+ ctx.status(e.status || 400).json({ error: ctx.t(e.message) || e.message });
64
+ }
65
+ }
66
+
67
+ /**
68
+ * POST /api/auth/logout — 로그아웃
69
+ *
70
+ * 세션 파기 후 { success: true } 반환.
71
+ *
72
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
73
+ * @returns {void}
74
+ */
75
+ async logout(ctx) {
76
+ ctx.session.destroy();
77
+ ctx.json({ success: true });
78
+ }
79
+
80
+ /**
81
+ * GET /api/auth/check — 인증 상태 확인
82
+ *
83
+ * 세션에 userId 존재 → DB 조회 → { authenticated, user }.
84
+ * 미인증 시 { authenticated: false, user: null }.
85
+ *
86
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
87
+ * @returns {void}
88
+ */
89
+ async check(ctx) {
90
+ const userId = ctx.session.get('userId');
91
+ if (!userId) return ctx.json({ authenticated: false, user: null });
92
+
93
+ try {
94
+ const user = await this.db.User.find(userId);
95
+ if (!user) return ctx.json({ authenticated: false, user: null });
96
+ ctx.json({ authenticated: true, user: user.toJSON() });
97
+ } catch {
98
+ ctx.json({ authenticated: false, user: null });
99
+ }
100
+ }
101
+
102
+ /**
103
+ * GET /api/heartbeat — 세션 연장 (하트비트)
104
+ *
105
+ * 인증된 사용자의 세션 유지. { alive, user }.
106
+ *
107
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
108
+ * @returns {void}
109
+ */
110
+ async heartbeat(ctx) {
111
+ if (!ctx.user) return ctx.status(401).json({ alive: false });
112
+ ctx.json({ alive: true, user: { id: ctx.user.id } });
113
+ }
114
+ }
@@ -0,0 +1,68 @@
1
+ import { Controller } from '@fuzionx/framework';
2
+
3
+ /**
4
+ * SPA HomeController — Vue 셸 렌더링
5
+ *
6
+ * 모든 프론트엔드 라우트에 대해 Vue 앱 셸을 서빙.
7
+ * 인증 여부와 관계없이 셸을 렌더링하며,
8
+ * 유저 데이터를 ASP 암호화하여 Vue에 전달.
9
+ * Vue가 user=null이면 로그인 화면, 아니면 대시보드를 표시.
10
+ *
11
+ * bridge.cryptoEncryptCustom(key, plaintext) → WASM decrypt_custom(key, ciphertext)
12
+ */
13
+ export default class HomeController extends Controller {
14
+ /** @type {import('@fuzionx/framework').RouteHandler} SPA 셸 렌더링 */
15
+ static index;
16
+
17
+ /**
18
+ * GET / | /* — Vue SPA 셸 렌더링
19
+ *
20
+ * 세션에서 유저 조회 후 ASP 암호화된 payload와 함께 렌더링.
21
+ * payload: { user, locale, isDev, asp, app }
22
+ *
23
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
24
+ * @returns {void}
25
+ */
26
+ async index(ctx) {
27
+ const clientSecret = this.config.get('app.client_secret');
28
+ const bridge = this.app._bridge;
29
+
30
+ // ASP config에서 masterSecret 가져오기
31
+ const aspConfig = JSON.parse(bridge.getAspConfig());
32
+ const masterSecret = aspConfig.masterSecret || '';
33
+
34
+ // 세션에서 유저 조회 (인증 안 되어 있으면 null)
35
+ let user = null;
36
+ const userId = ctx.session?.get('userId');
37
+ if (userId && this.db?.User) {
38
+ try {
39
+ const u = await this.db.User.find(userId);
40
+ if (u) user = { id: u.id, name: u.name, email: u.email, role: u.role };
41
+ } catch {}
42
+ }
43
+
44
+ const isDev = this.config.get('app.environment') === 'development';
45
+
46
+ // SPA에 전달할 payload
47
+ const payload = {
48
+ user,
49
+ locale: ctx.locale,
50
+ locales: this.app?.i18n?.locales?.() || [],
51
+ translations: ctx.t.all(),
52
+ isDev,
53
+ asp: { headerSignal: aspConfig.headerSignal || 'Ruxy-Enc-Mode' },
54
+ app: { name: this.config.get('app.name'), theme: this.config.get('app.themes.default') },
55
+ };
56
+
57
+ // 암호화 (bridge crypto_encrypt_custom — WASM decrypt_custom과 호환)
58
+ const encryptedPayload = bridge.cryptoEncryptCustom(clientSecret, JSON.stringify(payload));
59
+ const encryptedSecret = bridge.cryptoEncryptCustom(clientSecret, masterSecret);
60
+
61
+ ctx.render('home', {
62
+ __fx__: encryptedPayload,
63
+ __fx_secret__: encryptedSecret,
64
+ client_secret: clientSecret,
65
+ isDev,
66
+ });
67
+ }
68
+ }
@@ -0,0 +1,191 @@
1
+ import { Controller, DateUtil } from '@fuzionx/framework';
2
+
3
+ /**
4
+ * SPA PostController — 게시판 REST API
5
+ *
6
+ * RESTful CRUD. JSON 요청/응답.
7
+ * r.resource('posts', PostController) 로 자동 라우트 등록.
8
+ */
9
+ export default class PostController extends Controller {
10
+ /** @type {import('@fuzionx/framework').RouteHandler} 게시글 목록 조회 */
11
+ static index;
12
+ /** @type {import('@fuzionx/framework').RouteHandler} 게시글 상세 조회 */
13
+ static show;
14
+ /** @type {import('@fuzionx/framework').RouteHandler} 게시글 작성 */
15
+ static store;
16
+ /** @type {import('@fuzionx/framework').RouteHandler} 게시글 수정 */
17
+ static update;
18
+ /** @type {import('@fuzionx/framework').RouteHandler} 게시글 삭제 */
19
+ static destroy;
20
+
21
+ /**
22
+ * GET /api/posts — 게시글 목록 (페이지네이션)
23
+ *
24
+ * query.page로 페이지 결정. 10건씩 조회.
25
+ * 응답: { data, page, lastPage, hasMore, total, perPage }
26
+ *
27
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
28
+ * @returns {void}
29
+ */
30
+ async index(ctx) {
31
+ const page = parseInt(ctx.query.page || '1');
32
+ const result = await this.service('PostService').list(page, 10);
33
+
34
+ // 게시글 목록의 대표 썸네일 한 번에 조회 (N+1 방지)
35
+ const postIds = result.data.map(p => p.id);
36
+ const thumbMap = await this.service('PostService').getPostThumbnails(postIds);
37
+
38
+ // 작성자 이름 batch 조회 (N+1 방지)
39
+ const userIds = [...new Set(result.data.map(p => p.user_id).filter(Boolean))];
40
+ const userMap = new Map();
41
+ if (userIds.length) {
42
+ const users = await this.db.User.query().whereIn('id', userIds).get();
43
+ for (const u of users) userMap.set(u.id, u.name);
44
+ }
45
+
46
+ // 각 게시글에 thumbUrl, user_name, 포맷된 날짜 추가
47
+ const posts = result.data.map(p => ({
48
+ ...p,
49
+ thumbUrl: thumbMap.get(p.id) || null,
50
+ user_name: userMap.get(p.user_id) || '-',
51
+ created_at: DateUtil.format(p.created_at, 'YYYY-MM-DD HH:mm'),
52
+ }));
53
+
54
+ ctx.json({
55
+ data: posts,
56
+ page: result.page,
57
+ lastPage: result.lastPage,
58
+ hasMore: result.hasMore,
59
+ total: result.total,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * GET /api/posts/:id — 게시글 상세 조회
65
+ *
66
+ * 게시글 + 작성자 정보 반환. 미존재 시 404.
67
+ * 응답: { post, author }
68
+ *
69
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
70
+ * @returns {void}
71
+ */
72
+ async show(ctx) {
73
+ const postService = this.service('PostService');
74
+ const post = await postService.find(ctx.params.id);
75
+ if (!post) return ctx.status(404).json({ error: ctx.t('post.not_found') });
76
+
77
+ const author = await this.db.User.find(post.user_id);
78
+ const files = await postService.getAttachmentsWithThumbs(post.id);
79
+
80
+ ctx.json({
81
+ post: { ...post, created_at: DateUtil.format(post.created_at, 'YYYY-MM-DD HH:mm') },
82
+ author: author ? { id: author.id, name: author.name } : null,
83
+ files,
84
+ });
85
+ }
86
+
87
+ /**
88
+ * POST /api/posts — 게시글 작성
89
+ *
90
+ * JSON body에서 title/content 추출. 현재 사용자의 user_id 자동 설정.
91
+ * 응답: 201 { post }
92
+ *
93
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
94
+ * @returns {void}
95
+ */
96
+ async store(ctx) {
97
+ // 업로드 오류 처리 (파일 타입/크기 제한 등)
98
+ if (ctx.uploadError) {
99
+ return ctx.status(400).json({ error: ctx.uploadError });
100
+ }
101
+ const { title, content } = ctx.body;
102
+ const uploadedFiles = ctx.files || [];
103
+ const post = await this.service('PostService').create(
104
+ { title, content, user_id: ctx.user.id },
105
+ uploadedFiles,
106
+ );
107
+ ctx.status(201).json({ post });
108
+ }
109
+
110
+ /**
111
+ * PUT /api/posts/:id — 게시글 수정
112
+ *
113
+ * 작성자 본인만 수정 가능. 권한 없으면 403.
114
+ * 응답: { post }
115
+ *
116
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
117
+ * @returns {void}
118
+ */
119
+ async update(ctx) {
120
+ // 업로드 오류 처리
121
+ if (ctx.uploadError) {
122
+ return ctx.status(400).json({ error: ctx.uploadError });
123
+ }
124
+ const post = await this.service('PostService').find(ctx.params.id);
125
+ if (!post || post.user_id !== ctx.user.id) {
126
+ return ctx.status(403).json({ error: ctx.t('common.forbidden') });
127
+ }
128
+ const { title, content } = ctx.body;
129
+ const uploadedFiles = ctx.files || [];
130
+ await this.service('PostService').update(ctx.params.id, { title, content }, uploadedFiles);
131
+ const updated = await this.service('PostService').find(ctx.params.id);
132
+ ctx.json({ post: updated });
133
+ }
134
+
135
+ /**
136
+ * DELETE /api/posts/:id — 게시글 삭제
137
+ *
138
+ * 작성자 본인만 삭제 가능. 권한 없으면 403.
139
+ * 응답: { deleted: true }
140
+ *
141
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
142
+ * @returns {void}
143
+ */
144
+ async destroy(ctx) {
145
+ const post = await this.service('PostService').find(ctx.params.id);
146
+ if (!post || post.user_id !== ctx.user.id) return ctx.status(403).json({ error: ctx.t('common.forbidden') });
147
+ await this.service('PostService').remove(ctx.params.id);
148
+ ctx.json({ deleted: true });
149
+ }
150
+
151
+ /**
152
+ * GET /api/posts/status?ids=1,2,3 — 게시글 상태 JSON 반환
153
+ *
154
+ * processing 상태 폴링용. SSR PostController.status와 동일.
155
+ * 응답: { statuses: { 1: 'published', 2: 'processing' } }
156
+ *
157
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
158
+ */
159
+ async status(ctx) {
160
+ const raw = ctx.query.ids || '';
161
+ const ids = raw.split(',').map(Number).filter(Boolean);
162
+ if (!ids.length) return ctx.json({ statuses: {} });
163
+
164
+ const posts = await this.db.Post.query().whereIn('id', ids).get();
165
+ const statuses = {};
166
+ for (const p of posts) {
167
+ statuses[p.id] = p.status || 'published';
168
+ }
169
+ ctx.json({ statuses });
170
+ }
171
+
172
+ /**
173
+ * DELETE /api/posts/attachment/:id — 개별 첨부파일 삭제
174
+ *
175
+ * 수정 화면에서 기존 첨부파일 개별 삭제.
176
+ * 작성자 본인만 삭제 가능.
177
+ *
178
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
179
+ */
180
+ async deleteAttachment(ctx) {
181
+ const att = await this.db.Attachment.find(ctx.params.id);
182
+ if (!att) return ctx.status(404).json({ error: 'Not found' });
183
+
184
+ const post = await this.db.Post.find(att.post_id);
185
+ if (!post || post.user_id !== ctx.user.id) return ctx.status(403).json({ error: 'Forbidden' });
186
+
187
+ await this.service('PostService').removeAttachment(att.id);
188
+ ctx.json({ deleted: true });
189
+ }
190
+
191
+ }
@@ -0,0 +1,43 @@
1
+ import { Controller } from '@fuzionx/framework';
2
+
3
+ /**
4
+ * SPA UserController — 사용자 프로필 REST API
5
+ *
6
+ * 프로필 조회/수정. JSON 요청/응답.
7
+ */
8
+ export default class UserController extends Controller {
9
+ /** @type {import('@fuzionx/framework').RouteHandler} 프로필 조회 */
10
+ static profile;
11
+ /** @type {import('@fuzionx/framework').RouteHandler} 프로필 수정 */
12
+ static updateProfile;
13
+
14
+ /**
15
+ * GET /api/user/profile — 프로필 조회
16
+ *
17
+ * 인증된 사용자의 기본 정보 반환.
18
+ * 응답: { user: { id, name, email, role } }
19
+ *
20
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
21
+ * @returns {void}
22
+ */
23
+ async profile(ctx) {
24
+ const { id, name, email, role } = ctx.user;
25
+ ctx.json({ user: { id, name, email, role } });
26
+ }
27
+
28
+ /**
29
+ * PUT /api/user/profile — 프로필 수정
30
+ *
31
+ * JSON body에서 name/email/password 추출.
32
+ * UserService.update() 호출 후 갱신된 사용자 정보 반환.
33
+ * 응답: { user: { id, name, email, role } }
34
+ *
35
+ * @param {import('@fuzionx/framework').Context} ctx - 요청 컨텍스트
36
+ * @returns {void}
37
+ */
38
+ async updateProfile(ctx) {
39
+ const { name, email, password } = ctx.body;
40
+ const user = await this.service('UserService').update(ctx.user.id, { name, email, password });
41
+ ctx.json({ user: { id: user.id, name: user.name, email: user.email, role: user.role } });
42
+ }
43
+ }