create-tigra 3.3.0 → 4.0.1

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 (207) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +264 -56
  3. package/bin/create-tigra.js +497 -472
  4. package/lib/patchers/email-verification.patcher.js +72 -10
  5. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  6. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  7. package/modules/email-verification/server/verification.controller.ts +3 -1
  8. package/modules/email-verification/server/verification.service.ts +44 -13
  9. package/package.json +5 -3
  10. package/template/.github/dependabot.yml +47 -0
  11. package/template/.github/workflows/audit.yml +36 -0
  12. package/template/.github/workflows/ci.yml +79 -0
  13. package/template/AGENTS.md +18 -9
  14. package/template/README.md +79 -0
  15. package/template/client/.dockerignore +1 -0
  16. package/template/client/.env.example.production +13 -2
  17. package/template/client/AGENTS.md +13 -5
  18. package/template/client/Dockerfile +186 -14
  19. package/template/client/README.md +92 -21
  20. package/template/client/next.config.ts +1 -1
  21. package/template/client/package-lock.json +15983 -14181
  22. package/template/client/package.json +56 -48
  23. package/template/client/scripts/check-sharp.mjs +53 -0
  24. package/template/client/scripts/next-dev.cjs +5 -1
  25. package/template/client/src/__tests__/proxy.test.ts +92 -0
  26. package/template/client/src/app/healthz/route.ts +16 -0
  27. package/template/client/src/app/layout.tsx +9 -3
  28. package/template/client/src/app/page.tsx +2 -2
  29. package/template/client/src/app/providers.tsx +23 -4
  30. package/template/client/src/components/layout/Header.tsx +7 -3
  31. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  32. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  33. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  34. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  35. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  36. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  37. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  38. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  39. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  40. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  41. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  42. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  43. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  44. package/template/client/src/lib/api/api.types.ts +14 -0
  45. package/template/client/src/lib/api/axios.config.ts +101 -15
  46. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  47. package/template/client/src/lib/api/session-events.ts +29 -0
  48. package/template/client/src/lib/constants/routes.ts +12 -0
  49. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  50. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  51. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  52. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  53. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  54. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  55. package/template/client/src/lib/utils/error.ts +81 -0
  56. package/template/client/src/lib/utils/form.ts +31 -0
  57. package/template/client/src/lib/utils/paths.ts +18 -0
  58. package/template/client/src/lib/utils/session-marker.ts +24 -0
  59. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  60. package/template/client/src/store/__tests__/store.test.ts +44 -0
  61. package/template/client/src/store/index.ts +26 -8
  62. package/template/client/vitest.config.mts +48 -0
  63. package/template/server/.env.example +280 -270
  64. package/template/server/.env.example.production +283 -242
  65. package/template/server/AGENTS.md +13 -4
  66. package/template/server/Dockerfile +176 -14
  67. package/template/server/README.md +108 -0
  68. package/template/server/docker-compose.yml +4 -2
  69. package/template/server/docs/deployment.md +63 -0
  70. package/template/server/docs/logging.md +66 -4
  71. package/template/server/docs/rate-limits.md +153 -0
  72. package/template/server/docs/testing.md +81 -0
  73. package/template/server/eslint.config.mjs +19 -0
  74. package/template/server/package-lock.json +8784 -8743
  75. package/template/server/package.json +79 -75
  76. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  77. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  78. package/template/server/prisma/schema.prisma +0 -3
  79. package/template/server/scripts/check-heic.mjs +40 -0
  80. package/template/server/scripts/check-sharp.mjs +53 -0
  81. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  82. package/template/server/src/app.ts +248 -346
  83. package/template/server/src/config/__tests__/env.test.ts +219 -0
  84. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  85. package/template/server/src/config/env.ts +326 -182
  86. package/template/server/src/config/rate-limit.config.ts +157 -106
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  90. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  91. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  92. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  93. package/template/server/src/jobs/index.ts +12 -2
  94. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  95. package/template/server/src/jobs/schedule.ts +50 -0
  96. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  97. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  98. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  99. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  100. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  101. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  102. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  103. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  104. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  105. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  106. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  107. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  108. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  109. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  110. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  111. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  112. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  113. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  114. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  115. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  116. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  117. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  118. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  119. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  120. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  121. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  122. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  123. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  124. package/template/server/src/libs/auth.ts +39 -10
  125. package/template/server/src/libs/client-ip.ts +158 -77
  126. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  127. package/template/server/src/libs/cookies.ts +53 -14
  128. package/template/server/src/libs/email-quota.ts +74 -0
  129. package/template/server/src/libs/email.ts +46 -9
  130. package/template/server/src/libs/error-handler.ts +111 -0
  131. package/template/server/src/libs/health-routes.ts +53 -0
  132. package/template/server/src/libs/http.ts +139 -47
  133. package/template/server/src/libs/ip-address.ts +37 -0
  134. package/template/server/src/libs/ip-block.ts +284 -221
  135. package/template/server/src/libs/logger.ts +41 -12
  136. package/template/server/src/libs/monitoring.ts +127 -41
  137. package/template/server/src/libs/observability/sentry.ts +1 -1
  138. package/template/server/src/libs/origin-check.ts +9 -7
  139. package/template/server/src/libs/prisma.ts +47 -4
  140. package/template/server/src/libs/query-counter.ts +71 -59
  141. package/template/server/src/libs/rate-limiting.ts +110 -0
  142. package/template/server/src/libs/redis-required.ts +28 -0
  143. package/template/server/src/libs/redis.ts +27 -1
  144. package/template/server/src/libs/request-id.ts +18 -0
  145. package/template/server/src/libs/requestLogger.ts +112 -17
  146. package/template/server/src/libs/safe-http.ts +101 -0
  147. package/template/server/src/libs/shutdown.ts +87 -0
  148. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  149. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  150. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  151. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  152. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  153. package/template/server/src/libs/storage/file-validator.ts +48 -46
  154. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  155. package/template/server/src/libs/token-hash.ts +18 -0
  156. package/template/server/src/libs/url-safety.ts +127 -121
  157. package/template/server/src/libs/validation-errors.ts +86 -0
  158. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  159. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  160. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  161. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  162. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  163. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  164. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  165. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  166. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  167. package/template/server/src/modules/admin/admin.service.ts +66 -4
  168. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  170. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  171. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  172. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  173. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  174. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  175. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  176. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  177. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  178. package/template/server/src/modules/auth/auth.service.ts +167 -96
  179. package/template/server/src/modules/auth/session.repo.ts +12 -0
  180. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  181. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  182. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  183. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  184. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  185. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  186. package/template/server/src/modules/users/users.controller.ts +9 -38
  187. package/template/server/src/modules/users/users.repo.ts +23 -7
  188. package/template/server/src/modules/users/users.routes.ts +3 -22
  189. package/template/server/src/modules/users/users.schemas.ts +15 -9
  190. package/template/server/src/modules/users/users.service.ts +105 -93
  191. package/template/server/src/scripts/make-admin.ts +48 -0
  192. package/template/server/src/server.ts +48 -26
  193. package/template/server/src/shared/errors/AppError.ts +27 -1
  194. package/template/server/src/shared/errors/errors.ts +42 -5
  195. package/template/server/src/shared/responses/successResponse.ts +22 -3
  196. package/template/server/src/shared/types/index.ts +7 -0
  197. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  198. package/template/server/src/test/integration-helpers.ts +343 -0
  199. package/template/server/src/test/integration-services.ts +74 -0
  200. package/template/server/src/test/integration.global-setup.ts +144 -0
  201. package/template/server/src/test/integration.setup.ts +35 -158
  202. package/template/server/src/test/setup.ts +3 -10
  203. package/template/server/tsconfig.build.json +1 -1
  204. package/template/server/tsconfig.json +1 -0
  205. package/template/server/vitest.config.ts +17 -4
  206. package/template/server/vitest.integration.config.ts +18 -13
  207. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,472 +1,497 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import prompts from 'prompts';
