create-fs-app 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +233 -417
- package/dist/core/health-check.d.ts +3 -9
- package/dist/core/health-check.js +59 -174
- package/dist/core/health-check.js.map +1 -1
- package/dist/core/presets.d.ts +4 -0
- package/dist/core/presets.js +33 -7
- package/dist/core/presets.js.map +1 -1
- package/dist/core/registry-fetch.d.ts +20 -0
- package/dist/core/registry-fetch.js +121 -0
- package/dist/core/registry-fetch.js.map +1 -0
- package/dist/core/scaffold.d.ts +8 -0
- package/dist/core/scaffold.js +10 -12
- package/dist/core/scaffold.js.map +1 -1
- package/dist/core/template-cache.js +20 -6
- package/dist/core/template-cache.js.map +1 -1
- package/dist/core/template-clone.d.ts +1 -1
- package/dist/core/template-clone.js +520 -47
- package/dist/core/template-clone.js.map +1 -1
- package/dist/core/template-list.d.ts +33 -22
- package/dist/core/template-list.js +154 -95
- package/dist/core/template-list.js.map +1 -1
- package/dist/core/template-registry.d.ts +52 -31
- package/dist/core/template-registry.js +192 -70
- package/dist/core/template-registry.js.map +1 -1
- package/dist/index.js +539 -217
- package/dist/index.js.bak +872 -0
- package/dist/index.js.map +1 -1
- package/dist/types/index.d.ts +23 -27
- package/dist/types/index.js +24 -8
- package/dist/types/index.js.map +1 -1
- package/dist/utils/validation.d.ts +23 -0
- package/dist/utils/validation.js +47 -10
- package/dist/utils/validation.js.map +1 -1
- package/package.json +2 -2
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
import { execa } from 'execa';
|
|
6
6
|
import fs from 'fs/promises';
|
|
7
7
|
import path from 'path';
|
|
8
|
+
import os from 'os';
|
|
8
9
|
import { randomUUID } from 'crypto';
|
|
9
10
|
import { Logger } from '../utils/logger.js';
|
|
10
11
|
import { getCachedTemplatePath, cacheTemplate, copyCachedTemplate } from './template-cache.js';
|
|
11
12
|
/**
|
|
12
13
|
* Clone a template repository (with caching support)
|
|
13
14
|
*/
|
|
14
|
-
export async function cloneTemplate(template, targetDir, branch = 'main') {
|
|
15
|
+
export async function cloneTemplate(template, targetDir, branch = 'main', skipCache = false) {
|
|
15
16
|
const { url, subfolder, localPath } = template;
|
|
16
17
|
try {
|
|
17
18
|
// If it's a local template, just copy it
|
|
@@ -28,18 +29,20 @@ export async function cloneTemplate(template, targetDir, branch = 'main') {
|
|
|
28
29
|
await fs.cp(localPath, targetDir, { recursive: true });
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
|
-
// Check if template is cached
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
32
|
+
// Check if template is cached (skipped when --no-cache is passed)
|
|
33
|
+
if (!skipCache) {
|
|
34
|
+
const cachedPath = await getCachedTemplatePath(template);
|
|
35
|
+
if (cachedPath) {
|
|
36
|
+
Logger.verbose('Using cached template');
|
|
37
|
+
await copyCachedTemplate(cachedPath, targetDir);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
37
40
|
}
|
|
38
|
-
Logger.verbose('Template not cached, downloading...');
|
|
41
|
+
Logger.verbose(skipCache ? 'Cache skipped, downloading fresh copy...' : 'Template not cached, downloading...');
|
|
39
42
|
if (subfolder && url) {
|
|
40
43
|
// Clone entire repo to temp directory, then copy specific subfolder
|
|
41
44
|
// Use UUID to prevent race conditions with simultaneous runs
|
|
42
|
-
const tempDir = path.join(
|
|
45
|
+
const tempDir = path.join(os.tmpdir(), `.cfs-temp-${randomUUID()}`);
|
|
43
46
|
try {
|
|
44
47
|
// Clone with shallow depth for speed
|
|
45
48
|
await execa('git', [
|
|
@@ -63,11 +66,13 @@ export async function cloneTemplate(template, targetDir, branch = 'main') {
|
|
|
63
66
|
}
|
|
64
67
|
// Copy the template folder contents to target
|
|
65
68
|
await fs.cp(templatePath, targetDir, { recursive: true });
|
|
66
|
-
// Cache the template for future use
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
69
|
+
// Cache the template for future use (skipped when --no-cache)
|
|
70
|
+
if (!skipCache) {
|
|
71
|
+
Logger.verbose('Caching template for future use...');
|
|
72
|
+
await cacheTemplate(template, branch).catch(() => {
|
|
73
|
+
Logger.warn('Failed to cache template, continuing anyway');
|
|
74
|
+
});
|
|
75
|
+
}
|
|
71
76
|
// Clean up temp directory
|
|
72
77
|
await fs.rm(tempDir, { recursive: true, force: true });
|
|
73
78
|
}
|
|
@@ -94,11 +99,13 @@ export async function cloneTemplate(template, targetDir, branch = 'main') {
|
|
|
94
99
|
// Remove .git directory to start fresh
|
|
95
100
|
const gitDir = path.join(targetDir, '.git');
|
|
96
101
|
await fs.rm(gitDir, { recursive: true, force: true });
|
|
97
|
-
// Cache the template
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
+
// Cache the template (skipped when --no-cache)
|
|
103
|
+
if (!skipCache) {
|
|
104
|
+
Logger.verbose('Caching template for future use...');
|
|
105
|
+
await cacheTemplate(template, branch).catch(() => {
|
|
106
|
+
Logger.warn('Failed to cache template, continuing anyway');
|
|
107
|
+
});
|
|
108
|
+
}
|
|
102
109
|
}
|
|
103
110
|
}
|
|
104
111
|
catch (error) {
|
|
@@ -109,7 +116,7 @@ export async function cloneTemplate(template, targetDir, branch = 'main') {
|
|
|
109
116
|
* Customize the cloned template with user's configuration
|
|
110
117
|
*/
|
|
111
118
|
export async function customizeTemplate(targetDir, config) {
|
|
112
|
-
// 1. Update package.json with project name
|
|
119
|
+
// 1. Update package.json with project name + packageManager field
|
|
113
120
|
await updatePackageJson(targetDir, config);
|
|
114
121
|
// 2. Replace placeholders in files
|
|
115
122
|
await replacePlaceholders(targetDir, config);
|
|
@@ -119,11 +126,40 @@ export async function customizeTemplate(targetDir, config) {
|
|
|
119
126
|
await handleOptionalFeatures(targetDir, config);
|
|
120
127
|
// 5. Update environment variables template
|
|
121
128
|
await updateEnvTemplate(targetDir, config);
|
|
129
|
+
// 6. Fix workspace protocol for pnpm
|
|
130
|
+
// Templates ship with "@repo/*": "*" (npm-style).
|
|
131
|
+
// pnpm requires "workspace:*" — without it pnpm tries the npm registry → 404.
|
|
132
|
+
if (config.packageManager === 'pnpm') {
|
|
133
|
+
await fixWorkspaceProtocol(targetDir);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Detect the installed version of a package manager.
|
|
138
|
+
* Returns e.g. "pnpm@9.15.0" or falls back to a safe default.
|
|
139
|
+
*/
|
|
140
|
+
async function detectPackageManagerVersion(pm) {
|
|
141
|
+
try {
|
|
142
|
+
const result = await execa(pm, ['--version']);
|
|
143
|
+
const version = result.stdout.trim();
|
|
144
|
+
return `${pm}@${version}`;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// Fallback versions if detection fails
|
|
148
|
+
const defaults = {
|
|
149
|
+
pnpm: 'pnpm@9.0.0',
|
|
150
|
+
yarn: 'yarn@1.22.22',
|
|
151
|
+
npm: 'npm@10.0.0',
|
|
152
|
+
};
|
|
153
|
+
return defaults[pm] ?? `${pm}@latest`;
|
|
154
|
+
}
|
|
122
155
|
}
|
|
123
156
|
/**
|
|
124
|
-
* Update root and nested package.json files
|
|
157
|
+
* Update root and nested package.json files.
|
|
158
|
+
* Also fixes the `packageManager` field in the root to match the user's choice.
|
|
125
159
|
*/
|
|
126
160
|
async function updatePackageJson(targetDir, config) {
|
|
161
|
+
const pm = config.packageManager;
|
|
162
|
+
const pmVersion = await detectPackageManagerVersion(pm);
|
|
127
163
|
const packageJsonPaths = [
|
|
128
164
|
path.join(targetDir, 'package.json'),
|
|
129
165
|
path.join(targetDir, 'apps', 'frontend', 'package.json'),
|
|
@@ -142,17 +178,90 @@ async function updatePackageJson(targetDir, config) {
|
|
|
142
178
|
}
|
|
143
179
|
else {
|
|
144
180
|
pkg.name = config.name;
|
|
181
|
+
// Fix the packageManager field in root package.json only
|
|
182
|
+
pkg.packageManager = pmVersion;
|
|
183
|
+
// Write both formats so the project works across pnpm 9/10/11.
|
|
184
|
+
// pnpm 9/10: onlyBuiltDependencies (array of names)
|
|
185
|
+
// pnpm 11: allowBuilds (object map name → true)
|
|
186
|
+
if (pm === 'pnpm') {
|
|
187
|
+
const allowed = buildAllowList(config);
|
|
188
|
+
const allowBuildsMap = Object.fromEntries(allowed.map(n => [n, true]));
|
|
189
|
+
pkg.pnpm = {
|
|
190
|
+
...(pkg.pnpm ?? {}),
|
|
191
|
+
onlyBuiltDependencies: allowed, // pnpm 9/10
|
|
192
|
+
allowBuilds: allowBuildsMap, // pnpm 11
|
|
193
|
+
};
|
|
194
|
+
}
|
|
145
195
|
}
|
|
146
196
|
// Update description
|
|
147
197
|
pkg.description = `${config.name} - Full-stack application`;
|
|
148
|
-
// Write back
|
|
149
198
|
await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
150
199
|
}
|
|
151
|
-
catch
|
|
200
|
+
catch {
|
|
152
201
|
// File might not exist, that's okay
|
|
153
202
|
continue;
|
|
154
203
|
}
|
|
155
204
|
}
|
|
205
|
+
// pnpm-workspace.yaml — workspace discovery + build-script allowlist.
|
|
206
|
+
//
|
|
207
|
+
// pnpm changed the config key across major versions:
|
|
208
|
+
// pnpm 9: package.json pnpm.onlyBuiltDependencies (array of names)
|
|
209
|
+
// pnpm 10: package.json pnpm.onlyBuiltDependencies (array of names)
|
|
210
|
+
// pnpm-workspace.yaml onlyBuiltDependencies (array of names)
|
|
211
|
+
// pnpm 11: pnpm-workspace.yaml allowBuilds (map name→true)
|
|
212
|
+
//
|
|
213
|
+
// We write BOTH formats so the project works on pnpm 9/10/11.
|
|
214
|
+
if (pm === 'pnpm') {
|
|
215
|
+
const workspaceFile = path.join(targetDir, 'pnpm-workspace.yaml');
|
|
216
|
+
const allowed = buildAllowList(config);
|
|
217
|
+
// pnpm 11 format: allowBuilds map (name → true)
|
|
218
|
+
const allowBuildsMap = allowed.map(p => ` "${p}": true`).join('\n');
|
|
219
|
+
// pnpm 9/10 format: onlyBuiltDependencies list
|
|
220
|
+
const onlyBuiltList = allowed.map(p => ` - "${p}"`).join('\n');
|
|
221
|
+
const content = [
|
|
222
|
+
'packages:',
|
|
223
|
+
' - "apps/*"',
|
|
224
|
+
' - "packages/*"',
|
|
225
|
+
'',
|
|
226
|
+
'# pnpm 11+: allowBuilds map (package name → true/false)',
|
|
227
|
+
'allowBuilds:',
|
|
228
|
+
allowBuildsMap,
|
|
229
|
+
'',
|
|
230
|
+
'# pnpm 9/10: onlyBuiltDependencies list (kept for older pnpm compat)',
|
|
231
|
+
'onlyBuiltDependencies:',
|
|
232
|
+
onlyBuiltList,
|
|
233
|
+
'',
|
|
234
|
+
].join('\n');
|
|
235
|
+
await fs.writeFile(workspaceFile, content);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Packages that need to run postinstall/build scripts.
|
|
240
|
+
* Listed in both package.json (pnpm <10) and pnpm-workspace.yaml (pnpm 10+).
|
|
241
|
+
*
|
|
242
|
+
* Discovery process: scaffold each template combination with --no-install,
|
|
243
|
+
* run `pnpm install`, and collect ERR_PNPM_IGNORED_BUILDS output.
|
|
244
|
+
*
|
|
245
|
+
* Results per stack:
|
|
246
|
+
* All templates → sharp, unrs-resolver, esbuild
|
|
247
|
+
* Prisma templates → @prisma/engines, prisma
|
|
248
|
+
* NestJS templates → @nestjs/core, @scarf/scarf
|
|
249
|
+
* (@scarf/scarf is NestJS's telemetry runner)
|
|
250
|
+
* Express templates → no additional packages
|
|
251
|
+
*/
|
|
252
|
+
function buildAllowList(config) {
|
|
253
|
+
const list = [
|
|
254
|
+
'sharp', // Next.js image optimisation (all templates)
|
|
255
|
+
'unrs-resolver', // Rust-based module resolver (all templates)
|
|
256
|
+
'esbuild', // Build tool used across the stack (all templates)
|
|
257
|
+
];
|
|
258
|
+
if (config.apps.backend.orm === 'prisma') {
|
|
259
|
+
list.push('@prisma/engines', 'prisma');
|
|
260
|
+
}
|
|
261
|
+
if (config.apps.backend.framework === 'nest.js') {
|
|
262
|
+
list.push('@nestjs/core', '@scarf/scarf');
|
|
263
|
+
}
|
|
264
|
+
return list;
|
|
156
265
|
}
|
|
157
266
|
/**
|
|
158
267
|
* Replace placeholder variables in all files
|
|
@@ -167,6 +276,9 @@ async function replacePlaceholders(targetDir, config) {
|
|
|
167
276
|
'{{ORM}}': config.apps.backend.orm || 'none',
|
|
168
277
|
'{{PACKAGE_MANAGER}}': config.packageManager,
|
|
169
278
|
'{{MONOREPO_FRAMEWORK}}': config.monorepo,
|
|
279
|
+
// Scoped package names use 'my-app' as safe placeholder ({{}} invalid in npm names)
|
|
280
|
+
'@my-app/': `@${config.name}/`,
|
|
281
|
+
'"name": "my-app"': `"name": "${config.name}"`,
|
|
170
282
|
};
|
|
171
283
|
// Only process text files with these extensions for performance
|
|
172
284
|
const TEXT_EXTENSIONS = ['.md', '.json', '.ts', '.tsx', '.js', '.jsx', '.env', '.example', '.yml', '.yaml'];
|
|
@@ -223,12 +335,22 @@ async function updateReadme(targetDir, config) {
|
|
|
223
335
|
const techStack = `
|
|
224
336
|
## Tech Stack
|
|
225
337
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
338
|
+
| Layer | Choice |
|
|
339
|
+
|-----------------|--------|
|
|
340
|
+
| Monorepo | ${config.monorepo} |
|
|
341
|
+
| Frontend | ${config.apps.frontend.framework} |
|
|
342
|
+
| Styling | ${config.apps.frontend.styling} |
|
|
343
|
+
| Backend | ${config.apps.backend.framework} |
|
|
344
|
+
| Database | ${config.apps.backend.database} |
|
|
345
|
+
| ORM | ${config.apps.backend.orm || 'none'} |
|
|
346
|
+
| API style | ${config.apps.backend.apiStyle} |
|
|
347
|
+
| Auth | ${config.apps.backend.auth} |
|
|
348
|
+
| Package manager | ${config.packageManager} |
|
|
349
|
+
| ESLint | ${config.apps.frontend.eslint ? '✓' : '✗'} |
|
|
350
|
+
| Prettier | ${config.apps.frontend.prettier ? '✓' : '✗'} |
|
|
351
|
+
| Turbopack | ${config.apps.frontend.turbopack ? '✓' : '✗'} |
|
|
352
|
+
| Docker | ${config.apps.backend.docker ? '✓' : '✗'} |
|
|
353
|
+
| GitHub Actions | ${config.ci ? '✓' : '✗'} |
|
|
232
354
|
|
|
233
355
|
`;
|
|
234
356
|
readme = `# ${config.name}\n\n${techStack}${readme}`;
|
|
@@ -240,10 +362,11 @@ async function updateReadme(targetDir, config) {
|
|
|
240
362
|
}
|
|
241
363
|
}
|
|
242
364
|
/**
|
|
243
|
-
* Handle optional features - remove
|
|
365
|
+
* Handle optional features - remove config for unselected features,
|
|
366
|
+
* patch files for enabled ones (Turbopack, CI, JWT auth).
|
|
244
367
|
*/
|
|
245
368
|
async function handleOptionalFeatures(targetDir, config) {
|
|
246
|
-
//
|
|
369
|
+
// ── Docker ────────────────────────────────────────────────────────────────
|
|
247
370
|
if (!config.apps.backend.docker) {
|
|
248
371
|
const dockerFiles = [
|
|
249
372
|
path.join(targetDir, 'Dockerfile'),
|
|
@@ -256,27 +379,378 @@ async function handleOptionalFeatures(targetDir, config) {
|
|
|
256
379
|
try {
|
|
257
380
|
await fs.unlink(file);
|
|
258
381
|
}
|
|
259
|
-
catch {
|
|
260
|
-
// File doesn't exist, that's fine
|
|
261
|
-
}
|
|
382
|
+
catch { /* ok */ }
|
|
262
383
|
}
|
|
263
384
|
}
|
|
264
|
-
//
|
|
265
|
-
if (!config.apps.frontend.
|
|
266
|
-
const
|
|
385
|
+
// ── ESLint ────────────────────────────────────────────────────────────────
|
|
386
|
+
if (!config.apps.frontend.eslint) {
|
|
387
|
+
const eslintFiles = [
|
|
388
|
+
path.join(targetDir, 'eslint.config.mjs'),
|
|
267
389
|
path.join(targetDir, '.eslintrc.json'),
|
|
268
|
-
path.join(targetDir, '.
|
|
390
|
+
path.join(targetDir, '.eslintrc.js'),
|
|
391
|
+
path.join(targetDir, 'apps', 'frontend', 'eslint.config.mjs'),
|
|
269
392
|
path.join(targetDir, 'apps', 'frontend', '.eslintrc.json'),
|
|
393
|
+
path.join(targetDir, 'apps', 'backend', 'eslint.config.mjs'),
|
|
394
|
+
path.join(targetDir, 'apps', 'backend', '.eslintrc.json'),
|
|
270
395
|
];
|
|
271
|
-
for (const file of
|
|
396
|
+
for (const file of eslintFiles) {
|
|
272
397
|
try {
|
|
273
398
|
await fs.unlink(file);
|
|
274
399
|
}
|
|
275
|
-
catch {
|
|
276
|
-
|
|
400
|
+
catch { /* ok */ }
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
// ── Prettier ──────────────────────────────────────────────────────────────
|
|
404
|
+
if (!config.apps.frontend.prettier) {
|
|
405
|
+
const prettierFiles = [
|
|
406
|
+
path.join(targetDir, '.prettierrc'),
|
|
407
|
+
path.join(targetDir, '.prettierrc.json'),
|
|
408
|
+
path.join(targetDir, '.prettierignore'),
|
|
409
|
+
path.join(targetDir, 'apps', 'frontend', '.prettierrc'),
|
|
410
|
+
path.join(targetDir, 'apps', 'backend', '.prettierrc'),
|
|
411
|
+
];
|
|
412
|
+
for (const file of prettierFiles) {
|
|
413
|
+
try {
|
|
414
|
+
await fs.unlink(file);
|
|
415
|
+
}
|
|
416
|
+
catch { /* ok */ }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
// ── Turbopack (Next.js) ───────────────────────────────────────────────────
|
|
420
|
+
if (config.apps.frontend.turbopack && config.apps.frontend.framework === 'next.js') {
|
|
421
|
+
const frontendPkgPath = path.join(targetDir, 'apps', 'frontend', 'package.json');
|
|
422
|
+
try {
|
|
423
|
+
const raw = await fs.readFile(frontendPkgPath, 'utf-8');
|
|
424
|
+
const pkg = JSON.parse(raw);
|
|
425
|
+
if (pkg.scripts?.dev && !pkg.scripts.dev.includes('--turbopack')) {
|
|
426
|
+
pkg.scripts.dev = pkg.scripts.dev.replace('next dev', 'next dev --turbopack');
|
|
427
|
+
await fs.writeFile(frontendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
catch { /* package.json missing — skip */ }
|
|
431
|
+
}
|
|
432
|
+
// ── GitHub Actions CI ─────────────────────────────────────────────────────
|
|
433
|
+
if (config.ci) {
|
|
434
|
+
await generateCiWorkflow(targetDir, config);
|
|
435
|
+
}
|
|
436
|
+
// ── JWT auth scaffolding ──────────────────────────────────────────────────
|
|
437
|
+
if (config.apps.backend.auth === 'jwt') {
|
|
438
|
+
await generateJwtAuth(targetDir, config);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
// ─── CI workflow generator ────────────────────────────────────────────────────
|
|
442
|
+
async function generateCiWorkflow(targetDir, config) {
|
|
443
|
+
const workflowDir = path.join(targetDir, '.github', 'workflows');
|
|
444
|
+
await fs.mkdir(workflowDir, { recursive: true });
|
|
445
|
+
const pm = config.packageManager;
|
|
446
|
+
const installCmd = pm === 'npm' ? 'npm ci' : pm === 'yarn' ? 'yarn install --frozen-lockfile' : 'pnpm install --frozen-lockfile';
|
|
447
|
+
const lintCmd = `${pm} run lint`;
|
|
448
|
+
const buildCmd = `${pm} run build`;
|
|
449
|
+
const workflow = `name: CI
|
|
450
|
+
|
|
451
|
+
on:
|
|
452
|
+
push:
|
|
453
|
+
branches: [main, master]
|
|
454
|
+
pull_request:
|
|
455
|
+
branches: [main, master]
|
|
456
|
+
|
|
457
|
+
jobs:
|
|
458
|
+
build:
|
|
459
|
+
runs-on: ubuntu-latest
|
|
460
|
+
|
|
461
|
+
steps:
|
|
462
|
+
- uses: actions/checkout@v4
|
|
463
|
+
|
|
464
|
+
- name: Set up Node.js
|
|
465
|
+
uses: actions/setup-node@v4
|
|
466
|
+
with:
|
|
467
|
+
node-version: '20'
|
|
468
|
+
cache: '${pm}'
|
|
469
|
+
|
|
470
|
+
- name: Install dependencies
|
|
471
|
+
run: ${installCmd}
|
|
472
|
+
${config.apps.frontend.eslint ? `
|
|
473
|
+
- name: Lint
|
|
474
|
+
run: ${lintCmd}
|
|
475
|
+
` : ''}
|
|
476
|
+
- name: Build
|
|
477
|
+
run: ${buildCmd}
|
|
478
|
+
`;
|
|
479
|
+
await fs.writeFile(path.join(workflowDir, 'ci.yml'), workflow);
|
|
480
|
+
}
|
|
481
|
+
// ─── JWT auth scaffolding ─────────────────────────────────────────────────────
|
|
482
|
+
async function generateJwtAuth(targetDir, config) {
|
|
483
|
+
const framework = config.apps.backend.framework;
|
|
484
|
+
if (framework === 'nest.js') {
|
|
485
|
+
await generateNestJwtAuth(targetDir);
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
// Express / Fastify / Koa — generic middleware approach
|
|
489
|
+
await generateGenericJwtAuth(targetDir, framework);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
async function generateNestJwtAuth(targetDir) {
|
|
493
|
+
const authDir = path.join(targetDir, 'apps', 'backend', 'src', 'auth');
|
|
494
|
+
await fs.mkdir(authDir, { recursive: true });
|
|
495
|
+
// auth.module.ts
|
|
496
|
+
await fs.writeFile(path.join(authDir, 'auth.module.ts'), `import { Module } from '@nestjs/common';
|
|
497
|
+
import { JwtModule } from '@nestjs/jwt';
|
|
498
|
+
import { PassportModule } from '@nestjs/passport';
|
|
499
|
+
import { AuthService } from './auth.service';
|
|
500
|
+
import { AuthController } from './auth.controller';
|
|
501
|
+
import { JwtStrategy } from './jwt.strategy';
|
|
502
|
+
|
|
503
|
+
@Module({
|
|
504
|
+
imports: [
|
|
505
|
+
PassportModule,
|
|
506
|
+
JwtModule.register({
|
|
507
|
+
secret: process.env.JWT_SECRET || 'change-me',
|
|
508
|
+
signOptions: { expiresIn: '7d' },
|
|
509
|
+
}),
|
|
510
|
+
],
|
|
511
|
+
providers: [AuthService, JwtStrategy],
|
|
512
|
+
controllers: [AuthController],
|
|
513
|
+
exports: [AuthService],
|
|
514
|
+
})
|
|
515
|
+
export class AuthModule {}
|
|
516
|
+
`);
|
|
517
|
+
// auth.service.ts
|
|
518
|
+
await fs.writeFile(path.join(authDir, 'auth.service.ts'), `import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
519
|
+
import { JwtService } from '@nestjs/jwt';
|
|
520
|
+
|
|
521
|
+
export interface JwtPayload {
|
|
522
|
+
sub: string;
|
|
523
|
+
email: string;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
@Injectable()
|
|
527
|
+
export class AuthService {
|
|
528
|
+
constructor(private readonly jwtService: JwtService) {}
|
|
529
|
+
|
|
530
|
+
async login(userId: string, email: string): Promise<{ access_token: string }> {
|
|
531
|
+
const payload: JwtPayload = { sub: userId, email };
|
|
532
|
+
return { access_token: this.jwtService.sign(payload) };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async verifyToken(token: string): Promise<JwtPayload> {
|
|
536
|
+
try {
|
|
537
|
+
return this.jwtService.verify<JwtPayload>(token);
|
|
538
|
+
} catch {
|
|
539
|
+
throw new UnauthorizedException('Invalid or expired token');
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
`);
|
|
544
|
+
// jwt.strategy.ts
|
|
545
|
+
await fs.writeFile(path.join(authDir, 'jwt.strategy.ts'), `import { Injectable } from '@nestjs/common';
|
|
546
|
+
import { PassportStrategy } from '@nestjs/passport';
|
|
547
|
+
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
548
|
+
import { JwtPayload } from './auth.service';
|
|
549
|
+
|
|
550
|
+
@Injectable()
|
|
551
|
+
export class JwtStrategy extends PassportStrategy(Strategy) {
|
|
552
|
+
constructor() {
|
|
553
|
+
super({
|
|
554
|
+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
555
|
+
ignoreExpiration: false,
|
|
556
|
+
secretOrKey: process.env.JWT_SECRET || 'change-me',
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async validate(payload: JwtPayload) {
|
|
561
|
+
return { userId: payload.sub, email: payload.email };
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
`);
|
|
565
|
+
// jwt-auth.guard.ts
|
|
566
|
+
await fs.writeFile(path.join(authDir, 'jwt-auth.guard.ts'), `import { Injectable } from '@nestjs/common';
|
|
567
|
+
import { AuthGuard } from '@nestjs/passport';
|
|
568
|
+
|
|
569
|
+
@Injectable()
|
|
570
|
+
export class JwtAuthGuard extends AuthGuard('jwt') {}
|
|
571
|
+
`);
|
|
572
|
+
// auth.controller.ts (login endpoint stub)
|
|
573
|
+
await fs.writeFile(path.join(authDir, 'auth.controller.ts'), `import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
|
|
574
|
+
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
|
575
|
+
import { AuthService } from './auth.service';
|
|
576
|
+
import { IsEmail, IsString, MinLength } from 'class-validator';
|
|
577
|
+
|
|
578
|
+
export class LoginDto {
|
|
579
|
+
@IsEmail()
|
|
580
|
+
email!: string;
|
|
581
|
+
|
|
582
|
+
@IsString()
|
|
583
|
+
@MinLength(6)
|
|
584
|
+
password!: string;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
@ApiTags('auth')
|
|
588
|
+
@Controller('auth')
|
|
589
|
+
export class AuthController {
|
|
590
|
+
constructor(private readonly authService: AuthService) {}
|
|
591
|
+
|
|
592
|
+
/** POST /auth/login — returns a signed JWT */
|
|
593
|
+
@Post('login')
|
|
594
|
+
@HttpCode(HttpStatus.OK)
|
|
595
|
+
@ApiOperation({ summary: 'Log in and receive a JWT' })
|
|
596
|
+
async login(@Body() dto: LoginDto) {
|
|
597
|
+
// TODO: validate credentials against DB, then:
|
|
598
|
+
// return this.authService.login(user.id, user.email);
|
|
599
|
+
return this.authService.login('placeholder-id', dto.email);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
`);
|
|
603
|
+
// Append JWT_SECRET to .env.example if present
|
|
604
|
+
const envExample = path.join(targetDir, 'apps', 'backend', '.env.example');
|
|
605
|
+
try {
|
|
606
|
+
let env = await fs.readFile(envExample, 'utf-8');
|
|
607
|
+
if (!env.includes('JWT_SECRET')) {
|
|
608
|
+
env += '\n# JWT\nJWT_SECRET=change-me-in-production\n';
|
|
609
|
+
await fs.writeFile(envExample, env);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
catch { /* file missing — skip */ }
|
|
613
|
+
// Add JWT-related packages to backend package.json
|
|
614
|
+
const backendPkgPath = path.join(targetDir, 'apps', 'backend', 'package.json');
|
|
615
|
+
try {
|
|
616
|
+
const raw = await fs.readFile(backendPkgPath, 'utf-8');
|
|
617
|
+
const pkg = JSON.parse(raw);
|
|
618
|
+
pkg.dependencies = pkg.dependencies ?? {};
|
|
619
|
+
pkg.dependencies['@nestjs/jwt'] = '^10.2.0';
|
|
620
|
+
pkg.dependencies['@nestjs/passport'] = '^10.0.3';
|
|
621
|
+
pkg.dependencies['passport'] = '^0.7.0';
|
|
622
|
+
pkg.dependencies['passport-jwt'] = '^4.0.1';
|
|
623
|
+
pkg.devDependencies = pkg.devDependencies ?? {};
|
|
624
|
+
pkg.devDependencies['@types/passport-jwt'] = '^4.0.1';
|
|
625
|
+
await fs.writeFile(backendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
626
|
+
}
|
|
627
|
+
catch { /* backend package.json missing */ }
|
|
628
|
+
// Wire AuthModule into AppModule
|
|
629
|
+
const appModulePath = path.join(targetDir, 'apps', 'backend', 'src', 'app.module.ts');
|
|
630
|
+
try {
|
|
631
|
+
let appModule = await fs.readFile(appModulePath, 'utf-8');
|
|
632
|
+
if (!appModule.includes('AuthModule')) {
|
|
633
|
+
// Add import statement after the last import line
|
|
634
|
+
appModule = appModule.replace(/^(import .+;\n)(?!import)/m, `$1import { AuthModule } from './auth/auth.module';\n`);
|
|
635
|
+
// Add AuthModule to imports array
|
|
636
|
+
appModule = appModule.replace(/imports:\s*\[/, 'imports: [\n AuthModule,');
|
|
637
|
+
await fs.writeFile(appModulePath, appModule);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
catch { /* app.module.ts not present in template */ }
|
|
641
|
+
}
|
|
642
|
+
async function generateGenericJwtAuth(targetDir, framework) {
|
|
643
|
+
const middlewareDir = path.join(targetDir, 'apps', 'backend', 'src', 'middleware');
|
|
644
|
+
await fs.mkdir(middlewareDir, { recursive: true });
|
|
645
|
+
await fs.writeFile(path.join(middlewareDir, 'jwt.middleware.ts'), `/**
|
|
646
|
+
* Generic JWT middleware — works with Express, Fastify, Koa.
|
|
647
|
+
* Install: npm i jsonwebtoken @types/jsonwebtoken
|
|
648
|
+
*/
|
|
649
|
+
import jwt from 'jsonwebtoken';
|
|
650
|
+
|
|
651
|
+
const JWT_SECRET = process.env.JWT_SECRET || 'change-me';
|
|
652
|
+
|
|
653
|
+
export interface JwtPayload {
|
|
654
|
+
sub: string;
|
|
655
|
+
email: string;
|
|
656
|
+
iat?: number;
|
|
657
|
+
exp?: number;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Sign a payload — call after validating credentials */
|
|
661
|
+
export function signToken(payload: Omit<JwtPayload, 'iat' | 'exp'>): string {
|
|
662
|
+
return jwt.sign(payload, JWT_SECRET, { expiresIn: '7d' });
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Verify a token — throws if invalid or expired */
|
|
666
|
+
export function verifyToken(token: string): JwtPayload {
|
|
667
|
+
return jwt.verify(token, JWT_SECRET) as JwtPayload;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** Express/Koa-style auth middleware */
|
|
671
|
+
export function requireAuth(req: any, res: any, next: any) {
|
|
672
|
+
const header = req.headers?.authorization ?? '';
|
|
673
|
+
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
|
|
674
|
+
|
|
675
|
+
if (!token) {
|
|
676
|
+
return res.status(401).json({ message: 'Missing Authorization header' });
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
try {
|
|
680
|
+
req.user = verifyToken(token);
|
|
681
|
+
next();
|
|
682
|
+
} catch {
|
|
683
|
+
return res.status(401).json({ message: 'Invalid or expired token' });
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
`);
|
|
687
|
+
// Append JWT_SECRET to .env.example if present
|
|
688
|
+
const envExample = path.join(targetDir, 'apps', 'backend', '.env.example');
|
|
689
|
+
try {
|
|
690
|
+
let env = await fs.readFile(envExample, 'utf-8');
|
|
691
|
+
if (!env.includes('JWT_SECRET')) {
|
|
692
|
+
env += '\n# JWT\nJWT_SECRET=change-me-in-production\n';
|
|
693
|
+
await fs.writeFile(envExample, env);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
catch { /* file missing — skip */ }
|
|
697
|
+
// Add jsonwebtoken to backend package.json
|
|
698
|
+
const backendPkgPath = path.join(targetDir, 'apps', 'backend', 'package.json');
|
|
699
|
+
try {
|
|
700
|
+
const raw = await fs.readFile(backendPkgPath, 'utf-8');
|
|
701
|
+
const pkg = JSON.parse(raw);
|
|
702
|
+
pkg.dependencies = pkg.dependencies ?? {};
|
|
703
|
+
pkg.dependencies['jsonwebtoken'] = '^9.0.2';
|
|
704
|
+
pkg.devDependencies = pkg.devDependencies ?? {};
|
|
705
|
+
pkg.devDependencies['@types/jsonwebtoken'] = '^9.0.7';
|
|
706
|
+
await fs.writeFile(backendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
707
|
+
}
|
|
708
|
+
catch { /* backend package.json missing */ }
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Rewrite "@repo/*": "*" → "@repo/*": "workspace:*" in every package.json.
|
|
712
|
+
*
|
|
713
|
+
* Templates ship with npm-style "*" for local workspace packages.
|
|
714
|
+
* pnpm requires the explicit "workspace:*" protocol — without it pnpm treats
|
|
715
|
+
* the dependency as an npm package and fails with a 404.
|
|
716
|
+
*/
|
|
717
|
+
async function fixWorkspaceProtocol(targetDir) {
|
|
718
|
+
async function walkDir(dir) {
|
|
719
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
720
|
+
for (const entry of entries) {
|
|
721
|
+
const fullPath = path.join(dir, entry.name);
|
|
722
|
+
if (entry.name === 'node_modules' || entry.name === '.git')
|
|
723
|
+
continue;
|
|
724
|
+
if (entry.isDirectory()) {
|
|
725
|
+
await walkDir(fullPath);
|
|
726
|
+
}
|
|
727
|
+
else if (entry.name === 'package.json') {
|
|
728
|
+
try {
|
|
729
|
+
const raw = await fs.readFile(fullPath, 'utf-8');
|
|
730
|
+
const pkg = JSON.parse(raw);
|
|
731
|
+
let changed = false;
|
|
732
|
+
for (const depField of ['dependencies', 'devDependencies', 'peerDependencies']) {
|
|
733
|
+
const deps = pkg[depField];
|
|
734
|
+
if (!deps)
|
|
735
|
+
continue;
|
|
736
|
+
for (const [name, version] of Object.entries(deps)) {
|
|
737
|
+
if (name.startsWith('@repo/') && version === '*') {
|
|
738
|
+
deps[name] = 'workspace:*';
|
|
739
|
+
changed = true;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (changed) {
|
|
744
|
+
await fs.writeFile(fullPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
catch {
|
|
748
|
+
// skip unreadable files
|
|
749
|
+
}
|
|
277
750
|
}
|
|
278
751
|
}
|
|
279
752
|
}
|
|
753
|
+
await walkDir(targetDir);
|
|
280
754
|
}
|
|
281
755
|
/**
|
|
282
756
|
* Update environment variables template
|
|
@@ -306,13 +780,12 @@ async function updateEnvTemplate(targetDir, config) {
|
|
|
306
780
|
*/
|
|
307
781
|
export async function initializeGit(targetDir, config) {
|
|
308
782
|
try {
|
|
309
|
-
|
|
310
|
-
await execa('git', ['
|
|
311
|
-
await execa('git', ['
|
|
312
|
-
await execa('git', ['commit', '-m', `Initial commit: ${config.name}`]);
|
|
783
|
+
await execa('git', ['init'], { cwd: targetDir });
|
|
784
|
+
await execa('git', ['add', '.'], { cwd: targetDir });
|
|
785
|
+
await execa('git', ['commit', '-m', `Initial commit: ${config.name}`], { cwd: targetDir });
|
|
313
786
|
console.log('✓ Initialized git repository');
|
|
314
787
|
}
|
|
315
|
-
catch
|
|
788
|
+
catch {
|
|
316
789
|
console.warn('Warning: Git initialization failed');
|
|
317
790
|
}
|
|
318
791
|
}
|
|
@@ -321,9 +794,9 @@ export async function initializeGit(targetDir, config) {
|
|
|
321
794
|
*/
|
|
322
795
|
export async function installDependencies(targetDir, packageManager) {
|
|
323
796
|
try {
|
|
324
|
-
process.chdir(targetDir);
|
|
325
797
|
console.log(`Installing dependencies with ${packageManager}...`);
|
|
326
798
|
await execa(packageManager, ['install'], {
|
|
799
|
+
cwd: targetDir,
|
|
327
800
|
stdio: 'inherit',
|
|
328
801
|
});
|
|
329
802
|
console.log('✓ Dependencies installed');
|