create-fs-app 2.0.5 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +271 -158
- package/dist/cli/output.js +223 -0
- package/dist/cli/program.js +403 -0
- package/dist/cli/resolve-config.js +264 -0
- package/dist/cli/ui/errors.js +27 -0
- package/dist/cli/ui/help.js +43 -0
- package/dist/cli/ui/hints.js +22 -0
- package/dist/cli/ui/layer-log.js +113 -0
- package/dist/cli/ui/list.js +115 -0
- package/dist/cli/ui/text.js +56 -0
- package/dist/cli/wizard.js +275 -0
- package/dist/core/auth/jwt.js +478 -0
- package/dist/core/download.js +109 -0
- package/dist/core/health-check.js +46 -44
- package/dist/core/presets.js +75 -117
- package/dist/core/registry-fetch.js +101 -81
- package/dist/core/registry.fallback.json +904 -0
- package/dist/core/scaffold.js +121 -75
- package/dist/core/stack.js +109 -0
- package/dist/core/template-cache.js +95 -154
- package/dist/core/template-clone.js +353 -656
- package/dist/core/template-list.js +19 -141
- package/dist/core/template-registry.js +116 -216
- package/dist/index.js +13 -963
- package/dist/types/index.js +30 -82
- package/dist/utils/cli-error.js +15 -0
- package/dist/utils/exec.js +62 -0
- package/dist/utils/logger.js +10 -9
- package/dist/utils/theme.js +87 -0
- package/dist/utils/validation.js +24 -13
- package/package.json +38 -32
- package/dist/core/health-check.d.ts +0 -15
- package/dist/core/health-check.js.map +0 -1
- package/dist/core/presets.d.ts +0 -48
- package/dist/core/presets.js.map +0 -1
- package/dist/core/registry-fetch.d.ts +0 -20
- package/dist/core/registry-fetch.js.map +0 -1
- package/dist/core/scaffold.d.ts +0 -40
- package/dist/core/scaffold.js.map +0 -1
- package/dist/core/template-cache.d.ts +0 -38
- package/dist/core/template-cache.js.map +0 -1
- package/dist/core/template-clone.d.ts +0 -27
- package/dist/core/template-clone.js.map +0 -1
- package/dist/core/template-list.d.ts +0 -45
- package/dist/core/template-list.js.map +0 -1
- package/dist/core/template-registry.d.ts +0 -78
- package/dist/core/template-registry.js.map +0 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js.map +0 -1
- package/dist/types/index.d.ts +0 -102
- package/dist/types/index.js.map +0 -1
- package/dist/utils/errors.d.ts +0 -15
- package/dist/utils/errors.js +0 -50
- package/dist/utils/errors.js.map +0 -1
- package/dist/utils/logger.d.ts +0 -37
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/validation.d.ts +0 -48
- package/dist/utils/validation.js.map +0 -1
|
@@ -1,150 +1,170 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Template
|
|
3
|
-
* Handles downloading templates and customizing them for the user
|
|
2
|
+
* Template download and customization
|
|
4
3
|
*/
|
|
5
|
-
import { execa } from 'execa';
|
|
6
4
|
import fs from 'fs/promises';
|
|
7
5
|
import path from 'path';
|
|
8
|
-
import os from 'os';
|
|
9
|
-
import { randomUUID } from 'crypto';
|
|
10
6
|
import { Logger } from '../utils/logger.js';
|
|
11
|
-
import {
|
|
7
|
+
import { run } from '../utils/exec.js';
|
|
8
|
+
import { downloadTemplate } from './download.js';
|
|
9
|
+
import { getTemplateFromCache } from './template-cache.js';
|
|
10
|
+
import { describeJwtAuth, generateJwtAuth, jwtFiles, supportsAuth } from './auth/jwt.js';
|
|
12
11
|
/**
|
|
13
|
-
*
|
|
12
|
+
* Copy a template into `targetDir` (which must not exist):
|
|
13
|
+
* local path → copy; otherwise cache (24 h) → tarball download.
|
|
14
|
+
* Returns the source actually used.
|
|
14
15
|
*/
|
|
15
|
-
export async function cloneTemplate(template, targetDir,
|
|
16
|
-
const { url,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
// Check if local template exists
|
|
22
|
-
try {
|
|
23
|
-
await fs.access(localPath);
|
|
24
|
-
}
|
|
25
|
-
catch {
|
|
26
|
-
throw new Error(`Local template not found at: ${localPath}`);
|
|
27
|
-
}
|
|
28
|
-
// Copy local template to target
|
|
29
|
-
await fs.cp(localPath, targetDir, { recursive: true });
|
|
30
|
-
return;
|
|
16
|
+
export async function cloneTemplate(template, targetDir, options = {}) {
|
|
17
|
+
const { url, localPath } = template;
|
|
18
|
+
if (localPath) {
|
|
19
|
+
Logger.verbose(`Using local template from: ${localPath}`);
|
|
20
|
+
try {
|
|
21
|
+
await fs.access(localPath);
|
|
31
22
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const cachedPath = await getCachedTemplatePath(template);
|
|
35
|
-
if (cachedPath) {
|
|
36
|
-
Logger.verbose('Using cached template');
|
|
37
|
-
await copyCachedTemplate(cachedPath, targetDir);
|
|
38
|
-
return;
|
|
39
|
-
}
|
|
23
|
+
catch {
|
|
24
|
+
throw new Error(`Local template not found at: ${localPath}`);
|
|
40
25
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
catch (error) {
|
|
80
|
-
// Clean up temp directory on error
|
|
81
|
-
try {
|
|
82
|
-
await fs.rm(tempDir, { recursive: true, force: true });
|
|
83
|
-
}
|
|
84
|
-
catch { }
|
|
85
|
-
throw error;
|
|
86
|
-
}
|
|
26
|
+
await fs.cp(localPath, targetDir, { recursive: true });
|
|
27
|
+
return 'local';
|
|
28
|
+
}
|
|
29
|
+
if (!url) {
|
|
30
|
+
throw new Error('Template has neither a local path nor a repository URL');
|
|
31
|
+
}
|
|
32
|
+
if (options.noCache) {
|
|
33
|
+
Logger.verbose('Cache skipped, downloading a fresh copy...');
|
|
34
|
+
await downloadTemplate({ repoUrl: url, ref: template.branch ?? 'HEAD', subfolder: template.subfolder }, targetDir);
|
|
35
|
+
return 'download';
|
|
36
|
+
}
|
|
37
|
+
const cached = await getTemplateFromCache(template);
|
|
38
|
+
await fs.cp(cached.path, targetDir, { recursive: true });
|
|
39
|
+
return cached.from;
|
|
40
|
+
}
|
|
41
|
+
const APP_PACKAGES = ['frontend', 'backend'];
|
|
42
|
+
async function readJson(file) {
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(await fs.readFile(file, 'utf-8'));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function writeJson(file, data) {
|
|
51
|
+
await fs.writeFile(file, JSON.stringify(data, null, 2) + '\n');
|
|
52
|
+
}
|
|
53
|
+
/** Root + apps/* package.json paths that exist. */
|
|
54
|
+
async function projectPackageFiles(targetDir) {
|
|
55
|
+
const candidates = [
|
|
56
|
+
path.join(targetDir, 'package.json'),
|
|
57
|
+
...APP_PACKAGES.map(app => path.join(targetDir, 'apps', app, 'package.json')),
|
|
58
|
+
];
|
|
59
|
+
const found = [];
|
|
60
|
+
for (const file of candidates) {
|
|
61
|
+
try {
|
|
62
|
+
await fs.access(file);
|
|
63
|
+
found.push(file);
|
|
87
64
|
}
|
|
88
|
-
|
|
89
|
-
//
|
|
90
|
-
await execa('git', [
|
|
91
|
-
'clone',
|
|
92
|
-
'--depth',
|
|
93
|
-
'1',
|
|
94
|
-
'--branch',
|
|
95
|
-
branch,
|
|
96
|
-
url,
|
|
97
|
-
targetDir
|
|
98
|
-
]);
|
|
99
|
-
// Remove .git directory to start fresh
|
|
100
|
-
const gitDir = path.join(targetDir, '.git');
|
|
101
|
-
await fs.rm(gitDir, { recursive: true, force: true });
|
|
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
|
-
}
|
|
65
|
+
catch {
|
|
66
|
+
// not part of this template
|
|
109
67
|
}
|
|
110
68
|
}
|
|
111
|
-
|
|
112
|
-
throw new Error(`Failed to clone template: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
113
|
-
}
|
|
69
|
+
return found;
|
|
114
70
|
}
|
|
115
71
|
/**
|
|
116
|
-
* Customize the
|
|
72
|
+
* Customize the copied template with the user's configuration.
|
|
117
73
|
*/
|
|
118
|
-
export async function customizeTemplate(targetDir, config) {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
74
|
+
export async function customizeTemplate(targetDir, config, options) {
|
|
75
|
+
const custom = options.kind === 'custom';
|
|
76
|
+
// 1. package.json names + packageManager (+ pnpm build allow-list)
|
|
77
|
+
await updatePackageJson(targetDir, config, custom);
|
|
78
|
+
// 2. Placeholders
|
|
79
|
+
await replacePlaceholders(targetDir, config, custom);
|
|
80
|
+
// 3. ESLint / Prettier / Docker toggles (official and contributed only)
|
|
81
|
+
if (!custom) {
|
|
82
|
+
await applyToggles(targetDir, config);
|
|
83
|
+
}
|
|
84
|
+
// 4. GitHub Actions CI
|
|
85
|
+
if (config.ci) {
|
|
86
|
+
await generateCiWorkflow(targetDir, config);
|
|
87
|
+
}
|
|
88
|
+
// 5. JWT auth (official and contributed only)
|
|
89
|
+
if (!custom && config.auth === 'jwt') {
|
|
90
|
+
const backend = config.stack?.backend;
|
|
91
|
+
if (!supportsAuth(backend)) {
|
|
92
|
+
throw new Error(`--auth jwt is not available for the ${backend ?? 'unknown'} backend`);
|
|
93
|
+
}
|
|
94
|
+
await generateJwtAuth(targetDir, backend, config.packageManager);
|
|
95
|
+
}
|
|
96
|
+
// 6. pnpm needs "workspace:*" for local packages (templates ship npm-style "*")
|
|
132
97
|
if (config.packageManager === 'pnpm') {
|
|
133
98
|
await fixWorkspaceProtocol(targetDir);
|
|
134
99
|
}
|
|
135
100
|
}
|
|
136
101
|
/**
|
|
137
|
-
*
|
|
138
|
-
|
|
102
|
+
* The changes customizeTemplate will make, for --dry-run.
|
|
103
|
+
*/
|
|
104
|
+
export function describeCustomizations(config, kind) {
|
|
105
|
+
const custom = kind === 'custom';
|
|
106
|
+
const actions = [];
|
|
107
|
+
actions.push(custom
|
|
108
|
+
? `Set package.json name to "${config.name}"`
|
|
109
|
+
: `Set package names: ${config.name}, ${config.name}-frontend, ${config.name}-backend`);
|
|
110
|
+
actions.push(`Set packageManager to ${config.packageManager}`);
|
|
111
|
+
actions.push(custom
|
|
112
|
+
? `Replace {{PROJECT_NAME}} with "${config.name}"`
|
|
113
|
+
: `Replace {{PROJECT_NAME}} and stack placeholders (project name "${config.name}")`);
|
|
114
|
+
if (config.packageManager === 'pnpm') {
|
|
115
|
+
actions.push(`Write pnpm-workspace.yaml and the pnpm build allow-list (${buildAllowList(config).join(', ')})`);
|
|
116
|
+
actions.push('Rewrite @repo/* dependencies to workspace:*');
|
|
117
|
+
}
|
|
118
|
+
if (!custom) {
|
|
119
|
+
if (!config.docker)
|
|
120
|
+
actions.push('Remove Docker files (docker-compose.yml, .dockerignore, Dockerfiles)');
|
|
121
|
+
if (!config.eslint)
|
|
122
|
+
actions.push('Remove ESLint configs, lint scripts and the turbo lint task');
|
|
123
|
+
if (!config.prettier)
|
|
124
|
+
actions.push('Remove Prettier configs, the format script and prettier devDependencies');
|
|
125
|
+
}
|
|
126
|
+
if (config.ci)
|
|
127
|
+
actions.push('Generate .github/workflows/ci.yml');
|
|
128
|
+
const backend = config.stack?.backend;
|
|
129
|
+
if (!custom && config.auth === 'jwt' && supportsAuth(backend)) {
|
|
130
|
+
actions.push(...describeJwtAuth(backend));
|
|
131
|
+
}
|
|
132
|
+
return actions;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Files customizeTemplate adds and removes (project-relative POSIX paths), for
|
|
136
|
+
* --dry-run. Removed paths are candidates: a template may not have them all.
|
|
137
|
+
*/
|
|
138
|
+
export function plannedFileChanges(config, kind) {
|
|
139
|
+
const custom = kind === 'custom';
|
|
140
|
+
const added = [];
|
|
141
|
+
const removed = [];
|
|
142
|
+
if (config.packageManager === 'pnpm')
|
|
143
|
+
added.push('pnpm-workspace.yaml');
|
|
144
|
+
if (config.ci)
|
|
145
|
+
added.push('.github/workflows/ci.yml');
|
|
146
|
+
if (!custom) {
|
|
147
|
+
if (!config.docker)
|
|
148
|
+
removed.push(...DOCKER_FILES);
|
|
149
|
+
if (!config.eslint)
|
|
150
|
+
removed.push(...ESLINT_FILES);
|
|
151
|
+
if (!config.prettier)
|
|
152
|
+
removed.push(...PRETTIER_FILES);
|
|
153
|
+
const backend = config.stack?.backend;
|
|
154
|
+
if (config.auth === 'jwt' && supportsAuth(backend))
|
|
155
|
+
added.push(...jwtFiles(backend));
|
|
156
|
+
}
|
|
157
|
+
return { added, removed };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Detect the installed version of a package manager, e.g. "pnpm@9.15.0".
|
|
139
161
|
*/
|
|
140
162
|
async function detectPackageManagerVersion(pm) {
|
|
141
163
|
try {
|
|
142
|
-
const result = await
|
|
143
|
-
|
|
144
|
-
return `${pm}@${version}`;
|
|
164
|
+
const result = await run(pm, ['--version'], { timeout: 10_000 });
|
|
165
|
+
return `${pm}@${result.stdout.trim()}`;
|
|
145
166
|
}
|
|
146
167
|
catch {
|
|
147
|
-
// Fallback versions if detection fails
|
|
148
168
|
const defaults = {
|
|
149
169
|
pnpm: 'pnpm@9.0.0',
|
|
150
170
|
yarn: 'yarn@1.22.22',
|
|
@@ -154,70 +174,57 @@ async function detectPackageManagerVersion(pm) {
|
|
|
154
174
|
}
|
|
155
175
|
}
|
|
156
176
|
/**
|
|
157
|
-
* Update root
|
|
158
|
-
*
|
|
177
|
+
* Update package.json files: root name + packageManager (all kinds); app
|
|
178
|
+
* package names and descriptions (official and contributed only).
|
|
159
179
|
*/
|
|
160
|
-
async function updatePackageJson(targetDir, config) {
|
|
180
|
+
async function updatePackageJson(targetDir, config, custom) {
|
|
161
181
|
const pm = config.packageManager;
|
|
162
182
|
const pmVersion = await detectPackageManagerVersion(pm);
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
else {
|
|
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
|
-
}
|
|
195
|
-
}
|
|
196
|
-
// Update description
|
|
197
|
-
pkg.description = `${config.name} - Full-stack application`;
|
|
198
|
-
await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
183
|
+
const allowed = buildAllowList(config);
|
|
184
|
+
const rootFile = path.join(targetDir, 'package.json');
|
|
185
|
+
const root = await readJson(rootFile);
|
|
186
|
+
if (root) {
|
|
187
|
+
root.name = config.name;
|
|
188
|
+
root.packageManager = pmVersion;
|
|
189
|
+
if (!custom)
|
|
190
|
+
root.description = `${config.name} - Full-stack application`;
|
|
191
|
+
// Both formats so the project works across pnpm 9/10/11:
|
|
192
|
+
// pnpm 9/10: onlyBuiltDependencies (array), pnpm 11: allowBuilds (map)
|
|
193
|
+
if (pm === 'pnpm') {
|
|
194
|
+
root.pnpm = {
|
|
195
|
+
...(root.pnpm ?? {}),
|
|
196
|
+
onlyBuiltDependencies: allowed,
|
|
197
|
+
allowBuilds: Object.fromEntries(allowed.map(n => [n, true])),
|
|
198
|
+
};
|
|
199
199
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
200
|
+
await writeJson(rootFile, root);
|
|
201
|
+
}
|
|
202
|
+
if (!custom) {
|
|
203
|
+
for (const app of APP_PACKAGES) {
|
|
204
|
+
const file = path.join(targetDir, 'apps', app, 'package.json');
|
|
205
|
+
const pkg = await readJson(file);
|
|
206
|
+
if (!pkg)
|
|
207
|
+
continue;
|
|
208
|
+
pkg.name = `${config.name}-${app}`;
|
|
209
|
+
pkg.description = `${config.name} - Full-stack application`;
|
|
210
|
+
await writeJson(file, pkg);
|
|
203
211
|
}
|
|
204
212
|
}
|
|
205
213
|
// pnpm-workspace.yaml — workspace discovery + build-script allowlist.
|
|
206
|
-
//
|
|
207
|
-
//
|
|
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
|
+
// pnpm 9/10: onlyBuiltDependencies (array of names)
|
|
215
|
+
// pnpm 11: allowBuilds (map name → true)
|
|
214
216
|
if (pm === 'pnpm') {
|
|
215
217
|
const workspaceFile = path.join(targetDir, 'pnpm-workspace.yaml');
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
218
|
+
// A custom template's own workspace file knows its layout better than we do
|
|
219
|
+
if (custom) {
|
|
220
|
+
try {
|
|
221
|
+
await fs.access(workspaceFile);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// none shipped: write ours
|
|
226
|
+
}
|
|
227
|
+
}
|
|
221
228
|
const content = [
|
|
222
229
|
'packages:',
|
|
223
230
|
' - "apps/*"',
|
|
@@ -225,217 +232,177 @@ async function updatePackageJson(targetDir, config) {
|
|
|
225
232
|
'',
|
|
226
233
|
'# pnpm 11+: allowBuilds map (package name → true/false)',
|
|
227
234
|
'allowBuilds:',
|
|
228
|
-
|
|
235
|
+
allowed.map(p => ` "${p}": true`).join('\n'),
|
|
229
236
|
'',
|
|
230
237
|
'# pnpm 9/10: onlyBuiltDependencies list (kept for older pnpm compat)',
|
|
231
238
|
'onlyBuiltDependencies:',
|
|
232
|
-
|
|
239
|
+
allowed.map(p => ` - "${p}"`).join('\n'),
|
|
233
240
|
'',
|
|
234
241
|
].join('\n');
|
|
235
242
|
await fs.writeFile(workspaceFile, content);
|
|
236
243
|
}
|
|
237
244
|
}
|
|
238
245
|
/**
|
|
239
|
-
* Packages that need to run postinstall/build scripts.
|
|
240
|
-
* Listed in both package.json (pnpm <10) and pnpm-workspace.yaml (pnpm 10+).
|
|
246
|
+
* Packages that need to run postinstall/build scripts under pnpm.
|
|
241
247
|
*
|
|
242
248
|
* Discovery process: scaffold each template combination with --no-install,
|
|
243
249
|
* run `pnpm install`, and collect ERR_PNPM_IGNORED_BUILDS output.
|
|
244
250
|
*
|
|
245
|
-
* Results per stack:
|
|
246
251
|
* All templates → sharp, unrs-resolver, esbuild
|
|
247
252
|
* Prisma templates → @prisma/engines, prisma
|
|
248
|
-
* NestJS templates → @nestjs/core, @scarf/scarf
|
|
249
|
-
*
|
|
250
|
-
* Express templates → no additional packages
|
|
253
|
+
* NestJS templates → @nestjs/core, @scarf/scarf (NestJS telemetry), @swc/core (decorator
|
|
254
|
+
* metadata for the backend tests)
|
|
251
255
|
*/
|
|
252
|
-
function buildAllowList(config) {
|
|
253
|
-
const list = [
|
|
254
|
-
|
|
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') {
|
|
256
|
+
export function buildAllowList(config) {
|
|
257
|
+
const list = ['sharp', 'unrs-resolver', 'esbuild'];
|
|
258
|
+
if (config.stack?.orm === 'prisma') {
|
|
259
259
|
list.push('@prisma/engines', 'prisma');
|
|
260
260
|
}
|
|
261
|
-
if (config.
|
|
262
|
-
list.push('@nestjs/core', '@scarf/scarf');
|
|
261
|
+
if (config.stack?.backend === 'nest.js') {
|
|
262
|
+
list.push('@nestjs/core', '@scarf/scarf', '@swc/core');
|
|
263
263
|
}
|
|
264
264
|
return list;
|
|
265
265
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
'{{PACKAGE_MANAGER}}': config.packageManager,
|
|
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}"`,
|
|
282
|
-
};
|
|
283
|
-
// Only process text files with these extensions for performance
|
|
284
|
-
const TEXT_EXTENSIONS = ['.md', '.json', '.ts', '.tsx', '.js', '.jsx', '.env', '.example', '.yml', '.yaml'];
|
|
285
|
-
async function processFile(filePath) {
|
|
286
|
-
try {
|
|
287
|
-
// Skip non-text files for performance
|
|
288
|
-
const hasTextExtension = TEXT_EXTENSIONS.some(ext => filePath.endsWith(ext));
|
|
289
|
-
if (!hasTextExtension)
|
|
290
|
-
return;
|
|
291
|
-
let content = await fs.readFile(filePath, 'utf-8');
|
|
292
|
-
let modified = false;
|
|
293
|
-
// Use simple string replacement instead of regex to avoid issues with special characters
|
|
294
|
-
for (const [placeholder, value] of Object.entries(placeholders)) {
|
|
295
|
-
if (content.includes(placeholder)) {
|
|
296
|
-
content = content.split(placeholder).join(value);
|
|
297
|
-
modified = true;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
if (modified) {
|
|
301
|
-
await fs.writeFile(filePath, content);
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
catch (error) {
|
|
305
|
-
// Skip files that can't be read as text
|
|
266
|
+
// Only text files with these extensions are processed
|
|
267
|
+
const TEXT_EXTENSIONS = ['.md', '.json', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.env', '.example', '.yml', '.yaml', '.html', '.css'];
|
|
268
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist']);
|
|
269
|
+
async function walkFiles(dir, visit) {
|
|
270
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
271
|
+
for (const entry of entries) {
|
|
272
|
+
if (SKIP_DIRS.has(entry.name))
|
|
273
|
+
continue;
|
|
274
|
+
const fullPath = path.join(dir, entry.name);
|
|
275
|
+
if (entry.isDirectory()) {
|
|
276
|
+
await walkFiles(fullPath, visit);
|
|
306
277
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
310
|
-
for (const entry of entries) {
|
|
311
|
-
const fullPath = path.join(dir, entry.name);
|
|
312
|
-
// Skip node_modules and .git
|
|
313
|
-
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist') {
|
|
314
|
-
continue;
|
|
315
|
-
}
|
|
316
|
-
if (entry.isDirectory()) {
|
|
317
|
-
await walkDir(fullPath);
|
|
318
|
-
}
|
|
319
|
-
else if (entry.isFile()) {
|
|
320
|
-
await processFile(fullPath);
|
|
321
|
-
}
|
|
278
|
+
else if (entry.isFile()) {
|
|
279
|
+
await visit(fullPath);
|
|
322
280
|
}
|
|
323
281
|
}
|
|
324
|
-
await walkDir(targetDir);
|
|
325
282
|
}
|
|
326
283
|
/**
|
|
327
|
-
*
|
|
284
|
+
* Replace placeholders in text files. Custom templates only get {{PROJECT_NAME}}.
|
|
328
285
|
*/
|
|
329
|
-
async function
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
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 ? '✓' : '✗'} |
|
|
354
|
-
|
|
355
|
-
`;
|
|
356
|
-
readme = `# ${config.name}\n\n${techStack}${readme}`;
|
|
286
|
+
async function replacePlaceholders(targetDir, config, custom) {
|
|
287
|
+
const placeholders = { '{{PROJECT_NAME}}': config.name };
|
|
288
|
+
if (!custom) {
|
|
289
|
+
const stack = config.stack;
|
|
290
|
+
Object.assign(placeholders, {
|
|
291
|
+
'{{PACKAGE_MANAGER}}': config.packageManager,
|
|
292
|
+
// Scoped package names use 'my-app' as safe placeholder ({{}} is invalid in npm names)
|
|
293
|
+
'@my-app/': `@${config.name}/`,
|
|
294
|
+
'"name": "my-app"': `"name": "${config.name}"`,
|
|
295
|
+
});
|
|
296
|
+
if (stack) {
|
|
297
|
+
Object.assign(placeholders, {
|
|
298
|
+
'{{MONOREPO_FRAMEWORK}}': stack.monorepo,
|
|
299
|
+
'{{FRONTEND_FRAMEWORK}}': stack.frontend,
|
|
300
|
+
'{{BACKEND_FRAMEWORK}}': stack.backend,
|
|
301
|
+
'{{DATABASE}}': stack.database,
|
|
302
|
+
'{{ORM}}': stack.orm,
|
|
303
|
+
});
|
|
357
304
|
}
|
|
358
|
-
await fs.writeFile(readmePath, readme);
|
|
359
305
|
}
|
|
360
|
-
|
|
361
|
-
|
|
306
|
+
await walkFiles(targetDir, async (filePath) => {
|
|
307
|
+
const name = path.basename(filePath);
|
|
308
|
+
if (!TEXT_EXTENSIONS.some(ext => name.endsWith(ext)) && !name.startsWith('.env'))
|
|
309
|
+
return;
|
|
310
|
+
let content;
|
|
311
|
+
try {
|
|
312
|
+
content = await fs.readFile(filePath, 'utf-8');
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
return; // unreadable: leave as is
|
|
316
|
+
}
|
|
317
|
+
let modified = false;
|
|
318
|
+
for (const [placeholder, value] of Object.entries(placeholders)) {
|
|
319
|
+
if (content.includes(placeholder)) {
|
|
320
|
+
content = content.split(placeholder).join(value);
|
|
321
|
+
modified = true;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (modified)
|
|
325
|
+
await fs.writeFile(filePath, content);
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
async function removeFiles(targetDir, relativePaths) {
|
|
329
|
+
for (const relative of relativePaths) {
|
|
330
|
+
await fs.rm(path.join(targetDir, relative), { force: true });
|
|
362
331
|
}
|
|
363
332
|
}
|
|
333
|
+
const DOCKER_FILES = [
|
|
334
|
+
'Dockerfile',
|
|
335
|
+
'docker-compose.yml',
|
|
336
|
+
'docker-compose.yaml',
|
|
337
|
+
'compose.yml',
|
|
338
|
+
'compose.yaml',
|
|
339
|
+
'.dockerignore',
|
|
340
|
+
'apps/backend/Dockerfile',
|
|
341
|
+
'apps/backend/.dockerignore',
|
|
342
|
+
'apps/frontend/Dockerfile',
|
|
343
|
+
'apps/frontend/.dockerignore',
|
|
344
|
+
];
|
|
345
|
+
const ESLINT_FILES = [
|
|
346
|
+
'eslint.config.mjs',
|
|
347
|
+
'eslint.config.js',
|
|
348
|
+
'.eslintrc.json',
|
|
349
|
+
'.eslintrc.js',
|
|
350
|
+
'apps/frontend/eslint.config.mjs',
|
|
351
|
+
'apps/frontend/eslint.config.js',
|
|
352
|
+
'apps/frontend/.eslintrc.json',
|
|
353
|
+
'apps/backend/eslint.config.mjs',
|
|
354
|
+
'apps/backend/eslint.config.js',
|
|
355
|
+
'apps/backend/.eslintrc.json',
|
|
356
|
+
];
|
|
357
|
+
const PRETTIER_FILES = [
|
|
358
|
+
'.prettierrc',
|
|
359
|
+
'.prettierrc.json',
|
|
360
|
+
'.prettierignore',
|
|
361
|
+
'apps/frontend/.prettierrc',
|
|
362
|
+
'apps/backend/.prettierrc',
|
|
363
|
+
];
|
|
364
364
|
/**
|
|
365
|
-
*
|
|
366
|
-
* patch files for enabled ones (Turbopack, CI, JWT auth).
|
|
365
|
+
* --no-docker, --no-eslint, --no-prettier.
|
|
367
366
|
*/
|
|
368
|
-
async function
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
}
|
|
382
|
-
catch { /* ok */ }
|
|
367
|
+
async function applyToggles(targetDir, config) {
|
|
368
|
+
if (!config.docker) {
|
|
369
|
+
await removeFiles(targetDir, DOCKER_FILES);
|
|
370
|
+
}
|
|
371
|
+
if (!config.eslint) {
|
|
372
|
+
await removeFiles(targetDir, ESLINT_FILES);
|
|
373
|
+
for (const file of await projectPackageFiles(targetDir)) {
|
|
374
|
+
const pkg = await readJson(file);
|
|
375
|
+
if (!pkg?.scripts)
|
|
376
|
+
continue;
|
|
377
|
+
delete pkg.scripts.lint;
|
|
378
|
+
delete pkg.scripts['lint:fix'];
|
|
379
|
+
await writeJson(file, pkg);
|
|
383
380
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
path.join(targetDir, '.eslintrc.json'),
|
|
390
|
-
path.join(targetDir, '.eslintrc.js'),
|
|
391
|
-
path.join(targetDir, 'apps', 'frontend', 'eslint.config.mjs'),
|
|
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'),
|
|
395
|
-
];
|
|
396
|
-
for (const file of eslintFiles) {
|
|
397
|
-
try {
|
|
398
|
-
await fs.unlink(file);
|
|
399
|
-
}
|
|
400
|
-
catch { /* ok */ }
|
|
381
|
+
const turboFile = path.join(targetDir, 'turbo.json');
|
|
382
|
+
const turbo = await readJson(turboFile);
|
|
383
|
+
if (turbo?.tasks && 'lint' in turbo.tasks) {
|
|
384
|
+
delete turbo.tasks.lint;
|
|
385
|
+
await writeJson(turboFile, turbo);
|
|
401
386
|
}
|
|
402
387
|
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
try {
|
|
414
|
-
await fs.unlink(file);
|
|
388
|
+
if (!config.prettier) {
|
|
389
|
+
await removeFiles(targetDir, PRETTIER_FILES);
|
|
390
|
+
for (const file of await projectPackageFiles(targetDir)) {
|
|
391
|
+
const pkg = await readJson(file);
|
|
392
|
+
if (!pkg)
|
|
393
|
+
continue;
|
|
394
|
+
let changed = false;
|
|
395
|
+
if (pkg.scripts && 'format' in pkg.scripts) {
|
|
396
|
+
delete pkg.scripts.format;
|
|
397
|
+
changed = true;
|
|
415
398
|
}
|
|
416
|
-
|
|
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');
|
|
399
|
+
if (pkg.devDependencies && 'prettier' in pkg.devDependencies) {
|
|
400
|
+
delete pkg.devDependencies.prettier;
|
|
401
|
+
changed = true;
|
|
428
402
|
}
|
|
403
|
+
if (changed)
|
|
404
|
+
await writeJson(file, pkg);
|
|
429
405
|
}
|
|
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
406
|
}
|
|
440
407
|
}
|
|
441
408
|
// ─── CI workflow generator ────────────────────────────────────────────────────
|
|
@@ -444,8 +411,16 @@ async function generateCiWorkflow(targetDir, config) {
|
|
|
444
411
|
await fs.mkdir(workflowDir, { recursive: true });
|
|
445
412
|
const pm = config.packageManager;
|
|
446
413
|
const installCmd = pm === 'npm' ? 'npm ci' : pm === 'yarn' ? 'yarn install --frozen-lockfile' : 'pnpm install --frozen-lockfile';
|
|
447
|
-
|
|
448
|
-
|
|
414
|
+
// setup-node's pnpm cache needs pnpm on the PATH first; the version comes
|
|
415
|
+
// from the packageManager field in package.json
|
|
416
|
+
const pnpmSetup = pm === 'pnpm' ? `
|
|
417
|
+
- name: Set up pnpm
|
|
418
|
+
uses: pnpm/action-setup@v4
|
|
419
|
+
` : '';
|
|
420
|
+
const lintStep = config.eslint ? `
|
|
421
|
+
- name: Lint
|
|
422
|
+
run: ${pm} run lint
|
|
423
|
+
` : '';
|
|
449
424
|
const workflow = `name: CI
|
|
450
425
|
|
|
451
426
|
on:
|
|
@@ -460,333 +435,61 @@ jobs:
|
|
|
460
435
|
|
|
461
436
|
steps:
|
|
462
437
|
- uses: actions/checkout@v4
|
|
463
|
-
|
|
438
|
+
${pnpmSetup}
|
|
464
439
|
- name: Set up Node.js
|
|
465
440
|
uses: actions/setup-node@v4
|
|
466
441
|
with:
|
|
467
|
-
node-version: '
|
|
442
|
+
node-version: '22'
|
|
468
443
|
cache: '${pm}'
|
|
469
444
|
|
|
470
445
|
- name: Install dependencies
|
|
471
446
|
run: ${installCmd}
|
|
472
|
-
${
|
|
473
|
-
- name: Lint
|
|
474
|
-
run: ${lintCmd}
|
|
475
|
-
` : ''}
|
|
447
|
+
${lintStep}
|
|
476
448
|
- name: Build
|
|
477
|
-
run: ${
|
|
449
|
+
run: ${pm} run build
|
|
478
450
|
`;
|
|
479
451
|
await fs.writeFile(path.join(workflowDir, 'ci.yml'), workflow);
|
|
480
452
|
}
|
|
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
453
|
/**
|
|
711
454
|
* Rewrite "@repo/*": "*" → "@repo/*": "workspace:*" in every package.json.
|
|
712
455
|
*
|
|
713
|
-
* Templates ship with npm-style "*" for local workspace packages.
|
|
714
456
|
* pnpm requires the explicit "workspace:*" protocol — without it pnpm treats
|
|
715
457
|
* the dependency as an npm package and fails with a 404.
|
|
716
458
|
*/
|
|
717
459
|
async function fixWorkspaceProtocol(targetDir) {
|
|
718
|
-
async
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
460
|
+
await walkFiles(targetDir, async (file) => {
|
|
461
|
+
if (path.basename(file) !== 'package.json')
|
|
462
|
+
return;
|
|
463
|
+
const pkg = await readJson(file);
|
|
464
|
+
if (!pkg)
|
|
465
|
+
return;
|
|
466
|
+
let changed = false;
|
|
467
|
+
for (const field of ['dependencies', 'devDependencies', 'peerDependencies']) {
|
|
468
|
+
const deps = pkg[field];
|
|
469
|
+
if (!deps)
|
|
723
470
|
continue;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
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
|
|
471
|
+
for (const [name, version] of Object.entries(deps)) {
|
|
472
|
+
if (name.startsWith('@repo/') && version === '*') {
|
|
473
|
+
deps[name] = 'workspace:*';
|
|
474
|
+
changed = true;
|
|
749
475
|
}
|
|
750
476
|
}
|
|
751
477
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
}
|
|
755
|
-
/**
|
|
756
|
-
* Update environment variables template
|
|
757
|
-
*/
|
|
758
|
-
async function updateEnvTemplate(targetDir, config) {
|
|
759
|
-
const envExamplePath = path.join(targetDir, 'apps', 'backend', '.env.example');
|
|
760
|
-
try {
|
|
761
|
-
let envContent = await fs.readFile(envExamplePath, 'utf-8');
|
|
762
|
-
// Update database URL based on selected database
|
|
763
|
-
const dbUrls = {
|
|
764
|
-
postgresql: 'postgresql://user:password@localhost:5432/{{PROJECT_NAME}}',
|
|
765
|
-
mysql: 'mysql://user:password@localhost:3306/{{PROJECT_NAME}}',
|
|
766
|
-
mongodb: 'mongodb://localhost:27017/{{PROJECT_NAME}}',
|
|
767
|
-
sqlite: 'file:./dev.db',
|
|
768
|
-
};
|
|
769
|
-
const dbUrl = dbUrls[config.apps.backend.database] || '';
|
|
770
|
-
envContent = envContent.replace(/DATABASE_URL=.*/g, `DATABASE_URL="${dbUrl}"`);
|
|
771
|
-
envContent = envContent.replace(/{{PROJECT_NAME}}/g, config.name);
|
|
772
|
-
await fs.writeFile(envExamplePath, envContent);
|
|
773
|
-
}
|
|
774
|
-
catch (error) {
|
|
775
|
-
// .env.example might not exist
|
|
776
|
-
}
|
|
478
|
+
if (changed)
|
|
479
|
+
await writeJson(file, pkg);
|
|
480
|
+
});
|
|
777
481
|
}
|
|
778
482
|
/**
|
|
779
483
|
* Initialize git repository
|
|
780
484
|
*/
|
|
781
485
|
export async function initializeGit(targetDir, config) {
|
|
782
486
|
try {
|
|
783
|
-
await
|
|
784
|
-
await
|
|
785
|
-
await
|
|
786
|
-
console.log('✓ Initialized git repository');
|
|
487
|
+
await run('git', ['init'], { cwd: targetDir });
|
|
488
|
+
await run('git', ['add', '.'], { cwd: targetDir });
|
|
489
|
+
await run('git', ['commit', '-m', `Initial commit: ${config.name}`], { cwd: targetDir });
|
|
787
490
|
}
|
|
788
|
-
catch {
|
|
789
|
-
|
|
491
|
+
catch (error) {
|
|
492
|
+
Logger.warn(`Git initialization failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
790
493
|
}
|
|
791
494
|
}
|
|
792
495
|
/**
|
|
@@ -794,15 +497,9 @@ export async function initializeGit(targetDir, config) {
|
|
|
794
497
|
*/
|
|
795
498
|
export async function installDependencies(targetDir, packageManager) {
|
|
796
499
|
try {
|
|
797
|
-
|
|
798
|
-
await execa(packageManager, ['install'], {
|
|
799
|
-
cwd: targetDir,
|
|
800
|
-
stdio: 'inherit',
|
|
801
|
-
});
|
|
802
|
-
console.log('✓ Dependencies installed');
|
|
500
|
+
await run(packageManager, ['install'], { cwd: targetDir, stdio: 'inherit' });
|
|
803
501
|
}
|
|
804
502
|
catch (error) {
|
|
805
503
|
throw new Error(`Failed to install dependencies: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
806
504
|
}
|
|
807
505
|
}
|
|
808
|
-
//# sourceMappingURL=template-clone.js.map
|