5
- import chalk from 'chalk';
6
- import ora from 'ora';
7
- import fs from 'fs-extra';
8
- import path from 'path';
9
- import { fileURLToPath } from 'url';
10
- import crypto from 'crypto';
11
-
12
- const __filename = fileURLToPath(import.meta.url);
13
- const __dirname = path.dirname(__filename);
14
-
15
- const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
16
- const VERSION = packageJson.version;
17
-
18
- const TEMPLATE_DIR = path.join(__dirname, '..', 'template');
19
-
20
- // Non-secret placeholder written into the COMMITTED server/.env.example.
21
- // The real secret replaces it only in the git-ignored server/.env.
22
- const JWT_SECRET_PLACEHOLDER = 'CHANGE_ME_generate_with_openssl_rand_hex_48';
23
-
24
- // Files that contain template variables and need replacement
25
- const FILES_TO_REPLACE = [
26
- 'AGENTS.md',
27
- 'server/package.json',
28
- 'server/.env.example',
29
- 'server/docker-compose.yml',
30
- 'client/package.json',
31
- 'client/.env.example',
32
- 'client/.env.example.production',
33
- 'server/postman/collection.json',
34
- 'server/postman/environment.json',
35
- ];
36
-
37
- // Directories/files to skip when copying
38
- const SKIP_PATTERNS = [
39
- 'node_modules',
40
- '.next',
41
- 'dist',
42
- 'out',
43
- '.env',
44
- '.env.local',
45
- '.env.*.local',
46
- 'package-lock.json',
47
- 'pnpm-lock.yaml',
48
- 'yarn.lock',
49
- ];
50
-
51
- function toKebabCase(str) {
52
- return str
53
- .toLowerCase()
54
- .replace(/[^a-z0-9-]/g, '-')
55
- .replace(/-+/g, '-')
56
- .replace(/^-|-$/g, '');
57
- }
58
-
59
- function toSnakeCase(str) {
60
- return str.replace(/-/g, '_');
61
- }
62
-
63
- function toTitleCase(str) {
64
- return str
65
- .split('-')
66
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
67
- .join(' ');
68
- }
69
-
70
- function validateProjectName(name) {
71
- if (!name || name.trim().length === 0) {
72
- return 'Project name cannot be empty';
73
- }
74
- const kebab = toKebabCase(name);
75
- if (kebab.length === 0) {
76
- return 'Project name must contain at least one alphanumeric character';
77
- }
78
- if (kebab.length > 214) {
79
- return 'Project name is too long (max 214 characters)';
80
- }
81
- return true;
82
- }
83
-
84
- function shouldSkip(filePath) {
85
- const parts = filePath.split(path.sep);
86
- return parts.some((part) =>
87
- SKIP_PATTERNS.some((pattern) => {
88
- if (pattern.includes('*')) {
89
- const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
90
- return regex.test(part);
91
- }
92
- return part === pattern;
93
- })
94
- );
95
- }
96
-
97
- async function copyTemplate(templateDir, targetDir) {
98
- const entries = await fs.readdir(templateDir, { withFileTypes: true });
99
-
100
- for (const entry of entries) {
101
- const srcPath = path.join(templateDir, entry.name);
102
- const relativePath = path.relative(TEMPLATE_DIR, srcPath);
103
-
104
- if (shouldSkip(relativePath)) {
105
- continue;
106
- }
107
-
108
- // The repository stores the gitignore without a leading dot so npm reliably
109
- // includes it in the published template; generated projects receive the dotfile.
110
- let destName = entry.name;
111
- if (entry.name === 'gitignore') destName = '.gitignore';
112
-
113
- const destPath = path.join(targetDir, destName);
114
-
115
- if (entry.isDirectory()) {
116
- await fs.ensureDir(destPath);
117
- await copyTemplate(srcPath, destPath);
118
- } else {
119
- await fs.copy(srcPath, destPath);
120
- }
121
- }
122
- }
123
-
124
- function replaceVariables(content, variables) {
125
- let result = content;
126
- for (const [key, value] of Object.entries(variables)) {
127
- result = result.replaceAll(`{{${key}}}`, value);
128
- }
129
- return result;
130
- }
131
-
132
- // When stdin is closed/non-interactive, `prompts` never settles its promise:
133
- // the event loop drains and Node exits 0 mid-await — no scaffold, no error.
134
- // That silently "succeeds" in CI. Track the in-flight prompt and fail loudly.
135
- let activePromptMessage = null;
136
-
137
- process.on('exit', (code) => {
138
- if (activePromptMessage !== null && code === 0) {
139
- // writeSync: stderr writes via console.error can be lost in an 'exit'
140
- // handler when stderr is a pipe (async on Windows).
141
- fs.writeSync(
142
- 2,
143
- `\n Aborted: the prompt "${activePromptMessage}" was not answered ` +
144
- `(stdin is closed or non-interactive).\n` +
145
- ` Run in an interactive terminal, or pipe answers via stdin.\n\n`,
146
- );
147
- process.exitCode = 1;
148
- }
149
- });
150
-
151
- async function ask(question) {
152
- activePromptMessage = question.message;
153
- const response = await prompts(question, {
154
- onCancel: () => {
155
- console.error(chalk.red('\n Cancelled.\n'));
156
- process.exit(1);
157
- },
158
- });
159
- activePromptMessage = null;
160
- if (response[question.name] === undefined) {
161
- console.error(
162
- chalk.red(`\n Aborted: no answer received for "${question.message}".\n`),
163
- );
164
- process.exit(1);
165
- }
166
- return response;
167
- }
168
-
169
- function registerAddCommand(program) {
170
- program
171
- .command('add <module>')
172
- .description('Add a module to an existing Tigra project')
173
- .action(async (moduleName) => {
174
- console.log();
175
- console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
176
- console.log();
177
-
178
- const projectDir = process.cwd();
179
-
180
- // Detect if we're inside a Tigra project
181
- const hasServer = await fs.pathExists(path.join(projectDir, 'server', 'src', 'modules', 'auth'));
182
- const hasClient = await fs.pathExists(path.join(projectDir, 'client', 'src', 'features', 'auth'));
183
-
184
- if (!hasServer || !hasClient) {
185
- console.error(chalk.red(' This does not appear to be a Tigra project.'));
186
- console.error(chalk.dim(' Run this command from the root of your project (the folder containing server/ and client/).'));
187
- console.log();
188
- process.exit(1);
189
- }
190
-
191
- const availableModules = ['email-verification'];
192
-
193
- if (!availableModules.includes(moduleName)) {
194
- console.error(chalk.red(` Unknown module: "${moduleName}"`));
195
- console.log();
196
- console.log(chalk.dim(' Available modules:'));
197
- for (const m of availableModules) {
198
- console.log(chalk.cyan(` - ${m}`));
199
- }
200
- console.log();
201
- process.exit(1);
202
- }
203
-
204
- if (moduleName === 'email-verification') {
205
- // Check if already applied
206
- const alreadyApplied = await fs.pathExists(
207
- path.join(projectDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
208
- );
209
- if (alreadyApplied) {
210
- console.log(chalk.yellow(' Email verification is already installed in this project.'));
211
- console.log();
212
- process.exit(0);
213
- }
214
-
215
- const spinner = ora('Adding email verification module...').start();
216
-
217
- try {
218
- const { applyEmailVerificationModule } = await import(
219
- '../lib/patchers/email-verification.patcher.js'
220
- );
221
- await applyEmailVerificationModule(projectDir);
222
-
223
- // Set REQUIRE_USER_VERIFICATION=true in .env if it's currently false
224
- for (const envFile of ['server/.env.example', 'server/.env']) {
225
- const envPath = path.join(projectDir, envFile);
226
- if (await fs.pathExists(envPath)) {
227
- const content = await fs.readFile(envPath, 'utf-8');
228
- if (content.includes('REQUIRE_USER_VERIFICATION=false')) {
229
- await fs.writeFile(
230
- envPath,
231
- content.replace('REQUIRE_USER_VERIFICATION=false', 'REQUIRE_USER_VERIFICATION=true'),
232
- 'utf-8',
233
- );
234
- }
235
- }
236
- }
237
-
238
- spinner.succeed('Email verification module added!');
239
- } catch (error) {
240
- spinner.fail('Failed to add email verification module');
241
- console.error(chalk.red(`\n ${error.message}\n`));
242
- process.exit(1);
243
- }
244
-
245
- const dim = chalk.dim;
246
- const cyan = chalk.cyan;
247
- const green = chalk.green;
248
-
249
- console.log();
250
- console.log(green(' ✓ ') + 'Files added:');
251
- console.log(dim(' server/src/modules/auth/verification.service.ts'));
252
- console.log(dim(' server/src/modules/auth/verification.controller.ts'));
253
- console.log(dim(' client/src/features/auth/services/verification.service.ts'));
254
- console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
255
- console.log();
256
- console.log(green(' ✓ ') + 'Files patched:');
257
- console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, auth.repo.ts'));
258
- console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
259
- console.log(dim(' postman/collection.json'));
260
- console.log();
261
- console.log(green(' ✓ ') + 'REQUIRE_USER_VERIFICATION=true in server/.env');
262
- console.log();
263
- console.log(dim(' Next steps:'));
264
- console.log(cyan(' 1 ') + 'Set ' + chalk.bold('RESEND_API_KEY') + ' in server/.env');
265
- console.log(cyan(' 2 ') + 'Restart the server');
266
- console.log();
267
- }
268
- });
269
- }
270
-
271
- async function main() {
272
- const program = new Command();
273
-
274
- // Define the add subcommand BEFORE the default command so Commander recognizes it
275
- program
276
- .name('create-tigra')
277
- .description('Create a production-ready full-stack app with Next.js + Fastify + Prisma + Redis')
278
- .version(VERSION);
279
-
280
- // ─── Add module subcommand ────────────────────────────────────
281
- registerAddCommand(program);
282
-
283
- // ─── Default: scaffold new project ────────────────────────────
284
- program
285
- .argument('[project-name]', 'Name for your new project')
286
- .action(async (projectNameArg) => {
287
- console.log();
288
- console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`));
289
- console.log();
290
-
291
- let projectName = projectNameArg;
292
-
293
- if (!projectName) {
294
- const response = await ask({
295
- type: 'text',
296
- name: 'projectName',
297
- message: 'What is your project name?',
298
- validate: validateProjectName,
299
- });
300
- projectName = response.projectName;
301
- }
302
-
303
- // Validate and normalize
304
- const validation = validateProjectName(projectName);
305
- if (validation !== true) {
306
- console.error(chalk.red(`\n ${validation}\n`));
307
- process.exit(1);
308
- }
309
-
310
- projectName = toKebabCase(projectName);
311
-
312
- const targetDir = path.resolve(process.cwd(), projectName);
313
-
314
- // Check if directory exists and is non-empty
315
- if (await fs.pathExists(targetDir)) {
316
- const files = await fs.readdir(targetDir);
317
- if (files.length > 0) {
318
- console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
319
- process.exit(1);
320
- }
321
- }
322
-
323
- // Ask about email verification
324
- const { enableVerification } = await ask({
325
- type: 'toggle',
326
- name: 'enableVerification',
327
- message: 'Enable email verification for new users?',
328
- initial: false,
329
- active: 'Yes',
330
- inactive: 'No',
331
- hint: 'Users must verify email before accessing the app',
332
- });
333
-
334
- // Generate random port offset (1-200) so multiple projects don't conflict
335
- const portOffset = crypto.randomInt(1, 201);
336
-
337
- // Derive all variables.
338
- // SECURITY: everything in this map is written into COMMITTED files
339
- // (.env.example, docker-compose.yml, ...) — never put a real secret here.
340
- // JWT_SECRET gets an instructional placeholder; the real secret is
341
- // generated below and written ONLY to the git-ignored .env.
342
- const variables = {
343
- PROJECT_NAME: projectName,
344
- PROJECT_NAME_SNAKE: toSnakeCase(projectName),
345
- PROJECT_DISPLAY_NAME: toTitleCase(projectName),
346
- DATABASE_NAME: `${toSnakeCase(projectName)}_db`,
347
- JWT_SECRET: JWT_SECRET_PLACEHOLDER,
348
- MYSQL_PORT: String(3306 + portOffset),
349
- PHPMYADMIN_PORT: String(8080 + portOffset),
350
- REDIS_PORT: String(6379 + portOffset),
351
- REDIS_COMMANDER_PORT: String(8081 + portOffset),
352
- };
353
-
354
- // Copy template
355
- const spinner = ora('Scaffolding project...').start();
356
-
357
- try {
358
- await fs.ensureDir(targetDir);
359
- await copyTemplate(TEMPLATE_DIR, targetDir);
360
-
361
- // Replace template variables in specific files
362
- for (const filePath of FILES_TO_REPLACE) {
363
- const fullPath = path.join(targetDir, filePath);
364
- if (await fs.pathExists(fullPath)) {
365
- const content = await fs.readFile(fullPath, 'utf-8');
366
- const replaced = replaceVariables(content, variables);
367
- await fs.writeFile(fullPath, replaced, 'utf-8');
368
- }
369
- }
370
-
371
- // Generate .env from .env.example (so users don't have to copy manually).
372
- // The real JWT secret is injected HERE and only here — .env is
373
- // git-ignored, while .env.example is committed and must keep the
374
- // CHANGE_ME placeholder.
375
- const jwtSecret = crypto.randomBytes(48).toString('hex');
376
- for (const envExample of ['server/.env.example', 'client/.env.example']) {
377
- const examplePath = path.join(targetDir, envExample);
378
- const envPath = path.join(targetDir, envExample.replace('.env.example', '.env'));
379
- if (await fs.pathExists(examplePath)) {
380
- const content = await fs.readFile(examplePath, 'utf-8');
381
- await fs.writeFile(
382
- envPath,
383
- content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
384
- 'utf-8',
385
- );
386
- }
387
- }
388
-
389
- // Apply email verification module if selected
390
- if (enableVerification) {
391
- const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
392
- await applyEmailVerificationModule(targetDir);
393
- } else {
394
- // Disable verification requirement in .env files
395
- for (const envFile of ['server/.env.example', 'server/.env']) {
396
- const envPath = path.join(targetDir, envFile);
397
- if (await fs.pathExists(envPath)) {
398
- const content = await fs.readFile(envPath, 'utf-8');
399
- await fs.writeFile(
400
- envPath,
401
- content.replace('REQUIRE_USER_VERIFICATION=true', 'REQUIRE_USER_VERIFICATION=false'),
402
- 'utf-8',
403
- );
404
- }
405
- }
406
- }
407
-
408
- spinner.succeed('Project scaffolded successfully!');
409
- } catch (error) {
410
- spinner.fail('Failed to scaffold project');
411
- console.error(chalk.red(`\n ${error.message}\n`));
412
- process.exit(1);
413
- }
414
-
415
- // Print next steps
416
- const dim = chalk.dim;
417
- const bold = chalk.bold;
418
- const cyan = chalk.cyan;
419
- const green = chalk.green;
420
- const line = dim(' ─────────────────────────────────────────');
421
-
422
- console.log();
423
- console.log(green.bold(' ✓ Created ') + cyan.bold(projectName) + dim(` at ${targetDir}`));
424
- console.log();
425
- console.log(' ┌─────────────────────────────────────────┐');
426
- console.log(' │' + bold(' Getting Started ') + '│');
427
- console.log(' └─────────────────────────────────────────┘');
428
- console.log();
429
- console.log(bold(' SERVER') + dim(' cd ') + cyan(`${projectName}/server`));
430
- console.log();
431
- console.log(cyan(' 1 ') + 'Install & start infrastructure');
432
- console.log(dim(' npm install'));
433
- console.log(dim(' npm run docker:up'));
434
- console.log();
435
- console.log(cyan(' 2 ') + 'Set up database');
436
- console.log(dim(' npm run prisma:generate'));
437
- console.log(dim(' npm run prisma:migrate:dev -- --name init'));
438
- console.log();
439
- console.log(cyan(' 3 ') + 'Start the server');
440
- console.log(dim(' npm run dev'));
441
- console.log();
442
- console.log(bold(' CLIENT') + dim(' (new terminal) cd ') + cyan(`${projectName}/client`));
443
- console.log();
444
- console.log(cyan(' 4 ') + 'Start the client');
445
- console.log(dim(' npm install'));
446
- console.log(dim(' npm run dev'));
447
- console.log();
448
- console.log(line);
449
- console.log();
450
- console.log(dim(' App ') + cyan('http://localhost:3000'));
451
- console.log(dim(' API ') + cyan('http://localhost:8000'));
452
- console.log(dim(' DB/Redis UIs ') + 'optional — start with ' + cyan('npm run docker:tools'));
453
- console.log(dim(' phpMyAdmin ') + cyan(`http://localhost:${variables.PHPMYADMIN_PORT}`));
454
- console.log(dim(' Redis CMD ') + cyan(`http://localhost:${variables.REDIS_COMMANDER_PORT}`));
455
- console.log();
456
- console.log(line);
457
- console.log();
458
- if (enableVerification) {
459
- console.log(dim(' Email verification: ') + green('enabled'));
460
- console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
461
- console.log();
462
- }
463
- console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
464
- console.log();
465
- console.log(dim(' Happy coding! 🚀'));
466
- console.log();
467
- });
468
-
469
- program.parse();
470
- }
471
-
472
- main();
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import prompts from 'prompts';
5
+ import chalk from 'chalk';
6
+ import ora from 'ora';
7
+ import fs from 'fs-extra';
8
+ import path from 'path';
9
+ import { fileURLToPath } from 'url';
10
+ import crypto from 'crypto';
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+
15
+ const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
16
+ const VERSION = packageJson.version;
17
+
18
+ const TEMPLATE_DIR = path.join(__dirname, '..', 'template');
19
+
20
+ // Non-secret placeholder written into the COMMITTED server/.env.example.
21
+ // The real secret replaces it only in the git-ignored server/.env.
22
+ const JWT_SECRET_PLACEHOLDER = 'CHANGE_ME_generate_with_openssl_rand_hex_48';
23
+
24
+ // Files that contain template variables and need replacement
25
+ const FILES_TO_REPLACE = [
26
+ 'AGENTS.md',
27
+ // The project's own README: its name, database and local ports.
28
+ 'README.md',
29
+ 'server/package.json',
30
+ 'server/.env.example',
31
+ 'server/docker-compose.yml',
32
+ 'client/package.json',
33
+ // The shipped lockfiles carry {{PROJECT_NAME}} in their root "name" fields.
34
+ 'server/package-lock.json',
35
+ 'client/package-lock.json',
36
+ 'client/.env.example',
37
+ 'client/.env.example.production',
38
+ 'server/postman/collection.json',
39
+ 'server/postman/environment.json',
40
+ ];
41
+
42
+ // Directories/files to skip when copying
43
+ const SKIP_PATTERNS = [
44
+ 'node_modules',
45
+ '.next',
46
+ 'dist',
47
+ 'out',
48
+ '.env',
49
+ '.env.local',
50
+ '.env.*.local',
51
+ // package-lock.json is NOT skipped: new projects get the template's tested
52
+ // lockfiles, written with the npm in the Dockerfiles' image, so the first
53
+ // `npm ci` (locally and in Docker) installs exactly the versions we tested.
54
+ // Without them every project resolved fresh versions on first install.
55
+ 'pnpm-lock.yaml',
56
+ 'yarn.lock',
57
+ ];
58
+
59
+ function toKebabCase(str) {
60
+ return str
61
+ .toLowerCase()
62
+ .replace(/[^a-z0-9-]/g, '-')
63
+ .replace(/-+/g, '-')
64
+ .replace(/^-|-$/g, '');
65
+ }
66
+
67
+ function toSnakeCase(str) {
68
+ return str.replace(/-/g, '_');
69
+ }
70
+
71
+ function toTitleCase(str) {
72
+ return str
73
+ .split('-')
74
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
75
+ .join(' ');
76
+ }
77
+
78
+ function validateProjectName(name) {
79
+ if (!name || name.trim().length === 0) {
80
+ return 'Project name cannot be empty';
81
+ }
82
+ const kebab = toKebabCase(name);
83
+ if (kebab.length === 0) {
84
+ return 'Project name must contain at least one alphanumeric character';
85
+ }
86
+ if (kebab.length > 214) {
87
+ return 'Project name is too long (max 214 characters)';
88
+ }
89
+ return true;
90
+ }
91
+
92
+ // The generated apps need newer tools than this CLI itself (which runs on Node
93
+ // 22.12+): Node 24+ (their package.json engines and Docker images) and npm
94
+ // 11.19+ (the npm in those images; an older npm writes lockfiles that the
95
+ // image's `npm ci` rejects at deploy time). Warn, never stop: the project is
96
+ // still created, and the tools can be updated before the first `npm ci`.
97
+ const APP_MIN_NODE_MAJOR = 24;
98
+ const APP_MIN_NPM = { major: 11, minor: 19 };
99
+
100
+ function appRuntimeWarnings() {
101
+ const warnings = [];
102
+ const nodeMajor = Number(process.versions.node.split('.')[0]);
103
+ if (nodeMajor < APP_MIN_NODE_MAJOR) {
104
+ warnings.push(`Node ${process.versions.node} found: the new project needs Node ${APP_MIN_NODE_MAJOR} or newer.`);
105
+ }
106
+ // npm names itself in npm_config_user_agent ("npm/11.6.1 node/v24.11.0 ...")
107
+ // when it launches this CLI (npx, npm create, npm run). Launched any other
108
+ // way, npm is not checked rather than spawning it.
109
+ const npm = /\bnpm\/(\d+)\.(\d+)\./.exec(process.env.npm_config_user_agent ?? '');
110
+ if (npm) {
111
+ const major = Number(npm[1]);
112
+ const minor = Number(npm[2]);
113
+ if (major < APP_MIN_NPM.major || (major === APP_MIN_NPM.major && minor < APP_MIN_NPM.minor)) {
114
+ warnings.push(
115
+ `npm ${major}.${minor} found: use npm ${APP_MIN_NPM.major}.${APP_MIN_NPM.minor} or newer ` +
116
+ `(npm install -g npm@${APP_MIN_NPM.major}), or the Docker build rejects your lockfiles.`,
117
+ );
118
+ }
119
+ }
120
+ return warnings;
121
+ }
122
+
123
+ function shouldSkip(filePath) {
124
+ const parts = filePath.split(path.sep);
125
+ return parts.some((part) =>
126
+ SKIP_PATTERNS.some((pattern) => {
127
+ if (pattern.includes('*')) {
128
+ const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
129
+ return regex.test(part);
130
+ }
131
+ return part === pattern;
132
+ })
133
+ );
134
+ }
135
+
136
+ async function copyTemplate(templateDir, targetDir) {
137
+ const entries = await fs.readdir(templateDir, { withFileTypes: true });
138
+
139
+ for (const entry of entries) {
140
+ const srcPath = path.join(templateDir, entry.name);
141
+ const relativePath = path.relative(TEMPLATE_DIR, srcPath);
142
+
143
+ if (shouldSkip(relativePath)) {
144
+ continue;
145
+ }
146
+
147
+ // The repository stores the gitignore without a leading dot so npm reliably
148
+ // includes it in the published template; generated projects receive the dotfile.
149
+ let destName = entry.name;
150
+ if (entry.name === 'gitignore') destName = '.gitignore';
151
+
152
+ const destPath = path.join(targetDir, destName);
153
+
154
+ if (entry.isDirectory()) {
155
+ await fs.ensureDir(destPath);
156
+ await copyTemplate(srcPath, destPath);
157
+ } else {
158
+ await fs.copy(srcPath, destPath);
159
+ }
160
+ }
161
+ }
162
+
163
+ function replaceVariables(content, variables) {
164
+ let result = content;
165
+ for (const [key, value] of Object.entries(variables)) {
166
+ result = result.replaceAll(`{{${key}}}`, value);
167
+ }
168
+ return result;
169
+ }
170
+
171
+ // When stdin is closed/non-interactive, `prompts` never settles its promise:
172
+ // the event loop drains and Node exits 0 mid-await — no scaffold, no error.
173
+ // That silently "succeeds" in CI. Track the in-flight prompt and fail loudly.
174
+ let activePromptMessage = null;
175
+
176
+ process.on('exit', (code) => {
177
+ if (activePromptMessage !== null && code === 0) {
178
+ // writeSync: stderr writes via console.error can be lost in an 'exit'
179
+ // handler when stderr is a pipe (async on Windows).
180
+ fs.writeSync(
181
+ 2,
182
+ `\n Aborted: the prompt "${activePromptMessage}" was not answered ` +
183
+ `(stdin is closed or non-interactive).\n` +
184
+ ` Run in an interactive terminal, or pipe answers via stdin.\n\n`,
185
+ );
186
+ process.exitCode = 1;
187
+ }
188
+ });
189
+
190
+ async function ask(question) {
191
+ activePromptMessage = question.message;
192
+ const response = await prompts(question, {
193
+ onCancel: () => {
194
+ console.error(chalk.red('\n Cancelled.\n'));
195
+ process.exit(1);
196
+ },
197
+ });
198
+ activePromptMessage = null;
199
+ if (response[question.name] === undefined) {
200
+ console.error(
201
+ chalk.red(`\n Aborted: no answer received for "${question.message}".\n`),
202
+ );
203
+ process.exit(1);
204
+ }
205
+ return response;
206
+ }
207
+
208
+ function registerAddCommand(program) {
209
+ program
210
+ .command('add <module>')
211
+ .description('Add a module to an existing Tigra project')
212
+ .action(async (moduleName) => {
213
+ console.log();
214
+ console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
215
+ console.log();
216
+
217
+ const projectDir = process.cwd();
218
+
219
+ // Detect if we're inside a Tigra project
220
+ const hasServer = await fs.pathExists(path.join(projectDir, 'server', 'src', 'modules', 'auth'));
221
+ const hasClient = await fs.pathExists(path.join(projectDir, 'client', 'src', 'features', 'auth'));
222
+
223
+ if (!hasServer || !hasClient) {
224
+ console.error(chalk.red(' This does not appear to be a Tigra project.'));
225
+ console.error(chalk.dim(' Run this command from the root of your project (the folder containing server/ and client/).'));
226
+ console.log();
227
+ process.exit(1);
228
+ }
229
+
230
+ const availableModules = ['email-verification'];
231
+
232
+ if (!availableModules.includes(moduleName)) {
233
+ console.error(chalk.red(` Unknown module: "${moduleName}"`));
234
+ console.log();
235
+ console.log(chalk.dim(' Available modules:'));
236
+ for (const m of availableModules) {
237
+ console.log(chalk.cyan(` - ${m}`));
238
+ }
239
+ console.log();
240
+ process.exit(1);
241
+ }
242
+
243
+ if (moduleName === 'email-verification') {
244
+ // Check if already applied
245
+ const alreadyApplied = await fs.pathExists(
246
+ path.join(projectDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
247
+ );
248
+ if (alreadyApplied) {
249
+ console.log(chalk.yellow(' Email verification is already installed in this project.'));
250
+ console.log();
251
+ process.exit(0);
252
+ }
253
+
254
+ const spinner = ora('Adding email verification module...').start();
255
+
256
+ try {
257
+ const { applyEmailVerificationModule } = await import(
258
+ '../lib/patchers/email-verification.patcher.js'
259
+ );
260
+ // Also switches REQUIRE_USER_VERIFICATION on (env.ts default + every
261
+ // server env file), exactly as at scaffold time.
262
+ await applyEmailVerificationModule(projectDir);
263
+
264
+ spinner.succeed('Email verification module added!');
265
+ } catch (error) {
266
+ spinner.fail('Failed to add email verification module');
267
+ console.error(chalk.red(`\n ${error.message}\n`));
268
+ process.exit(1);
269
+ }
270
+
271
+ const dim = chalk.dim;
272
+ const cyan = chalk.cyan;
273
+ const green = chalk.green;
274
+
275
+ console.log();
276
+ console.log(green(' ✓ ') + 'Files added:');
277
+ console.log(dim(' server/src/modules/auth/verification.service.ts'));
278
+ console.log(dim(' server/src/modules/auth/verification.controller.ts'));
279
+ console.log(dim(' client/src/features/auth/services/verification.service.ts'));
280
+ console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
281
+ console.log();
282
+ console.log(green(' ✓ ') + 'Files patched:');
283
+ console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, auth.repo.ts'));
284
+ console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
285
+ console.log(dim(' postman/collection.json'));
286
+ console.log();
287
+ console.log(green(' ✓ ') + 'REQUIRE_USER_VERIFICATION=true in server/.env');
288
+ console.log();
289
+ console.log(dim(' Next steps:'));
290
+ console.log(cyan(' 1 ') + 'Set ' + chalk.bold('RESEND_API_KEY') + ' in server/.env');
291
+ console.log(cyan(' 2 ') + 'Restart the server');
292
+ console.log();
293
+ }
294
+ });
295
+ }
296
+
297
+ async function main() {
298
+ const program = new Command();
299
+
300
+ // Define the add subcommand BEFORE the default command so Commander recognizes it
301
+ program
302
+ .name('create-tigra')
303
+ .description('Create a production-ready full-stack app with Next.js + Fastify + Prisma + Redis')
304
+ .version(VERSION);
305
+
306
+ // ─── Add module subcommand ────────────────────────────────────
307
+ registerAddCommand(program);
308
+
309
+ // ─── Default: scaffold new project ────────────────────────────
310
+ program
311
+ .argument('[project-name]', 'Name for your new project')
312
+ .action(async (projectNameArg) => {
313
+ console.log();
314
+ console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`));
315
+ console.log();
316
+ const runtimeWarnings = appRuntimeWarnings();
317
+ for (const warning of runtimeWarnings) {
318
+ console.log(chalk.yellow(` ! ${warning}`));
319
+ }
320
+ if (runtimeWarnings.length > 0) console.log();
321
+
322
+ let projectName = projectNameArg;
323
+
324
+ if (!projectName) {
325
+ const response = await ask({
326
+ type: 'text',
327
+ name: 'projectName',
328
+ message: 'What is your project name?',
329
+ validate: validateProjectName,
330
+ });
331
+ projectName = response.projectName;
332
+ }
333
+
334
+ // Validate and normalize
335
+ const validation = validateProjectName(projectName);
336
+ if (validation !== true) {
337
+ console.error(chalk.red(`\n ${validation}\n`));
338
+ process.exit(1);
339
+ }
340
+
341
+ projectName = toKebabCase(projectName);
342
+
343
+ const targetDir = path.resolve(process.cwd(), projectName);
344
+
345
+ // Check if directory exists and is non-empty
346
+ if (await fs.pathExists(targetDir)) {
347
+ const files = await fs.readdir(targetDir);
348
+ if (files.length > 0) {
349
+ console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
350
+ process.exit(1);
351
+ }
352
+ }
353
+
354
+ // Ask about email verification
355
+ const { enableVerification } = await ask({
356
+ type: 'toggle',
357
+ name: 'enableVerification',
358
+ message: 'Enable email verification for new users?',
359
+ initial: false,
360
+ active: 'Yes',
361
+ inactive: 'No',
362
+ hint: 'Users must verify email before accessing the app',
363
+ });
364
+
365
+ // Generate random port offset (1-200) so multiple projects don't conflict
366
+ const portOffset = crypto.randomInt(1, 201);
367
+
368
+ // Derive all variables.
369
+ // SECURITY: everything in this map is written into COMMITTED files
370
+ // (.env.example, docker-compose.yml, ...) — never put a real secret here.
371
+ // JWT_SECRET gets an instructional placeholder; the real secret is
372
+ // generated below and written ONLY to the git-ignored .env.
373
+ const variables = {
374
+ PROJECT_NAME: projectName,
375
+ PROJECT_NAME_SNAKE: toSnakeCase(projectName),
376
+ PROJECT_DISPLAY_NAME: toTitleCase(projectName),
377
+ DATABASE_NAME: `${toSnakeCase(projectName)}_db`,
378
+ JWT_SECRET: JWT_SECRET_PLACEHOLDER,
379
+ MYSQL_PORT: String(3306 + portOffset),
380
+ PHPMYADMIN_PORT: String(8080 + portOffset),
381
+ REDIS_PORT: String(6379 + portOffset),
382
+ REDIS_COMMANDER_PORT: String(8081 + portOffset),
383
+ };
384
+
385
+ // Copy template
386
+ const spinner = ora('Scaffolding project...').start();
387
+
388
+ try {
389
+ await fs.ensureDir(targetDir);
390
+ await copyTemplate(TEMPLATE_DIR, targetDir);
391
+
392
+ // Replace template variables in specific files
393
+ for (const filePath of FILES_TO_REPLACE) {
394
+ const fullPath = path.join(targetDir, filePath);
395
+ if (await fs.pathExists(fullPath)) {
396
+ const content = await fs.readFile(fullPath, 'utf-8');
397
+ const replaced = replaceVariables(content, variables);
398
+ await fs.writeFile(fullPath, replaced, 'utf-8');
399
+ }
400
+ }
401
+
402
+ // Generate .env from .env.example (so users don't have to copy manually).
403
+ // The real JWT secret is injected HERE and only here — .env is
404
+ // git-ignored, while .env.example is committed and must keep the
405
+ // CHANGE_ME placeholder.
406
+ const jwtSecret = crypto.randomBytes(48).toString('hex');
407
+ for (const envExample of ['server/.env.example', 'client/.env.example']) {
408
+ const examplePath = path.join(targetDir, envExample);
409
+ const envPath = path.join(targetDir, envExample.replace('.env.example', '.env'));
410
+ if (await fs.pathExists(examplePath)) {
411
+ const content = await fs.readFile(examplePath, 'utf-8');
412
+ await fs.writeFile(
413
+ envPath,
414
+ content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
415
+ 'utf-8',
416
+ );
417
+ }
418
+ }
419
+
420
+ // Apply email verification module if selected. The template ships with
421
+ // REQUIRE_USER_VERIFICATION off everywhere (no verify route without the
422
+ // module); the patcher switches it on in env.ts and every env file.
423
+ if (enableVerification) {
424
+ const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
425
+ await applyEmailVerificationModule(targetDir);
426
+ }
427
+
428
+ spinner.succeed('Project scaffolded successfully!');
429
+ } catch (error) {
430
+ spinner.fail('Failed to scaffold project');
431
+ console.error(chalk.red(`\n ${error.message}\n`));
432
+ process.exit(1);
433
+ }
434
+
435
+ // Print next steps
436
+ const dim = chalk.dim;
437
+ const bold = chalk.bold;
438
+ const cyan = chalk.cyan;
439
+ const green = chalk.green;
440
+ const line = dim(' ─────────────────────────────────────────');
441
+
442
+ console.log();
443
+ console.log(green.bold(' ✓ Created ') + cyan.bold(projectName) + dim(` at ${targetDir}`));
444
+ console.log();
445
+ console.log(' ┌─────────────────────────────────────────┐');
446
+ console.log(' │' + bold(' Getting Started ') + '│');
447
+ console.log(' └─────────────────────────────────────────┘');
448
+ console.log();
449
+ console.log(bold(' SERVER') + dim(' cd ') + cyan(`${projectName}/server`));
450
+ console.log();
451
+ console.log(cyan(' 1 ') + 'Install & start infrastructure');
452
+ // `npm ci`, not `npm install`: it installs the shipped lockfile as-is.
453
+ // `npm install` on an older local npm rewrites the lockfile into a shape
454
+ // the image's npm then rejects at deploy time.
455
+ console.log(dim(' npm ci'));
456
+ console.log(dim(' npm run docker:up'));
457
+ console.log();
458
+ console.log(cyan(' 2 ') + 'Set up database');
459
+ console.log(dim(' npm run prisma:generate'));
460
+ // No `--name init`: the template ships prisma/migrations/0_init, so this
461
+ // only applies it (creating the tables) unless the schema was changed.
462
+ console.log(dim(' npm run prisma:migrate:dev'));
463
+ console.log();
464
+ console.log(cyan(' 3 ') + 'Start the server');
465
+ console.log(dim(' npm run dev'));
466
+ console.log();
467
+ console.log(bold(' CLIENT') + dim(' (new terminal) cd ') + cyan(`${projectName}/client`));
468
+ console.log();
469
+ console.log(cyan(' 4 ') + 'Start the client');
470
+ console.log(dim(' npm ci'));
471
+ console.log(dim(' npm run dev'));
472
+ console.log();
473
+ console.log(line);
474
+ console.log();
475
+ console.log(dim(' App ') + cyan('http://localhost:3000'));
476
+ console.log(dim(' API ') + cyan('http://localhost:8000'));
477
+ console.log(dim(' DB/Redis UIs ') + 'optional — start with ' + cyan('npm run docker:tools'));
478
+ console.log(dim(' phpMyAdmin ') + cyan(`http://localhost:${variables.PHPMYADMIN_PORT}`));
479
+ console.log(dim(' Redis CMD ') + cyan(`http://localhost:${variables.REDIS_COMMANDER_PORT}`));
480
+ console.log();
481
+ console.log(line);
482
+ console.log();
483
+ if (enableVerification) {
484
+ console.log(dim(' Email verification: ') + green('enabled'));
485
+ console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
486
+ console.log();
487
+ }
488
+ console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
489
+ console.log();
490
+ console.log(dim(' Happy coding! 🚀'));
491
+ console.log();
492
+ });
493
+
494
+ program.parse();
495
+ }
496
+
497
+ main();