create-fs-app 2.0.3 → 3.0.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.
Files changed (60) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +255 -151
  3. package/dist/cli/output.js +223 -0
  4. package/dist/cli/program.js +403 -0
  5. package/dist/cli/resolve-config.js +264 -0
  6. package/dist/cli/ui/errors.js +27 -0
  7. package/dist/cli/ui/help.js +43 -0
  8. package/dist/cli/ui/hints.js +22 -0
  9. package/dist/cli/ui/layer-log.js +109 -0
  10. package/dist/cli/ui/list.js +115 -0
  11. package/dist/cli/ui/text.js +56 -0
  12. package/dist/cli/wizard.js +275 -0
  13. package/dist/core/auth/jwt.js +478 -0
  14. package/dist/core/download.js +109 -0
  15. package/dist/core/health-check.js +42 -44
  16. package/dist/core/presets.js +75 -117
  17. package/dist/core/registry-fetch.js +101 -81
  18. package/dist/core/registry.fallback.json +892 -0
  19. package/dist/core/scaffold.js +121 -75
  20. package/dist/core/stack.js +109 -0
  21. package/dist/core/template-cache.js +95 -154
  22. package/dist/core/template-clone.js +351 -655
  23. package/dist/core/template-list.js +19 -141
  24. package/dist/core/template-registry.js +116 -216
  25. package/dist/index.js +13 -963
  26. package/dist/types/index.js +30 -82
  27. package/dist/utils/cli-error.js +15 -0
  28. package/dist/utils/exec.js +62 -0
  29. package/dist/utils/logger.js +10 -9
  30. package/dist/utils/theme.js +87 -0
  31. package/dist/utils/validation.js +24 -13
  32. package/package.json +22 -25
  33. package/dist/core/health-check.d.ts +0 -15
  34. package/dist/core/health-check.js.map +0 -1
  35. package/dist/core/presets.d.ts +0 -48
  36. package/dist/core/presets.js.map +0 -1
  37. package/dist/core/registry-fetch.d.ts +0 -20
  38. package/dist/core/registry-fetch.js.map +0 -1
  39. package/dist/core/scaffold.d.ts +0 -40
  40. package/dist/core/scaffold.js.map +0 -1
  41. package/dist/core/template-cache.d.ts +0 -38
  42. package/dist/core/template-cache.js.map +0 -1
  43. package/dist/core/template-clone.d.ts +0 -27
  44. package/dist/core/template-clone.js.map +0 -1
  45. package/dist/core/template-list.d.ts +0 -45
  46. package/dist/core/template-list.js.map +0 -1
  47. package/dist/core/template-registry.d.ts +0 -78
  48. package/dist/core/template-registry.js.map +0 -1
  49. package/dist/index.d.ts +0 -2
  50. package/dist/index.js.bak +0 -872
  51. package/dist/index.js.map +0 -1
  52. package/dist/types/index.d.ts +0 -102
  53. package/dist/types/index.js.map +0 -1
  54. package/dist/utils/errors.d.ts +0 -15
  55. package/dist/utils/errors.js +0 -50
  56. package/dist/utils/errors.js.map +0 -1
  57. package/dist/utils/logger.d.ts +0 -37
  58. package/dist/utils/logger.js.map +0 -1
  59. package/dist/utils/validation.d.ts +0 -48
  60. package/dist/utils/validation.js.map +0 -1
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Terminal output for create: warnings, errors, the progress lines, the
3
+ * --dry-run plan and the success screen with the next steps.
4
+ */
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { describeCustomizations, plannedFileChanges } from '../core/template-clone.js';
8
+ import { CliError } from '../utils/cli-error.js';
9
+ import { Logger } from '../utils/logger.js';
10
+ import { detectTheme } from '../utils/theme.js';
11
+ import { renderError } from './ui/errors.js';
12
+ import { renderLayerLog } from './ui/layer-log.js';
13
+ import { pad, wrapText } from './ui/text.js';
14
+ /** A user error: printed without a stack trace, exit 1. */
15
+ export class UsageError extends CliError {
16
+ constructor(message, details) {
17
+ super(message, details);
18
+ this.name = 'UsageError';
19
+ }
20
+ }
21
+ export function warn(message) {
22
+ Logger.warn(message);
23
+ }
24
+ /** Print an error (what / why / Try; stack trace only with DEBUG=1) and exit 1. */
25
+ export function fail(error) {
26
+ const theme = detectTheme(process.stderr);
27
+ console.error(renderError(error, theme));
28
+ if (Logger.isDebug() && error instanceof Error && error.stack)
29
+ console.error(theme.dim(error.stack));
30
+ process.exit(1);
31
+ }
32
+ /** Align "label value" rows. */
33
+ export function rows(entries) {
34
+ const width = Math.max(...entries.map(([label]) => label.length));
35
+ return entries.map(([label, value]) => `${label.padEnd(width)} ${value}`);
36
+ }
37
+ export function yesNo(value) {
38
+ return value ? 'yes' : 'no';
39
+ }
40
+ /** Extras that are on, e.g. "ESLint, Prettier, Docker, git init". */
41
+ export function describeExtras(config) {
42
+ const on = [
43
+ config.eslint && 'ESLint',
44
+ config.prettier && 'Prettier',
45
+ config.docker && 'Docker',
46
+ config.ci && 'GitHub Actions CI',
47
+ config.git && 'git init',
48
+ ].filter((v) => Boolean(v));
49
+ return on.length > 0 ? on.join(', ') : 'none';
50
+ }
51
+ export function seconds(ms) {
52
+ return `${(ms / 1000).toFixed(1)}s`;
53
+ }
54
+ // ── Progress ──────────────────────────────────────────────────────────────────
55
+ /** What a finished step did, e.g. "Template copied from local templates". */
56
+ export function stepText(step, info, plan) {
57
+ switch (step) {
58
+ case 'copy': {
59
+ const { source } = plan;
60
+ const cachedAt = source.type === 'cache'
61
+ ? source.cachedAt
62
+ : source.type === 'download' ? source.staleCache?.cachedAt : undefined;
63
+ const date = cachedAt ? `cached ${cachedAt.toLocaleString()}` : '';
64
+ switch (info.source) {
65
+ case 'local': return 'Template copied from local templates';
66
+ case 'download': return 'Template downloaded';
67
+ case 'stale-cache': return `Template from cache (${['offline', date].filter(Boolean).join(', ')})`;
68
+ default: return date ? `Template from cache (${date})` : 'Template from cache';
69
+ }
70
+ }
71
+ case 'customize': return 'Project customized';
72
+ case 'git': return 'Git repository initialized';
73
+ case 'install': return `Dependencies installed (${plan.config.packageManager})`;
74
+ }
75
+ }
76
+ /** "✓ Project customized 0.2s" */
77
+ export function stepLine(step, info, plan, theme) {
78
+ return `${theme.success(theme.glyphs.check)} ${stepText(step, info, plan)} ${theme.dim(seconds(info.ms))}`;
79
+ }
80
+ // ── --dry-run ─────────────────────────────────────────────────────────────────
81
+ function listFiles(dir) {
82
+ try {
83
+ return fs.readdirSync(dir, { recursive: true, withFileTypes: true })
84
+ .filter(e => e.isFile())
85
+ .map(e => path.relative(dir, path.join(e.parentPath, e.name)).split(path.sep).join('/'));
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ /** Join `items` with `sep` into lines that fit `width` after `indent`. */
92
+ function joinLines(items, sep, width, indent) {
93
+ const lines = [];
94
+ let line = '';
95
+ for (const item of items) {
96
+ const candidate = line ? `${line}${sep}${item}` : item;
97
+ if (line && indent.length + [...candidate].length > width) {
98
+ lines.push(indent + line);
99
+ line = item;
100
+ }
101
+ else {
102
+ line = candidate;
103
+ }
104
+ }
105
+ if (line)
106
+ lines.push(indent + line);
107
+ return lines;
108
+ }
109
+ /** Root files, then apps/<app>/ and packages/<pkg>/ (other top-level dirs as <dir>/) with file counts. */
110
+ function layoutLines(files, theme, width) {
111
+ const rootFiles = files.filter(f => !f.includes('/')).sort((a, b) => a.localeCompare(b));
112
+ const dirs = new Map();
113
+ for (const file of files) {
114
+ const parts = file.split('/');
115
+ if (parts.length === 1)
116
+ continue;
117
+ const depth = (parts[0] === 'apps' || parts[0] === 'packages') && parts.length > 2 ? 2 : 1;
118
+ const dir = `${parts.slice(0, depth).join('/')}/`;
119
+ dirs.set(dir, (dirs.get(dir) ?? 0) + 1);
120
+ }
121
+ const rank = (dir) => (dir.startsWith('apps/') ? 0 : dir.startsWith('packages/') ? 1 : 2);
122
+ const sorted = [...dirs.entries()].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
123
+ const dirWidth = Math.max(0, ...sorted.map(([dir]) => dir.length));
124
+ const countWidth = Math.max(0, ...sorted.map(([, n]) => String(n).length));
125
+ return [
126
+ ...joinLines(rootFiles, ` ${theme.glyphs.dot} `, width, ' '),
127
+ ...sorted.map(([dir, n]) => ` ${pad(dir, dirWidth)} ${theme.dim(`${String(n).padStart(countWidth)} ${n === 1 ? 'file' : 'files'}`)}`),
128
+ ];
129
+ }
130
+ function sourceDir(plan) {
131
+ return plan.source.type === 'local' || plan.source.type === 'cache' ? plan.source.path : undefined;
132
+ }
133
+ /** The --dry-run screen. Reads the source directory (local or cache) but writes nothing. */
134
+ export function renderDryRun(plan, theme, width = 80) {
135
+ const { config, template } = plan;
136
+ const { added, removed } = plannedFileChanges(config, plan.kind);
137
+ const out = [
138
+ `${theme.bold('Dry run')} ${plan.templateLabel} ${theme.dim(`(${plan.kind})`)}`,
139
+ '',
140
+ renderLayerLog({
141
+ title: config.name, template, packageManager: config.packageManager, docker: config.docker, auth: config.auth,
142
+ }, theme, width),
143
+ '',
144
+ `${theme.bold('Would create')} ${config.name}/`,
145
+ ];
146
+ const dir = sourceDir(plan);
147
+ const files = dir ? listFiles(dir) : null;
148
+ if (files) {
149
+ const removedSet = new Set(removed);
150
+ const planned = [...new Set([...files.filter(f => !removedSet.has(f)), ...added])];
151
+ out.push(...layoutLines(planned, theme, width));
152
+ }
153
+ else {
154
+ const layers = template.layers;
155
+ const layerPaths = layers
156
+ ? [layers.frontend.path, layers.packages?.path, layers.backend.path]
157
+ : template.stack ? ['apps/frontend', 'apps/backend'] : [];
158
+ for (const p of layerPaths) {
159
+ if (p)
160
+ out.push(` ${p.includes('*') ? p : `${p}/`}`);
161
+ }
162
+ for (const file of added)
163
+ out.push(` ${file}`);
164
+ if (plan.source.type === 'download') {
165
+ const from = `${template.url ?? plan.source.url}${template.subfolder ? ` (${template.subfolder})` : ''}`;
166
+ out.push(...wrapText(`template files: downloaded from ${from}`, width - 4).map((l, i) => theme.dim(`${i ? ' ' : ' '}${l}`)));
167
+ if (plan.source.staleCache) {
168
+ out.push(theme.dim(` offline fallback: cached copy from ${plan.source.staleCache.cachedAt.toLocaleString()}`));
169
+ }
170
+ }
171
+ }
172
+ out.push('', theme.bold('Customizations'));
173
+ for (const action of describeCustomizations(config, plan.kind)) {
174
+ out.push(...wrapText(action, width - 4).map((l, i) => `${i ? ' ' : ' - '}${l}`));
175
+ }
176
+ const install = config.install
177
+ ? `yes (${config.packageManager} install)`
178
+ : `no (run ${config.packageManager} install yourself)`;
179
+ out.push('', ...rows([['Git init', yesNo(config.git)], ['Install', install]]), '', 'Nothing was written.');
180
+ return out.join('\n');
181
+ }
182
+ export function printDryRun(plan, theme = detectTheme(process.stdout)) {
183
+ console.log();
184
+ console.log(renderDryRun(plan, theme));
185
+ }
186
+ // ── Success ───────────────────────────────────────────────────────────────────
187
+ /** Commands to run after scaffolding, in order ("# ..." lines are comments). */
188
+ export function nextSteps(plan, arrow = '→') {
189
+ const { config, targetDir } = plan;
190
+ const pm = config.packageManager;
191
+ const steps = [`cd ${config.name}`];
192
+ if (!config.install)
193
+ steps.push(`${pm} install`);
194
+ for (const app of ['backend', 'frontend']) {
195
+ for (const [example, env] of [['.env.example', '.env'], ['.env.local.example', '.env.local']]) {
196
+ if (fs.existsSync(path.join(targetDir, 'apps', app, example))) {
197
+ steps.push(`cp apps/${app}/${example} apps/${app}/${env}`);
198
+ }
199
+ }
200
+ }
201
+ if (config.auth === 'jwt') {
202
+ steps.push('# set JWT_SECRET (openssl rand -hex 32) and AUTH_USER_EMAIL', '# in apps/backend/.env', `cd apps/backend && ${pm} run auth:hash-password -- '<password>' && cd ../..`, `# ${arrow} paste the output into AUTH_USER_PASSWORD_HASH`);
203
+ }
204
+ if (config.docker && fs.existsSync(path.join(targetDir, 'docker-compose.yml'))) {
205
+ steps.push('docker compose up -d');
206
+ }
207
+ steps.push(`${pm} run dev`);
208
+ return steps;
209
+ }
210
+ /** "✓ demo is ready 3.2s", the layer log and the next steps. */
211
+ export function renderSuccess(plan, totalMs, theme, width = 80) {
212
+ const { config } = plan;
213
+ return [
214
+ `${theme.success(`${theme.glyphs.check} ${config.name} is ready`)} ${theme.dim(seconds(totalMs))}`,
215
+ '',
216
+ renderLayerLog({
217
+ title: config.name, template: plan.template, packageManager: config.packageManager, docker: config.docker, auth: config.auth,
218
+ }, theme, width),
219
+ '',
220
+ theme.bold('Next steps'),
221
+ ...nextSteps(plan, theme.glyphs.arrow).map(step => ` ${step.startsWith('#') ? theme.dim(step) : step}`),
222
+ ].join('\n');
223
+ }
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Commander wiring for every command. Registry loading happens inside the
3
+ * commands that need it (create, list, info, preset save), not at startup,
4
+ * so --help never loads it. index.ts calls main().
5
+ */
6
+ import { readFileSync } from 'fs';
7
+ import { Command, Help, Option } from 'commander';
8
+ import * as p from '@clack/prompts';
9
+ import { ProjectConfigSchema } from '../types/index.js';
10
+ import { planScaffold, scaffoldProject, validateProjectDirectory, } from '../core/scaffold.js';
11
+ import { getContributedByName, getOfficialByName, listTemplates, } from '../core/template-list.js';
12
+ import { savePreset, listPresets, deletePreset, isBuiltinPresetName, userPresetExists, BUILTIN_PRESETS, } from '../core/presets.js';
13
+ import { runHealthCheck, displayHealthCheckResults } from '../core/health-check.js';
14
+ import { clearCache, getCacheStats } from '../core/template-cache.js';
15
+ import { FALLBACK_REGISTRY, getOfficialTemplates, setActiveRegistry, toTemplates, } from '../core/template-registry.js';
16
+ import { loadRegistry, clearRegistryCache } from '../core/registry-fetch.js';
17
+ import { availableOptions, describeStack } from '../core/stack.js';
18
+ import { AUTH_SUPPORT } from '../core/auth/jwt.js';
19
+ import { assertValidProjectName } from '../utils/validation.js';
20
+ import { Logger } from '../utils/logger.js';
21
+ import { assertAuthSupported, isInteractive, parseAuth, parsePackageManager, resolveCreate, resolveStack, warnRemovedFlags, } from './resolve-config.js';
22
+ import { askName, runWizard, WizardCancelled } from './wizard.js';
23
+ import { UsageError, fail, printDryRun, renderSuccess, stepLine, stepText, seconds, warn } from './output.js';
24
+ import { detectTheme } from '../utils/theme.js';
25
+ import { COMMANDS_GROUP, formatRootHelp } from './ui/help.js';
26
+ import { renderTemplateInfo, renderTemplateList } from './ui/list.js';
27
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'));
28
+ function valuesHelp(field) {
29
+ return availableOptions(toTemplates(FALLBACK_REGISTRY).official, field, {}).join(', ');
30
+ }
31
+ function opt(flags, description, group) {
32
+ return new Option(flags, description).helpGroup(group);
33
+ }
34
+ /** Stack and project options shared by the create command and `preset save`. */
35
+ function addStackOptions(cmd) {
36
+ return cmd
37
+ .addOption(opt('--monorepo <tool>', `Monorepo tool (${valuesHelp('monorepo')})`, 'Stack'))
38
+ .addOption(opt('--frontend <framework>', `Frontend framework (${valuesHelp('frontend')})`, 'Stack'))
39
+ .addOption(opt('--backend <framework>', `Backend framework (${valuesHelp('backend')})`, 'Stack'))
40
+ .addOption(opt('--database <db>', `Database (${valuesHelp('database')})`, 'Stack'))
41
+ .addOption(opt('--orm <orm>', `ORM (${valuesHelp('orm')})`, 'Stack'))
42
+ .addOption(opt('--auth <strategy>', `Auth scaffolding: none | jwt (jwt: ${AUTH_SUPPORT.join(', ')})`, 'Stack'))
43
+ .addOption(opt('--package-manager <pm>', 'Package manager (npm, pnpm, yarn)', 'Stack'))
44
+ .addOption(opt('--eslint', 'Keep ESLint (default)', 'Output'))
45
+ .addOption(opt('--no-eslint', 'Remove ESLint configs and lint scripts', 'Output'))
46
+ .addOption(opt('--prettier', 'Keep Prettier (default)', 'Output'))
47
+ .addOption(opt('--no-prettier', 'Remove Prettier and the format script', 'Output'))
48
+ .addOption(opt('--docker', 'Keep Docker files (default)', 'Output'))
49
+ .addOption(opt('--no-docker', 'Remove Docker files', 'Output'))
50
+ .addOption(opt('--ci', 'Add a GitHub Actions CI workflow', 'Output'))
51
+ .addOption(opt('--no-ci', 'Skip GitHub Actions CI (default)', 'Output'));
52
+ }
53
+ async function hydrateRegistry() {
54
+ const loaded = await loadRegistry();
55
+ setActiveRegistry(loaded.registry);
56
+ Logger.debug(`Registry source: ${loaded.source}`);
57
+ }
58
+ const STEP_MESSAGES = {
59
+ copy: 'Copying template',
60
+ customize: 'Customizing project',
61
+ git: 'Initializing git',
62
+ install: 'Installing dependencies',
63
+ };
64
+ /**
65
+ * Run the plan. TTY: a clack spinner per step, stopped with the completion
66
+ * line (install inherits stdio, so it runs without a spinner). Otherwise just
67
+ * the completion lines.
68
+ */
69
+ async function execute(plan, interactive, theme) {
70
+ if (!interactive) {
71
+ await scaffoldProject(plan, { onStepDone: (step, info) => console.log(stepLine(step, info, plan, theme)) });
72
+ return;
73
+ }
74
+ const s = p.spinner();
75
+ let spinning = false;
76
+ try {
77
+ await scaffoldProject(plan, {
78
+ onStep: (step) => {
79
+ if (step === 'install') {
80
+ p.log.step(`${STEP_MESSAGES.install} (${plan.config.packageManager})`);
81
+ return;
82
+ }
83
+ s.start(step === 'copy' && plan.source.type === 'download' ? 'Downloading template' : STEP_MESSAGES[step]);
84
+ spinning = true;
85
+ },
86
+ onStepDone: (step, info) => {
87
+ const line = `${stepText(step, info, plan)} ${theme.dim(seconds(info.ms))}`;
88
+ if (spinning)
89
+ s.stop(line);
90
+ else
91
+ p.log.success(line);
92
+ spinning = false;
93
+ },
94
+ });
95
+ }
96
+ catch (error) {
97
+ if (spinning)
98
+ s.error('Failed');
99
+ throw error;
100
+ }
101
+ }
102
+ async function createAction(nameArg, flags, cmd, theme) {
103
+ warnRemovedFlags(flags);
104
+ const interactive = isInteractive();
105
+ let localDir = flags.localTemplates;
106
+ if (flags.templateUrl && localDir) {
107
+ warn('--local-templates is ignored with --template-url.');
108
+ localDir = undefined;
109
+ }
110
+ let name = nameArg?.trim() || undefined;
111
+ if (name) {
112
+ assertValidProjectName(name);
113
+ await validateProjectDirectory(name);
114
+ }
115
+ const loaded = await loadRegistry({ localDir, noCacheWrite: flags.dryRun === true });
116
+ setActiveRegistry(loaded.registry, { localDir: loaded.localDir });
117
+ Logger.debug(`Registry source: ${loaded.source}`);
118
+ // clack UI (intro/wizard/outro) only when we ask something
119
+ let usesWizard = false;
120
+ const startWizard = () => {
121
+ if (!usesWizard)
122
+ p.intro(`${theme.bold('create-fs-app')} ${theme.dim(`v${pkg.version}`)}`);
123
+ usesWizard = true;
124
+ };
125
+ if (!name && interactive && !flags.yes && (flags.templateUrl || flags.template)) {
126
+ startWizard();
127
+ name = await askName();
128
+ }
129
+ const resolved = await resolveCreate(name, flags, {
130
+ interactive,
131
+ gitGiven: cmd.getOptionValueSource('git') === 'cli',
132
+ installGiven: cmd.getOptionValueSource('install') === 'cli',
133
+ });
134
+ let config = resolved.config;
135
+ if (resolved.wizard) {
136
+ startWizard();
137
+ config = await runWizard(resolved.wizard, getOfficialTemplates());
138
+ }
139
+ if (!config)
140
+ throw new Error('No configuration resolved');
141
+ const plan = await planScaffold(config, { template: resolved.template, kind: resolved.kind, noCache: flags.cache === false });
142
+ if (flags.docker === true && !plan.template.supports.docker) {
143
+ warn(`--docker: ${plan.templateLabel} has no Docker files; ignoring it.`);
144
+ }
145
+ if (!usesWizard) {
146
+ console.log(`${theme.dim(`create-fs-app v${pkg.version}`)} ${flags.dryRun ? 'Planning' : 'Creating'} ${theme.bold(plan.config.name)}`);
147
+ }
148
+ if (flags.dryRun) {
149
+ printDryRun(plan, theme);
150
+ if (usesWizard)
151
+ p.outro('Dry run finished');
152
+ else
153
+ console.log();
154
+ return;
155
+ }
156
+ const started = performance.now();
157
+ await execute(plan, interactive, theme);
158
+ console.log();
159
+ console.log(renderSuccess(plan, performance.now() - started, theme));
160
+ if (usesWizard)
161
+ p.outro('Done');
162
+ else
163
+ console.log();
164
+ }
165
+ /** Errors in an action: Ctrl+C / Cancel exits 0, everything else exits 1. */
166
+ function handleActionError(error) {
167
+ if (error instanceof WizardCancelled) {
168
+ p.cancel('Cancelled');
169
+ process.exit(0);
170
+ }
171
+ fail(error);
172
+ }
173
+ export function buildProgram(options = {}) {
174
+ const theme = options.theme ?? detectTheme(process.stdout);
175
+ const program = new Command();
176
+ program
177
+ .name('create-fs-app')
178
+ .description('Create a full-stack monorepo application')
179
+ .version(pkg.version, '-V, --version', 'output the version number')
180
+ // `preset save` defines the same stack options as the root command; without
181
+ // this, commander gives options after the subcommand to the root command
182
+ .enablePositionalOptions()
183
+ // Inherited by the subcommands created below
184
+ .configureOutput({ getOutHasColors: () => theme.color !== 'none', getErrHasColors: () => theme.color !== 'none' })
185
+ .configureHelp({
186
+ styleTitle: (title) => theme.bold(title),
187
+ formatHelp: (cmd, helper) => (cmd.parent
188
+ ? Help.prototype.formatHelp.call(helper, cmd, helper)
189
+ : formatRootHelp(cmd, helper, theme, Math.min(80, helper.helpWidth || 80))),
190
+ });
191
+ program.options.find(o => o.long === '--version')?.helpGroup(COMMANDS_GROUP);
192
+ addStackOptions(program
193
+ .argument('[name]', 'The name of your application'))
194
+ .addOption(opt('--preset <name>', 'Use a configuration preset', 'Stack'))
195
+ .addOption(opt('--no-git', 'Skip git initialization', 'Output'))
196
+ .addOption(opt('--install', 'Install dependencies after scaffolding (default: false)', 'Output'))
197
+ .addOption(opt('--dry-run', 'Show what would be created without writing anything', 'Output'))
198
+ .addOption(opt('-y, --yes', 'Use defaults for missing options (no prompts)', 'Output'))
199
+ .addOption(opt('-t, --template <uuid>', 'Use a contributed template by UUID', 'Templates'))
200
+ .addOption(opt('--template-url <url>', 'Use a custom template from a GitHub URL', 'Templates'))
201
+ .addOption(opt('--local-templates <dir>', 'Use templates from a local directory that contains registry.json', 'Templates'))
202
+ .addOption(opt('--no-cache', 'Skip the template cache', 'Templates'))
203
+ // Removed in v3: accepted with a warning so old commands keep working
204
+ .addOption(new Option('--styling <styling>').hideHelp())
205
+ .addOption(new Option('--api-style <style>').hideHelp())
206
+ .addOption(new Option('--turbopack').hideHelp())
207
+ .addOption(new Option('--no-turbopack').hideHelp())
208
+ .action(async (name, flags, cmd) => {
209
+ try {
210
+ await createAction(name, flags, cmd, theme);
211
+ }
212
+ catch (error) {
213
+ handleActionError(error);
214
+ }
215
+ });
216
+ program
217
+ .command('list [search]')
218
+ .alias('ls')
219
+ .description('List templates. Default: official only. Use --contributed or --all to see community templates.')
220
+ .option('--contributed', 'Show only contributed (community) templates')
221
+ .option('--all', 'Show official and contributed templates')
222
+ .action(async (searchArg, cmdOpts) => {
223
+ try {
224
+ await hydrateRegistry();
225
+ const search = searchArg?.trim() || undefined;
226
+ const found = listTemplates({ search, contributed: cmdOpts.contributed, all: cmdOpts.all });
227
+ console.log();
228
+ console.log(renderTemplateList({ ...found, search, contributedOnly: cmdOpts.contributed && !cmdOpts.all }, theme));
229
+ console.log();
230
+ }
231
+ catch (error) {
232
+ fail(error);
233
+ }
234
+ });
235
+ program
236
+ .command('info <template>')
237
+ .description('Show detailed information about a template (key, part of a key, or UUID)')
238
+ .action(async (templateName) => {
239
+ try {
240
+ await hydrateRegistry();
241
+ const officialRes = getOfficialByName(templateName);
242
+ const contributedRes = getContributedByName(templateName);
243
+ const found = officialRes.match ?? contributedRes.match;
244
+ if (!found) {
245
+ const ambiguous = [...(officialRes.ambiguous ?? []), ...(contributedRes.ambiguous ?? [])];
246
+ throw ambiguous.length > 0
247
+ ? new UsageError(`"${templateName}" matches several templates`, {
248
+ reason: ambiguous.map(t => t.key).join('\n'),
249
+ fix: `create-fs-app info ${ambiguous[0].key}`,
250
+ })
251
+ : new UsageError(`"${templateName}" doesn't match any template`, { fix: 'create-fs-app list --all' });
252
+ }
253
+ console.log();
254
+ console.log(renderTemplateInfo(found, theme));
255
+ console.log();
256
+ }
257
+ catch (error) {
258
+ fail(error);
259
+ }
260
+ });
261
+ program
262
+ .command('health')
263
+ .description('Check the tools create-fs-app and the templates use')
264
+ .action(async () => {
265
+ try {
266
+ const result = await runHealthCheck();
267
+ displayHealthCheckResults(result);
268
+ process.exit(result.passed ? 0 : 1);
269
+ }
270
+ catch (error) {
271
+ fail(error);
272
+ }
273
+ });
274
+ const presetCmd = program.command('preset').description('Manage configuration presets');
275
+ addStackOptions(presetCmd
276
+ .command('save <name>')
277
+ .description('Save a stack configuration as a reusable preset (unspecified stack fields use --yes defaults)')
278
+ .option('-d, --description <desc>', 'Preset description')
279
+ .option('-f, --force', 'Overwrite an existing preset')).action(async (presetName, cmdOptions) => {
280
+ try {
281
+ if (isBuiltinPresetName(presetName)) {
282
+ throw new UsageError(`"${presetName}" is a built-in preset and cannot be overwritten`, {
283
+ reason: `Built-in presets: ${Object.keys(BUILTIN_PRESETS).join(', ')}`,
284
+ fix: `create-fs-app preset save ${presetName}-custom`,
285
+ });
286
+ }
287
+ if ((await userPresetExists(presetName)) && !cmdOptions.force) {
288
+ throw new UsageError(`Preset "${presetName}" already exists`, { fix: '--force' });
289
+ }
290
+ await hydrateRegistry();
291
+ const { stack } = resolveStack({
292
+ monorepo: cmdOptions.monorepo, frontend: cmdOptions.frontend, backend: cmdOptions.backend,
293
+ database: cmdOptions.database, orm: cmdOptions.orm,
294
+ }, getOfficialTemplates(), true);
295
+ const auth = parseAuth(cmdOptions.auth);
296
+ assertAuthSupported(auth, stack.backend);
297
+ const config = ProjectConfigSchema.parse({
298
+ name: 'preset',
299
+ stack: stack,
300
+ packageManager: parsePackageManager(cmdOptions.packageManager),
301
+ eslint: cmdOptions.eslint, prettier: cmdOptions.prettier, docker: cmdOptions.docker,
302
+ ci: cmdOptions.ci, auth,
303
+ });
304
+ await savePreset(presetName, config, cmdOptions.description);
305
+ console.log(theme.dim(` ${describeStack(stack)} ${theme.glyphs.dot} ${config.packageManager}`));
306
+ console.log(`${theme.dim('Use it:')} ${theme.accent(`create-fs-app my-app --preset ${presetName}`)}`);
307
+ }
308
+ catch (error) {
309
+ fail(error);
310
+ }
311
+ });
312
+ presetCmd
313
+ .command('list')
314
+ .description('List all saved presets')
315
+ .action(async () => {
316
+ try {
317
+ const stackOf = (cfg) => (cfg.stack ? describeStack(cfg.stack) : 'no stack');
318
+ console.log();
319
+ console.log(theme.bold('Built-in presets'));
320
+ for (const [key, preset] of Object.entries(BUILTIN_PRESETS)) {
321
+ console.log(` ${key} ${theme.dim(stackOf(preset.config))}`);
322
+ if (preset.description)
323
+ console.log(theme.dim(` ${preset.description}`));
324
+ }
325
+ const userPresets = (await listPresets()).filter(preset => !isBuiltinPresetName(preset.name));
326
+ if (userPresets.length > 0) {
327
+ console.log();
328
+ console.log(theme.bold('Your presets'));
329
+ for (const preset of userPresets) {
330
+ console.log(` ${preset.name} ${theme.dim(stackOf(preset.config))}`);
331
+ if (preset.description)
332
+ console.log(theme.dim(` ${preset.description}`));
333
+ }
334
+ }
335
+ console.log();
336
+ console.log(`${theme.dim('Use:')} ${theme.accent('create-fs-app my-app --preset <name>')}`);
337
+ console.log();
338
+ }
339
+ catch (error) {
340
+ fail(error);
341
+ }
342
+ });
343
+ presetCmd
344
+ .command('delete <name>')
345
+ .description('Delete a saved preset')
346
+ .action(async (presetName) => {
347
+ try {
348
+ if (!(await deletePreset(presetName))) {
349
+ throw new UsageError(isBuiltinPresetName(presetName)
350
+ ? `"${presetName}" is a built-in preset and cannot be deleted`
351
+ : `Preset "${presetName}" not found`, { fix: 'create-fs-app preset list' });
352
+ }
353
+ }
354
+ catch (error) {
355
+ fail(error);
356
+ }
357
+ });
358
+ const cacheCmd = program.command('cache').description('Manage template cache');
359
+ cacheCmd
360
+ .command('clear')
361
+ .description('Clear template cache and registry cache')
362
+ .action(async () => {
363
+ try {
364
+ await clearCache();
365
+ await clearRegistryCache();
366
+ console.log(theme.success(`${theme.glyphs.check} Template cache and registry cache cleared`));
367
+ }
368
+ catch (error) {
369
+ fail(error);
370
+ }
371
+ });
372
+ cacheCmd
373
+ .command('stats')
374
+ .description('Show cache statistics')
375
+ .action(async () => {
376
+ try {
377
+ const stats = await getCacheStats();
378
+ console.log();
379
+ console.log(theme.bold('Cache'));
380
+ console.log(` Templates: ${stats.totalTemplates}`);
381
+ console.log(` Size: ${stats.cacheSize}`);
382
+ for (const t of stats.templates) {
383
+ console.log(theme.dim(` ${t.key} (cached ${new Date(t.cachedAt).toLocaleString()})`));
384
+ }
385
+ console.log();
386
+ }
387
+ catch (error) {
388
+ fail(error);
389
+ }
390
+ });
391
+ // After the subcommands: they copy the root's help option when created, and
392
+ // their own help keeps -h in the default "Options" group
393
+ program.addHelpOption(new Option('-h, --help', 'display help for command').helpGroup(COMMANDS_GROUP));
394
+ return program;
395
+ }
396
+ export async function main(argv = process.argv) {
397
+ try {
398
+ await buildProgram().parseAsync(argv);
399
+ }
400
+ catch (error) {
401
+ fail(error);
402
+ }
403
+ }