create-vanilla-vite 1.0.2 → 1.2.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.
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
+ import { spawnSync } from "node:child_process";
4
5
  import spawn from "cross-spawn";
5
6
  import { emitKeypressEvents } from "node:readline";
6
7
  import { createInterface } from "node:readline/promises";
@@ -9,8 +10,114 @@ import { dirname, join, resolve } from "node:path";
9
10
  import { fileURLToPath } from "node:url";
10
11
 
11
12
  const args = process.argv.slice(2);
12
- const useDefaultStructure = args.includes("--default");
13
- let projectName = args.find((arg) => !arg.startsWith("--"));
13
+ const allowedOptions = [
14
+ "--yes",
15
+ "--default",
16
+ "--host",
17
+ "--tailwind",
18
+ "--no-tailwind",
19
+ "--axios",
20
+ "--no-axios",
21
+ "--router",
22
+ "--no-router",
23
+ "--icons",
24
+ "--backend",
25
+ "--ts",
26
+ "--js",
27
+ "--structure",
28
+ "--pm",
29
+ "--template",
30
+ "--no-start",
31
+ "--no-update-check",
32
+ "--no-git",
33
+ ];
34
+ const valueOptions = new Set(["--icons", "--backend", "--structure", "--pm", "--template"]);
35
+ const optionNames = new Set(allowedOptions);
36
+ const positionalArgs = [];
37
+ const optionErrors = [];
38
+ for (let index = 0; index < args.length; index += 1) {
39
+ const argument = args[index];
40
+ if (!argument.startsWith("--")) {
41
+ positionalArgs.push(argument);
42
+ continue;
43
+ }
44
+ const separator = argument.indexOf("=");
45
+ const name = separator === -1 ? argument : argument.slice(0, separator);
46
+ if (!optionNames.has(name)) {
47
+ optionErrors.push(`Unknown option: ${name}`);
48
+ continue;
49
+ }
50
+ if (valueOptions.has(name)) {
51
+ if (separator === -1 || !argument.slice(separator + 1)) {
52
+ optionErrors.push(`${name} requires a value in the form ${name}=<value>`);
53
+ if (separator === -1 && args[index + 1] && !args[index + 1].startsWith("--")) {
54
+ index += 1;
55
+ }
56
+ }
57
+ } else if (separator !== -1) {
58
+ optionErrors.push(`${name} does not accept a value`);
59
+ }
60
+ }
61
+ const readOption = (name) =>
62
+ args.find((argument) => argument.startsWith(`--${name}=`))?.slice(name.length + 3);
63
+ const hasOption = (name) => args.includes(`--${name}`);
64
+ const yes = hasOption("yes");
65
+ let activeChild;
66
+ let creationCancelled = false;
67
+ const useDefaultStructure =
68
+ hasOption("default") || process.env.npm_config_default === "true";
69
+ const exposeClient = hasOption("host");
70
+ const noTailwind = hasOption("no-tailwind");
71
+ const noAxios = hasOption("no-axios");
72
+ const noStart = hasOption("no-start");
73
+ const skipUpdateCheck =
74
+ hasOption("no-update-check") || yes || process.env.CI !== undefined;
75
+ const backendOption = readOption("backend");
76
+ const languageOption = hasOption("ts") ? "ts" : hasOption("js") ? "js" : null;
77
+ const structureOption = readOption("structure");
78
+ const requestedPackageManager = readOption("pm");
79
+ const templateOption = readOption("template");
80
+ const iconsOption = readOption("icons");
81
+ if (backendOption !== undefined && !["none", "basic", "express"].includes(backendOption)) {
82
+ optionErrors.push("--backend must be none, basic, or express");
83
+ }
84
+ if (hasOption("ts") && hasOption("js")) {
85
+ optionErrors.push("Use only one of --ts or --js");
86
+ }
87
+ if (hasOption("router") && hasOption("no-router")) {
88
+ optionErrors.push("Use only one of --router or --no-router");
89
+ }
90
+ if (structureOption !== undefined && !["simple", "module"].includes(structureOption)) {
91
+ optionErrors.push("--structure must be simple or module");
92
+ }
93
+ if (
94
+ requestedPackageManager !== undefined &&
95
+ !["npm", "pnpm"].includes(requestedPackageManager)
96
+ ) {
97
+ optionErrors.push("--pm must be npm or pnpm");
98
+ }
99
+ if (noTailwind && hasOption("tailwind")) {
100
+ optionErrors.push("Use only one of --tailwind or --no-tailwind");
101
+ }
102
+ if (noAxios && hasOption("axios")) {
103
+ optionErrors.push("Use only one of --axios or --no-axios");
104
+ }
105
+ if (
106
+ iconsOption !== undefined &&
107
+ !["react-icons", "animateicons", "none"].includes(iconsOption)
108
+ ) {
109
+ optionErrors.push("--icons must be react-icons, animateicons, or none");
110
+ }
111
+ if (args.some((argument) => argument.startsWith("--template=")) && !templateOption) {
112
+ optionErrors.push("--template must include a template name");
113
+ }
114
+ if (optionErrors.length) {
115
+ console.error(
116
+ `${optionErrors.join("\n")}\nAllowed options: ${allowedOptions.join(", ")}`,
117
+ );
118
+ process.exit(1);
119
+ }
120
+ let projectName = positionalArgs[0];
14
121
  const validProjectName = (name) => /^[a-z0-9][a-z0-9_-]*$/.test(name);
15
122
 
16
123
  if (!projectName && stdin.isTTY) {
@@ -35,10 +142,11 @@ if (!projectName || !validProjectName(projectName)) {
35
142
  process.exit(1);
36
143
  }
37
144
 
38
- const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
39
- ? "pnpm"
40
- : "npm";
145
+ const packageManager =
146
+ requestedPackageManager ??
147
+ (process.env.npm_config_user_agent?.startsWith("pnpm/") ? "pnpm" : "npm");
41
148
  const root = resolve(process.cwd(), projectName);
149
+ let rootCreated = false;
42
150
  const clientFolder = `${projectName}-client`;
43
151
  const serverFolder = `${projectName}-server`;
44
152
  const packageRoot = fileURLToPath(new URL("../", import.meta.url));
@@ -46,8 +154,94 @@ const scriptRoot = fileURLToPath(new URL("../scripts/", import.meta.url));
46
154
  const cliPackage = JSON.parse(
47
155
  await readFile(join(packageRoot, "package.json"), "utf8"),
48
156
  );
157
+ const delay = (milliseconds) =>
158
+ new Promise((resolveDelay) => setTimeout(resolveDelay, milliseconds));
159
+ const removeIncompleteProject = async () => {
160
+ process.off("SIGINT", handleCreationSignal);
161
+ process.off("SIGTERM", handleCreationSignal);
162
+ if (!rootCreated) return;
163
+ rootCreated = false;
164
+ for (let attempt = 0; attempt < 6; attempt += 1) {
165
+ try {
166
+ await rm(root, { recursive: true, force: true });
167
+ return;
168
+ } catch (error) {
169
+ if (!["EBUSY", "ENOTEMPTY"].includes(error.code) || attempt === 5) {
170
+ console.error(`Unable to remove the incomplete project directory: ${error.message}`);
171
+ return;
172
+ }
173
+ await delay(100 * (attempt + 1));
174
+ }
175
+ }
176
+ };
177
+ const handleCreationSignal = async () => {
178
+ if (creationCancelled) return;
179
+ creationCancelled = true;
180
+ const child = activeChild;
181
+ if (child && child.exitCode === null && child.signalCode === null) {
182
+ child.kill("SIGTERM");
183
+ await Promise.race([
184
+ new Promise((resolveClose) => child.once("close", resolveClose)),
185
+ delay(3000),
186
+ ]);
187
+ if (child.exitCode === null && child.signalCode === null) {
188
+ child.kill("SIGKILL");
189
+ await new Promise((resolveClose) => child.once("close", resolveClose));
190
+ }
191
+ }
192
+ await removeIncompleteProject();
193
+ process.exit(130);
194
+ };
195
+
196
+ function parseSemver(version) {
197
+ const match =
198
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version);
199
+ if (!match) throw new Error(`Invalid semantic version: ${version}`);
200
+ const prerelease = match[4]?.split(".") ?? [];
201
+ return {
202
+ major: BigInt(match[1]),
203
+ minor: BigInt(match[2]),
204
+ patch: BigInt(match[3]),
205
+ prerelease,
206
+ };
207
+ }
208
+
209
+ function compareSemver(left, right) {
210
+ const a = parseSemver(left);
211
+ const b = parseSemver(right);
212
+ for (const component of ["major", "minor", "patch"]) {
213
+ if (a[component] !== b[component]) {
214
+ return a[component] < b[component] ? -1 : 1;
215
+ }
216
+ }
217
+ if (!a.prerelease.length || !b.prerelease.length) {
218
+ return a.prerelease.length === b.prerelease.length
219
+ ? 0
220
+ : a.prerelease.length
221
+ ? -1
222
+ : 1;
223
+ }
224
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
225
+ for (let index = 0; index < length; index += 1) {
226
+ const leftId = a.prerelease[index];
227
+ const rightId = b.prerelease[index];
228
+ if (leftId === undefined || rightId === undefined) {
229
+ return leftId === rightId ? 0 : leftId === undefined ? -1 : 1;
230
+ }
231
+ if (leftId === rightId) continue;
232
+ const leftNumeric = /^\d+$/.test(leftId);
233
+ const rightNumeric = /^\d+$/.test(rightId);
234
+ if (leftNumeric && rightNumeric) {
235
+ return BigInt(leftId) < BigInt(rightId) ? -1 : 1;
236
+ }
237
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
238
+ return leftId < rightId ? -1 : 1;
239
+ }
240
+ return 0;
241
+ }
49
242
 
50
243
  async function updateIfOutdated() {
244
+ if (skipUpdateCheck) return;
51
245
  const { version: installedVersion } = cliPackage;
52
246
  const registry = (process.env.npm_config_registry || "https://registry.npmjs.org")
53
247
  .replace(/\/$/, "");
@@ -67,7 +261,12 @@ async function updateIfOutdated() {
67
261
  return;
68
262
  }
69
263
 
70
- if (installedVersion === latestVersion) return;
264
+ try {
265
+ if (compareSemver(latestVersion, installedVersion) <= 0) return;
266
+ } catch (error) {
267
+ console.warn(`\nCould not compare CLI versions: ${error.message}`);
268
+ return;
269
+ }
71
270
  if (!stdin.isTTY) {
72
271
  console.warn(
73
272
  `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}). Run ${packageManager} create vanilla-vite@latest to use it.`,
@@ -84,16 +283,21 @@ async function updateIfOutdated() {
84
283
  ]);
85
284
  if (!useLatest) return;
86
285
 
286
+ const relaunchArgs = [
287
+ ...args.filter((arg) => arg !== "--no-update-check"),
288
+ ...(args.some((arg) => !arg.startsWith("--")) ? [] : [projectName]),
289
+ "--no-update-check",
290
+ ];
87
291
  const updateArgs =
88
292
  packageManager === "pnpm"
89
- ? ["dlx", "create-vanilla-vite@latest", ...args]
293
+ ? ["dlx", "create-vanilla-vite@latest", ...relaunchArgs]
90
294
  : [
91
295
  "exec",
92
296
  "--yes",
93
297
  "--package=create-vanilla-vite@latest",
94
298
  "--",
95
299
  "create-vanilla-vite",
96
- ...args,
300
+ ...relaunchArgs,
97
301
  ];
98
302
  try {
99
303
  await run(packageManager, updateArgs, process.cwd());
@@ -104,11 +308,16 @@ async function updateIfOutdated() {
104
308
  process.exit(0);
105
309
  }
106
310
 
107
- function run(command, commandArgs, cwd) {
311
+ function run(command, commandArgs, cwd, env = process.env) {
108
312
  return new Promise((resolveRun, rejectRun) => {
109
- const child = spawn(command, commandArgs, { cwd, stdio: "inherit" });
110
- child.once("error", rejectRun);
313
+ const child = spawn(command, commandArgs, { cwd, stdio: "inherit", env });
314
+ activeChild = child;
315
+ child.once("error", (error) => {
316
+ if (activeChild === child) activeChild = undefined;
317
+ rejectRun(error);
318
+ });
111
319
  child.once("close", (code, signal) => {
320
+ if (activeChild === child) activeChild = undefined;
112
321
  if (code === 0) resolveRun();
113
322
  else {
114
323
  rejectRun(
@@ -119,14 +328,17 @@ function run(command, commandArgs, cwd) {
119
328
  });
120
329
  }
121
330
 
122
- async function selectOption(question, options, defaultIndex = 0) {
331
+ async function selectOption(question, options, defaultIndex = 0, color = "cyan") {
123
332
  if (!stdin.isTTY) return options[defaultIndex].value;
124
333
  let selected = defaultIndex;
125
334
  emitKeypressEvents(stdin);
126
335
 
127
336
  return new Promise((resolveSelection) => {
128
337
  function render() {
129
- stdout.write(`\r\x1b[2K${question}\n`);
338
+ const prompt = stdout.isTTY && process.env.NO_COLOR === undefined
339
+ ? `\x1b[1;${color === "cyan" ? "36" : "33"}m${question}\x1b[0m`
340
+ : question;
341
+ stdout.write(`\r\x1b[2K${prompt}\n`);
130
342
  for (const [index, option] of options.entries()) {
131
343
  stdout.write(` ${index === selected ? "❯" : " "} ${option.label}\n`);
132
344
  }
@@ -149,8 +361,14 @@ async function selectOption(question, options, defaultIndex = 0) {
149
361
  options.length;
150
362
  render();
151
363
  } else if (key?.name === "return") finish(options[selected].value);
152
- else if (key?.name === "escape" || (key?.ctrl && key.name === "c")) {
364
+ else if (key?.name === "escape") {
153
365
  finish(options[defaultIndex].value);
366
+ } else if (key?.ctrl && key.name === "c") {
367
+ stdin.off("keypress", onKeypress);
368
+ stdin.setRawMode(false);
369
+ stdin.pause();
370
+ stdout.write(`\x1b[${options.length + 2}B\n`);
371
+ void handleCreationSignal();
154
372
  }
155
373
  }
156
374
 
@@ -161,12 +379,27 @@ async function selectOption(question, options, defaultIndex = 0) {
161
379
  });
162
380
  }
163
381
 
382
+ function chooseOption(question, options, defaultIndex = 0, color = "cyan") {
383
+ return yes
384
+ ? Promise.resolve(options[defaultIndex].value)
385
+ : selectOption(question, options, defaultIndex, color);
386
+ }
387
+
164
388
  async function configureTailwind(clientRoot) {
165
- const viteConfigName = (await readdir(clientRoot)).find((file) =>
389
+ let viteConfigName = (await readdir(clientRoot)).find((file) =>
166
390
  /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
167
391
  );
168
392
  if (!viteConfigName) {
169
- throw new Error("Could not find the Vite config to configure Tailwind CSS.");
393
+ const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
394
+ viteConfigName = `vite.config.${isTypeScript ? "ts" : "js"}`;
395
+ await writeFile(
396
+ join(clientRoot, viteConfigName),
397
+ 'import { defineConfig } from "vite";\n' +
398
+ 'import tailwindcss from "@tailwindcss/vite";\n\n' +
399
+ "export default defineConfig({\n" +
400
+ " plugins: [tailwindcss()],\n" +
401
+ "});\n",
402
+ );
170
403
  }
171
404
 
172
405
  const viteConfigPath = join(clientRoot, viteConfigName);
@@ -205,9 +438,12 @@ async function configureTailwind(clientRoot) {
205
438
  throw new Error("Could not find the frontend entry file to configure Tailwind CSS.");
206
439
  }
207
440
  const entry = await readFile(entryPath, "utf8");
208
- const cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
441
+ let cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
209
442
  if (!cssImport) {
210
- throw new Error("Could not find a CSS import to configure Tailwind CSS.");
443
+ const cssPath = join(dirname(entryPath), "style.css");
444
+ await writeFile(cssPath, '@import "tailwindcss";\n');
445
+ await writeFile(entryPath, `import "./style.css";\n${entry}`);
446
+ cssImport = ['import "./style.css";', "./style.css"];
211
447
  }
212
448
  const cssPath = resolve(dirname(entryPath), cssImport[1]);
213
449
  const css = await readFile(cssPath, "utf8");
@@ -216,45 +452,794 @@ async function configureTailwind(clientRoot) {
216
452
  }
217
453
  }
218
454
 
455
+ async function configureStrictPort(clientRoot) {
456
+ let configName = (await readdir(clientRoot)).find((file) =>
457
+ /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
458
+ );
459
+ if (!configName) {
460
+ const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
461
+ configName = `vite.config.${isTypeScript ? "ts" : "js"}`;
462
+ await writeFile(
463
+ join(clientRoot, configName),
464
+ 'import { defineConfig } from "vite";\n\nexport default defineConfig({});\n',
465
+ );
466
+ }
467
+
468
+ const configPath = join(clientRoot, configName);
469
+ let config = await readFile(configPath, "utf8");
470
+ if (/\bstrictPort\s*:/.test(config)) {
471
+ config = config.replace(/\bstrictPort\s*:\s*(?:true|false)/, "strictPort: true");
472
+ } else if (/\bserver\s*:\s*\{/.test(config)) {
473
+ config = config.replace(/\bserver\s*:\s*\{/, "server: { strictPort: true,");
474
+ } else {
475
+ const configObject = /(\bdefineConfig\s*\(\s*\{|\bexport\s+default\s*\{)/;
476
+ if (!configObject.test(config)) {
477
+ console.warn(
478
+ `Could not configure strictPort in ${configName}; the Vite config shape was not recognized.`,
479
+ );
480
+ return;
481
+ }
482
+ config = config.replace(configObject, "$1\n server: { strictPort: true },");
483
+ }
484
+ await writeFile(configPath, config);
485
+ }
486
+
487
+ async function scaffoldReactRouter(clientRoot, useTailwind) {
488
+ const sourceRoot = join(clientRoot, "src");
489
+ const sourceFiles = await readdir(sourceRoot);
490
+ const appFile = sourceFiles.find((file) => /^App\.(?:jsx|tsx)$/.test(file));
491
+ const entryFile = sourceFiles.find((file) => /^main\.(?:jsx|tsx)$/.test(file));
492
+ if (!appFile || !entryFile) {
493
+ throw new Error("Could not find the React app and entry files to configure routing.");
494
+ }
495
+
496
+ const typed = appFile.endsWith(".tsx");
497
+ const extension = typed ? "tsx" : "jsx";
498
+ const appPath = join(sourceRoot, appFile);
499
+ const entryPath = join(sourceRoot, entryFile);
500
+ const entry = await readFile(entryPath, "utf8");
501
+ const cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
502
+ if (!cssImport) {
503
+ throw new Error("Could not find a CSS import for the React Router starter.");
504
+ }
505
+
506
+ const cssPath = resolve(sourceRoot, cssImport[1]);
507
+ const tailwindImport = (await readFile(cssPath, "utf8"))
508
+ .includes('@import "tailwindcss";')
509
+ ? '@import "tailwindcss";\n'
510
+ : "";
511
+ const styles = useTailwind
512
+ ? {
513
+ shell: "min-h-screen flex flex-col bg-[#f5f7f4] text-[#17231f]",
514
+ container: "w-[calc(100%_-_2rem)] sm:w-[calc(100%_-_3rem)] max-w-[1040px] mx-auto",
515
+ header: "min-h-[72px] sm:min-h-[84px] flex items-center justify-between border-b border-[#dfe6df]",
516
+ brand: "flex items-center gap-[10px] text-sm font-bold text-[#17231f] no-underline",
517
+ brandMark: "w-[30px] h-[30px] grid place-items-center rounded-[9px] bg-[#315d4a] text-white",
518
+ nav: "flex items-center gap-2",
519
+ navLink: "min-h-10 flex items-center px-[10px] sm:px-[14px] rounded-lg text-sm text-[#5b6861] no-underline hover:bg-[#e7eee8] hover:text-[#244b39]",
520
+ navActive: "bg-[#e7eee8] text-[#244b39]",
521
+ page: "flex-1",
522
+ footer: "py-6 border-t border-[#dfe6df] text-[13px] text-[#78857d]",
523
+ home: "py-[72px] sm:pt-[clamp(72px,12vw,132px)] sm:pb-[84px]",
524
+ eyebrow: "text-xs font-bold tracking-[0.12em] text-[#557663]",
525
+ title: "max-w-[680px] my-[18px] text-[clamp(40px,7vw,68px)] font-semibold leading-[1.05] tracking-[-0.055em]",
526
+ authTitle: "max-w-[680px] my-[18px] text-[clamp(38px,7vw,52px)] font-semibold leading-[1.05] tracking-[-0.055em]",
527
+ copy: "max-w-[550px] mb-7 text-[17px] leading-[1.7] text-[#627068]",
528
+ button: "min-h-[46px] inline-flex items-center justify-center gap-[14px] px-[18px] rounded-lg font-semibold no-underline cursor-pointer",
529
+ buttonPrimary: "bg-[#315d4a] text-white hover:bg-[#244b39]",
530
+ grid: "grid grid-cols-1 sm:grid-cols-2 gap-4 mt-14 sm:mt-[72px]",
531
+ card: "min-h-[164px] p-6 border border-[#dfe6df] rounded-xl bg-[#fbfcfa]",
532
+ cardIndex: "text-xs font-bold tracking-[0.12em] text-[#557663]",
533
+ cardTitle: "mt-4 mb-2 text-lg",
534
+ cardCopy: "m-0 leading-[1.6] text-[#627068]",
535
+ code: "text-[#315d4a]",
536
+ auth: "w-full max-w-[440px] mx-auto py-[88px] pb-[72px]",
537
+ authIntro: "",
538
+ authCopy: "max-w-[550px] mb-8 text-[17px] leading-[1.7] text-[#627068]",
539
+ form: "grid gap-[10px]",
540
+ label: "mt-2 text-sm font-semibold text-[#35443c]",
541
+ input: "w-full min-h-[46px] px-[13px] border border-[#ccd7ce] rounded-lg bg-white text-[#17231f] focus:border-[#557663] focus:outline-3 focus:outline-[#dce8df]",
542
+ formButton: "mt-3",
543
+ notice: "min-h-6 m-0 text-sm leading-[1.5] text-[#557663]",
544
+ back: "inline-block mt-[18px] text-sm text-[#486353] hover:underline",
545
+ }
546
+ : {
547
+ shell: "app-shell",
548
+ container: "layout-container",
549
+ header: "site-header",
550
+ brand: "brand",
551
+ brandMark: "brand-mark",
552
+ nav: "site-nav",
553
+ navLink: "nav-link",
554
+ navActive: "is-active",
555
+ page: "page-content",
556
+ footer: "site-footer",
557
+ home: "home-page",
558
+ eyebrow: "eyebrow",
559
+ title: "",
560
+ authTitle: "",
561
+ copy: "hero-copy",
562
+ button: "button",
563
+ buttonPrimary: "button-primary",
564
+ grid: "route-grid",
565
+ card: "route-card",
566
+ cardIndex: "card-index",
567
+ cardTitle: "",
568
+ cardCopy: "",
569
+ code: "",
570
+ auth: "auth-page",
571
+ authIntro: "auth-intro",
572
+ authCopy: "hero-copy",
573
+ form: "login-form",
574
+ label: "",
575
+ input: "",
576
+ formButton: "",
577
+ notice: "form-notice",
578
+ back: "back-link",
579
+ };
580
+ const appCssImport = useTailwind ? "" : 'import "./App.css";\n';
581
+ const homeDirectory = join(sourceRoot, "Pages", "Home");
582
+ const authDirectory = join(sourceRoot, "Pages", "Auth");
583
+ await Promise.all([
584
+ mkdir(homeDirectory, { recursive: true }),
585
+ mkdir(authDirectory, { recursive: true }),
586
+ ]);
587
+ await Promise.all([
588
+ writeFile(
589
+ join(sourceRoot, `MainRouter.${extension}`),
590
+ `import { createBrowserRouter } from "react-router";
591
+ import App from "./App";
592
+ import Home from "./Pages/Home/Home";
593
+ import AuthPage from "./Pages/Auth/AuthPage";
594
+
595
+ const MainRouter = createBrowserRouter([
596
+ {
597
+ path: "/",
598
+ element: <App />,
599
+ children: [
600
+ { index: true, element: <Home /> },
601
+ { path: "login", element: <AuthPage /> },
602
+ ],
603
+ },
604
+ ]);
605
+
606
+ // eslint-disable-next-line react-refresh/only-export-components
607
+ export default MainRouter;
608
+ `,
609
+ ),
610
+ writeFile(
611
+ appPath,
612
+ `import { NavLink, Outlet } from "react-router";
613
+ ${appCssImport}
614
+
615
+ function App() {
616
+ return (
617
+ <div className="${styles.shell}">
618
+ <header className="${styles.container} ${styles.header}">
619
+ <NavLink className="${styles.brand}" to="/" end>
620
+ <span className="${styles.brandMark}" aria-hidden="true">V</span>
621
+ <span>Workspace starter</span>
622
+ </NavLink>
623
+ <nav className="${styles.nav}" aria-label="Main navigation">
624
+ <NavLink to="/" end className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
625
+ Home
626
+ </NavLink>
627
+ <NavLink to="/login" className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
628
+ Login
629
+ </NavLink>
630
+ </nav>
631
+ </header>
632
+ <main className="${styles.container} ${styles.page}">
633
+ <Outlet />
634
+ </main>
635
+ <footer className="${styles.container} ${styles.footer}">A small starting point for your next project.</footer>
636
+ </div>
637
+ );
638
+ }
639
+
640
+ export default App;
641
+ `,
642
+ ),
643
+ writeFile(
644
+ join(homeDirectory, `Home.${extension}`),
645
+ `import { Link } from "react-router";
646
+
647
+ function Home() {
648
+ return (
649
+ <section className="${styles.home}">
650
+ <p className="${styles.eyebrow}">YOUR PROJECT STARTS HERE</p>
651
+ <h1 className="${styles.title}">A faster start for your next project.</h1>
652
+ <p className="${styles.copy}">
653
+ This starter makes setting up your development environment quick and
654
+ straightforward. React Router is ready with Home and Login pages so you
655
+ can test navigation right away.
656
+ </p>
657
+ <Link className="${styles.button} ${styles.buttonPrimary}" to="/login">Visit the login page <span aria-hidden="true">→</span></Link>
658
+ <div className="${styles.grid}">
659
+ <article className="${styles.card}">
660
+ <span className="${styles.cardIndex}">01</span>
661
+ <h2 className="${styles.cardTitle}">Home</h2>
662
+ <p className="${styles.cardCopy}">An example landing page at <code className="${styles.code}">/</code> to help you get started.</p>
663
+ </article>
664
+ <article className="${styles.card}">
665
+ <span className="${styles.cardIndex}">02</span>
666
+ <h2 className="${styles.cardTitle}">Login</h2>
667
+ <p className="${styles.cardCopy}">A sample page at <code className="${styles.code}">/login</code> for checking route navigation.</p>
668
+ </article>
669
+ </div>
670
+ </section>
671
+ );
672
+ }
673
+
674
+ export default Home;
675
+ `,
676
+ ),
677
+ writeFile(
678
+ join(authDirectory, `AuthPage.${extension}`),
679
+ `import { useState${typed ? ", type FormEvent" : ""} } from "react";
680
+ import { Link } from "react-router";
681
+
682
+ function AuthPage() {
683
+ const [notice, setNotice] = useState("");
684
+
685
+ function handleSubmit(event${typed ? ": FormEvent<HTMLFormElement>" : ""}) {
686
+ event.preventDefault();
687
+ setNotice("This starter form is ready to connect to your authentication service.");
688
+ }
689
+
690
+ return (
691
+ <section className="${styles.auth}">
692
+ <div className="${styles.authIntro}">
693
+ <p className="${styles.eyebrow}">WELCOME BACK</p>
694
+ <h1 className="${styles.authTitle}">Login</h1>
695
+ <p className="${styles.authCopy}">Sign in to continue to your workspace.</p>
696
+ </div>
697
+ <form className="${styles.form}" onSubmit={handleSubmit}>
698
+ <label className="${styles.label}" htmlFor="email">Email address</label>
699
+ <input className="${styles.input}" id="email" name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
700
+ <label className="${styles.label}" htmlFor="password">Password</label>
701
+ <input className="${styles.input}" id="password" name="password" type="password" autoComplete="current-password" placeholder="Enter your password" required />
702
+ <button className="${styles.button} ${styles.buttonPrimary} ${styles.formButton}" type="submit">Continue</button>
703
+ <p className="${styles.notice}" role="status">{notice}</p>
704
+ </form>
705
+ <Link className="${styles.back}" to="/">← Back to home</Link>
706
+ </section>
707
+ );
708
+ }
709
+
710
+ export default AuthPage;
711
+ `,
712
+ ),
713
+ writeFile(
714
+ cssPath,
715
+ useTailwind
716
+ ? tailwindImport
717
+ : `${tailwindImport}:root {
718
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
719
+ color: #17231f;
720
+ background: #f5f7f4;
721
+ font-synthesis: none;
722
+ text-rendering: optimizeLegibility;
723
+ -webkit-font-smoothing: antialiased;
724
+ -moz-osx-font-smoothing: grayscale;
725
+ }
726
+
727
+ * {
728
+ box-sizing: border-box;
729
+ }
730
+
731
+ body {
732
+ min-width: 320px;
733
+ min-height: 100vh;
734
+ margin: 0;
735
+ }
736
+
737
+ button,
738
+ input {
739
+ font: inherit;
740
+ }
741
+
742
+ a {
743
+ color: inherit;
744
+ }
745
+ `,
746
+ ),
747
+ ...(!useTailwind
748
+ ? [
749
+ writeFile(
750
+ join(sourceRoot, "App.css"),
751
+ `.app-shell {
752
+ min-height: 100vh;
753
+ display: flex;
754
+ flex-direction: column;
755
+ }
756
+
757
+ .layout-container,
758
+ .site-header,
759
+ .page-content,
760
+ .site-footer {
761
+ width: min(100% - 48px, 1040px);
762
+ margin-inline: auto;
763
+ }
764
+
765
+ .site-header {
766
+ min-height: 84px;
767
+ display: flex;
768
+ align-items: center;
769
+ justify-content: space-between;
770
+ border-bottom: 1px solid #dfe6df;
771
+ }
772
+
773
+ .brand,
774
+ .site-nav,
775
+ .nav-link {
776
+ display: flex;
777
+ align-items: center;
778
+ }
779
+
780
+ .brand {
781
+ gap: 10px;
782
+ color: #17231f;
783
+ font-size: 14px;
784
+ font-weight: 700;
785
+ text-decoration: none;
786
+ }
787
+
788
+ .brand-mark {
789
+ width: 30px;
790
+ height: 30px;
791
+ display: grid;
792
+ place-items: center;
793
+ border-radius: 9px;
794
+ background: #315d4a;
795
+ color: #fff;
796
+ }
797
+
798
+ .site-nav {
799
+ gap: 8px;
800
+ }
801
+
802
+ .nav-link {
803
+ min-height: 40px;
804
+ padding: 0 14px;
805
+ border-radius: 8px;
806
+ color: #5b6861;
807
+ font-size: 14px;
808
+ text-decoration: none;
809
+ }
810
+
811
+ .nav-link:hover,
812
+ .nav-link.is-active {
813
+ background: #e7eee8;
814
+ color: #244b39;
815
+ }
816
+
817
+ .page-content {
818
+ flex: 1;
819
+ }
820
+
821
+ .home-page {
822
+ padding: clamp(72px, 12vw, 132px) 0 84px;
823
+ }
824
+
825
+ .eyebrow,
826
+ .card-index {
827
+ color: #557663;
828
+ font-size: 12px;
829
+ font-weight: 700;
830
+ letter-spacing: 0.12em;
831
+ }
832
+
833
+ .home-page h1,
834
+ .auth-intro h1 {
835
+ max-width: 680px;
836
+ margin: 18px 0;
837
+ font-size: clamp(40px, 7vw, 68px);
838
+ font-weight: 600;
839
+ letter-spacing: -0.055em;
840
+ line-height: 1.05;
841
+ }
842
+
843
+ .hero-copy {
844
+ max-width: 550px;
845
+ margin: 0 0 28px;
846
+ color: #627068;
847
+ font-size: 17px;
848
+ line-height: 1.7;
849
+ }
850
+
851
+ .button {
852
+ min-height: 46px;
853
+ display: inline-flex;
854
+ align-items: center;
855
+ justify-content: center;
856
+ gap: 14px;
857
+ padding: 0 18px;
858
+ border: 0;
859
+ border-radius: 8px;
860
+ cursor: pointer;
861
+ font-weight: 600;
862
+ text-decoration: none;
863
+ }
864
+
865
+ .button-primary {
866
+ background: #315d4a;
867
+ color: white;
868
+ }
869
+
870
+ .button-primary:hover {
871
+ background: #244b39;
872
+ }
873
+
874
+ .route-grid {
875
+ display: grid;
876
+ grid-template-columns: repeat(2, minmax(0, 1fr));
877
+ gap: 16px;
878
+ margin-top: 72px;
879
+ }
880
+
881
+ .route-card {
882
+ min-height: 164px;
883
+ padding: 24px;
884
+ border: 1px solid #dfe6df;
885
+ border-radius: 12px;
886
+ background: #fbfcfa;
887
+ }
888
+
889
+ .route-card h2 {
890
+ margin: 16px 0 8px;
891
+ font-size: 18px;
892
+ }
893
+
894
+ .route-card p {
895
+ margin: 0;
896
+ color: #627068;
897
+ line-height: 1.6;
898
+ }
899
+
900
+ .route-card code {
901
+ color: #315d4a;
902
+ }
903
+
904
+ .auth-page {
905
+ width: min(100%, 440px);
906
+ margin: 0 auto;
907
+ padding: 88px 0 72px;
908
+ }
909
+
910
+ .auth-intro h1 {
911
+ font-size: clamp(38px, 7vw, 52px);
912
+ }
913
+
914
+ .auth-intro .hero-copy {
915
+ margin-bottom: 32px;
916
+ }
917
+
918
+ .login-form {
919
+ display: grid;
920
+ gap: 10px;
921
+ }
922
+
923
+ .login-form label {
924
+ margin-top: 8px;
925
+ color: #35443c;
926
+ font-size: 14px;
927
+ font-weight: 600;
928
+ }
929
+
930
+ .login-form input {
931
+ width: 100%;
932
+ min-height: 46px;
933
+ padding: 0 13px;
934
+ border: 1px solid #ccd7ce;
935
+ border-radius: 8px;
936
+ background: #fff;
937
+ color: #17231f;
938
+ }
939
+
940
+ .login-form input:focus {
941
+ border-color: #557663;
942
+ outline: 3px solid #dce8df;
943
+ }
944
+
945
+ .login-form .button {
946
+ margin-top: 12px;
947
+ }
948
+
949
+ .form-notice {
950
+ min-height: 24px;
951
+ margin: 2px 0 0;
952
+ color: #557663;
953
+ font-size: 14px;
954
+ line-height: 1.5;
955
+ }
956
+
957
+ .back-link {
958
+ display: inline-block;
959
+ margin-top: 18px;
960
+ color: #486353;
961
+ font-size: 14px;
962
+ text-decoration: none;
963
+ }
964
+
965
+ .back-link:hover {
966
+ text-decoration: underline;
967
+ }
968
+
969
+ .site-footer {
970
+ padding: 24px 0;
971
+ border-top: 1px solid #dfe6df;
972
+ color: #78857d;
973
+ font-size: 13px;
974
+ }
975
+
976
+ @media (max-width: 560px) {
977
+ .site-header,
978
+ .page-content,
979
+ .site-footer {
980
+ width: min(100% - 32px, 1040px);
981
+ }
982
+
983
+ .site-header {
984
+ min-height: 72px;
985
+ }
986
+
987
+ .nav-link {
988
+ padding: 0 10px;
989
+ }
990
+
991
+ .route-grid {
992
+ grid-template-columns: 1fr;
993
+ margin-top: 56px;
994
+ }
995
+ }
996
+ `,
997
+ ),
998
+ ]
999
+ : []),
1000
+ writeFile(
1001
+ entryPath,
1002
+ `import { StrictMode } from "react";
1003
+ import { createRoot } from "react-dom/client";
1004
+ import { RouterProvider } from "react-router/dom";
1005
+ import MainRouter from "./MainRouter";
1006
+ ${cssImport[0]};
1007
+
1008
+ createRoot(document.getElementById("root")${typed ? "!" : ""}).render(
1009
+ <StrictMode>
1010
+ <RouterProvider router={MainRouter} />
1011
+ </StrictMode>,
1012
+ );
1013
+ `,
1014
+ ),
1015
+ ]);
1016
+
1017
+ return true;
1018
+ }
1019
+
1020
+ async function scaffoldBackendStatus(clientRoot) {
1021
+ const indexPath = join(clientRoot, "index.html");
1022
+ const html = await readFile(indexPath, "utf8");
1023
+ if (!/<\/body\s*>/i.test(html)) {
1024
+ throw new Error("Could not find the closing body tag for the backend status control.");
1025
+ }
1026
+ await writeFile(
1027
+ indexPath,
1028
+ html.replace(
1029
+ /<\/body\s*>/i,
1030
+ ' <script type="module" src="/backend-status.js"></script>\n</body>',
1031
+ ),
1032
+ );
1033
+ await writeFile(
1034
+ join(clientRoot, "backend-status.js"),
1035
+ `if (import.meta.env.DEV) {
1036
+ import("./backend-status.css");
1037
+ const apiUrl = (import.meta.env.VITE_API_URL || "http://localhost:4000").replace(/\\/+$/, "");
1038
+ const panel = document.createElement("aside");
1039
+ panel.className = "backend-status";
1040
+ panel.setAttribute("aria-label", "Backend connection");
1041
+ panel.innerHTML = \`
1042
+ <span class="backend-status__dot" aria-hidden="true"></span>
1043
+ <div class="backend-status__content">
1044
+ <strong class="backend-status__title">Backend</strong>
1045
+ <span class="backend-status__message" role="status" aria-live="polite">Not checked yet</span>
1046
+ </div>
1047
+ <button class="backend-status__button" type="button">Check connection</button>
1048
+ \`;
1049
+
1050
+ const message = panel.querySelector(".backend-status__message");
1051
+ const button = panel.querySelector(".backend-status__button");
1052
+ button.addEventListener("click", async () => {
1053
+ button.disabled = true;
1054
+ panel.dataset.state = "checking";
1055
+ message.textContent = "Checking…";
1056
+ const controller = new AbortController();
1057
+ const timeout = setTimeout(() => controller.abort(), 5000);
1058
+ try {
1059
+ const response = await fetch(\`\${apiUrl}/api/health\`, {
1060
+ headers: { Accept: "application/json" },
1061
+ signal: controller.signal,
1062
+ });
1063
+ const result = await response.json();
1064
+ if (!response.ok || result.status !== "ok") {
1065
+ throw new Error("Backend health check returned an unexpected response.");
1066
+ }
1067
+ panel.dataset.state = "connected";
1068
+ message.textContent = "Connected";
1069
+ } catch {
1070
+ panel.dataset.state = "disconnected";
1071
+ message.textContent = "Unavailable — check the server and network";
1072
+ } finally {
1073
+ clearTimeout(timeout);
1074
+ button.disabled = false;
1075
+ }
1076
+ });
1077
+
1078
+ document.body.append(panel);
1079
+ }
1080
+ `,
1081
+ );
1082
+ await writeFile(
1083
+ join(clientRoot, "backend-status.css"),
1084
+ `.backend-status {
1085
+ position: fixed;
1086
+ z-index: 1000;
1087
+ right: 18px;
1088
+ bottom: 18px;
1089
+ display: grid;
1090
+ grid-template-columns: 9px minmax(0, 1fr) auto;
1091
+ align-items: center;
1092
+ gap: 12px;
1093
+ width: min(390px, calc(100vw - 36px));
1094
+ padding: 14px;
1095
+ border: 1px solid #dfe6df;
1096
+ border-radius: 12px;
1097
+ background: #fbfcfa;
1098
+ color: #17231f;
1099
+ box-shadow: 0 8px 28px rgb(23 35 31 / 12%);
1100
+ font: 13px/1.4 Inter, ui-sans-serif, system-ui, sans-serif;
1101
+ }
1102
+
1103
+ .backend-status__dot {
1104
+ width: 9px;
1105
+ height: 9px;
1106
+ border-radius: 50%;
1107
+ background: #9aa59e;
1108
+ }
1109
+
1110
+ .backend-status[data-state="checking"] .backend-status__dot {
1111
+ background: #c28a30;
1112
+ }
1113
+
1114
+ .backend-status[data-state="connected"] .backend-status__dot {
1115
+ background: #31835b;
1116
+ }
1117
+
1118
+ .backend-status[data-state="disconnected"] .backend-status__dot {
1119
+ background: #bd4d43;
1120
+ }
1121
+
1122
+ .backend-status__content {
1123
+ display: grid;
1124
+ gap: 2px;
1125
+ min-width: 0;
1126
+ }
1127
+
1128
+ .backend-status__title {
1129
+ font-size: 13px;
1130
+ }
1131
+
1132
+ .backend-status__message {
1133
+ color: #627068;
1134
+ font-size: 12px;
1135
+ }
1136
+
1137
+ .backend-status__button {
1138
+ min-height: 36px;
1139
+ padding: 0 12px;
1140
+ border: 0;
1141
+ border-radius: 8px;
1142
+ background: #315d4a;
1143
+ color: #fff;
1144
+ font: inherit;
1145
+ font-weight: 600;
1146
+ cursor: pointer;
1147
+ }
1148
+
1149
+ .backend-status__button:hover:not(:disabled) {
1150
+ background: #244b39;
1151
+ }
1152
+
1153
+ .backend-status__button:focus-visible {
1154
+ outline: 3px solid #9db9a5;
1155
+ outline-offset: 2px;
1156
+ }
1157
+
1158
+ .backend-status__button:disabled {
1159
+ cursor: wait;
1160
+ opacity: 0.7;
1161
+ }
1162
+
1163
+ @media (max-width: 420px) {
1164
+ .backend-status {
1165
+ right: 12px;
1166
+ bottom: 12px;
1167
+ width: calc(100vw - 24px);
1168
+ }
1169
+ }
1170
+ `,
1171
+ );
1172
+ }
1173
+
219
1174
  async function configureFrontend(clientRoot, clientPackage) {
220
- const tailwind = await selectOption("Would you like to install Tailwind CSS?", [
221
- { label: "Yes — add Tailwind CSS v4", value: true },
222
- { label: "No (default)", value: false },
223
- ], 1);
224
- const axios = await selectOption("Would you like to install Axios?", [
225
- { label: "Yes — add Axios", value: true },
226
- { label: "No (default)", value: false },
227
- ], 1);
1175
+ const tailwind = noTailwind
1176
+ ? false
1177
+ : hasOption("tailwind")
1178
+ ? true
1179
+ : await chooseOption("Would you like to install Tailwind CSS?", [
1180
+ { label: "Yes — add Tailwind CSS v4", value: true },
1181
+ { label: "No", value: false },
1182
+ ]);
1183
+ const axios = hasOption("axios")
1184
+ ? true
1185
+ : noAxios
1186
+ ? false
1187
+ : await chooseOption("Would you like to install Axios?", [
1188
+ { label: "Yes — add Axios", value: true },
1189
+ { label: "No", value: false },
1190
+ ]);
228
1191
  const isReact = Boolean(
229
1192
  clientPackage.dependencies?.react || clientPackage.devDependencies?.react,
230
1193
  );
231
- const installIcons =
1194
+ const installRouter =
232
1195
  isReact &&
233
- (await selectOption("Would you like to install an icon library?", [
234
- { label: "Yes", value: true },
235
- { label: "No (default)", value: false },
236
- ], 1));
237
- const icons = installIcons
238
- ? await selectOption("Which React icon library would you like to install?", [
239
- { label: "React Icons (default)", value: ["react-icons", "^5.7.0"] },
240
- { label: "@animateicons/react", value: ["@animateicons/react", "^0.13.0"] },
241
- ])
242
- : null;
1196
+ (hasOption("router")
1197
+ ? true
1198
+ : hasOption("no-router")
1199
+ ? false
1200
+ : await chooseOption("Would you like to install React Router?", [
1201
+ { label: "Yes — add Home and Login pages with navigation", value: true },
1202
+ { label: "No", value: false },
1203
+ ]));
1204
+ const iconPackages = {
1205
+ "react-icons": ["react-icons", "^5.7.0"],
1206
+ animateicons: ["@animateicons/react", "^0.13.0"],
1207
+ };
1208
+ const icons =
1209
+ !isReact || iconsOption === "none"
1210
+ ? null
1211
+ : iconsOption
1212
+ ? iconPackages[iconsOption]
1213
+ : (await chooseOption("Would you like to install an icon library?", [
1214
+ { label: "Yes", value: true },
1215
+ { label: "No", value: false },
1216
+ ]))
1217
+ ? await chooseOption("Which React icon library would you like to install?", [
1218
+ { label: "React Icons (default)", value: iconPackages["react-icons"] },
1219
+ { label: "@animateicons/react", value: iconPackages.animateicons },
1220
+ ])
1221
+ : null;
243
1222
 
244
1223
  if (tailwind) {
245
1224
  clientPackage.devDependencies ??= {};
246
- clientPackage.devDependencies["@tailwindcss/vite"] = "^4.3.4";
247
- clientPackage.devDependencies.tailwindcss = "^4.3.4";
1225
+ clientPackage.devDependencies["@tailwindcss/vite"] = "^4.3.5";
1226
+ clientPackage.devDependencies.tailwindcss = "^4.3.5";
248
1227
  await configureTailwind(clientRoot);
249
1228
  }
250
1229
  if (axios) {
251
1230
  clientPackage.dependencies ??= {};
252
- clientPackage.dependencies.axios = "^1.21.0";
1231
+ clientPackage.dependencies.axios = "^1.21.1";
253
1232
  }
254
1233
  if (icons) {
255
1234
  clientPackage.dependencies ??= {};
256
1235
  clientPackage.dependencies[icons[0]] = icons[1];
257
1236
  }
1237
+ if (installRouter) {
1238
+ clientPackage.dependencies ??= {};
1239
+ clientPackage.dependencies["react-router"] = "^7";
1240
+ await scaffoldReactRouter(clientRoot, tailwind);
1241
+ }
1242
+ await configureStrictPort(clientRoot);
258
1243
  }
259
1244
 
260
1245
  async function copyScript(name) {
@@ -262,111 +1247,206 @@ async function copyScript(name) {
262
1247
  await writeFile(join(root, "scripts", name), source);
263
1248
  }
264
1249
 
1250
+ function expressErrorHandlerParameters(language) {
1251
+ return language === "ts"
1252
+ ? `error: unknown,
1253
+ _request: import("express").Request,
1254
+ response: import("express").Response,
1255
+ _next: import("express").NextFunction`
1256
+ : "error, _request, response, _next";
1257
+ }
1258
+
265
1259
  function backendFiles(language, framework) {
266
1260
  const extension = language;
267
1261
  const typeAnnotation = language === "ts" ? ": number" : "";
268
- const request = language === "ts"
269
- ? framework === "express"
270
- ? "request: import('express').Request"
271
- : "request: import('node:http').IncomingMessage"
272
- : "request";
273
- const response = language === "ts"
274
- ? framework === "express"
275
- ? "response: import('express').Response"
276
- : "response: import('node:http').ServerResponse"
277
- : "response";
278
- const app =
279
- framework === "express"
280
- ? `import express from "express";
1262
+ const app = framework === "express"
1263
+ ? `import cors from "cors";
1264
+ import express from "express";
281
1265
 
282
1266
  export function createApp() {
283
1267
  const app = express();
1268
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1269
+ .split(",")
1270
+ .map((origin) => origin.trim());
1271
+ app.use((request, response, next) => {
1272
+ const origin = request.headers.origin;
1273
+ if (origin && !origins.includes("*") && origins.includes(origin)) {
1274
+ response.vary("Origin");
1275
+ }
1276
+ next();
1277
+ });
1278
+ app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
284
1279
  app.use(express.json());
285
1280
  app.get("/", (_request, response) => response.json({ message: "Backend is running" }));
286
1281
  app.get("/api/health", (_request, response) => response.json({ status: "ok" }));
1282
+ app.use((${expressErrorHandlerParameters(language)}) => {
1283
+ console.error(error);
1284
+ response.status(500).json({ error: "Internal Server Error" });
1285
+ });
287
1286
  return app;
288
1287
  }
289
1288
  `
290
1289
  : `import { createServer } from "node:http";
1290
+ import { handleRequest } from "./basicHandler.${extension}";
291
1291
 
292
1292
  export function createApp() {
293
- return createServer((${request}, ${response}) => {
294
- response.writeHead(200, { "content-type": "application/json" });
295
- response.end(JSON.stringify({ message: "Backend is running" }));
296
- });
1293
+ return createServer(handleRequest);
297
1294
  }
298
1295
  `;
299
- const server = `${framework === "express" ? 'import "dotenv/config";\n' : ""}import { createApp } from "./app.${extension}";
1296
+ const basicHandler =
1297
+ framework === "basic"
1298
+ ? `export function handleRequest(
1299
+ request${language === "ts" ? ": import('node:http').IncomingMessage" : ""},
1300
+ response${language === "ts" ? ": import('node:http').ServerResponse" : ""},
1301
+ ) {
1302
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1303
+ .split(",")
1304
+ .map((origin) => origin.trim());
1305
+ const requestOrigin = request.headers.origin;
1306
+ const allowedOrigin = origins.includes("*")
1307
+ ? "*"
1308
+ : typeof requestOrigin === "string" && origins.includes(requestOrigin)
1309
+ ? requestOrigin
1310
+ : undefined;
1311
+ const corsHeaders = {
1312
+ ...(allowedOrigin ? { "access-control-allow-origin": allowedOrigin } : {}),
1313
+ ...(allowedOrigin && allowedOrigin !== "*" ? { vary: "Origin" } : {}),
1314
+ "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1315
+ "access-control-allow-headers": "Content-Type, Authorization",
1316
+ };
1317
+
1318
+ try {
1319
+ if (request.method === "OPTIONS") {
1320
+ response.writeHead(204, corsHeaders);
1321
+ response.end();
1322
+ return;
1323
+ }
1324
+
1325
+ const path = new URL(request.url ?? "/", "http://localhost").pathname;
1326
+ const payload =
1327
+ request.method === "GET" && path === "/"
1328
+ ? { status: 200, body: { message: "Backend is running" } }
1329
+ : request.method === "GET" && path === "/api/health"
1330
+ ? { status: 200, body: { status: "ok" } }
1331
+ : { status: 404, body: { message: "Not Found" } };
1332
+
1333
+ response.writeHead(payload.status, {
1334
+ ...corsHeaders,
1335
+ "content-type": "application/json",
1336
+ });
1337
+ response.end(JSON.stringify(payload.body));
1338
+ } catch (error) {
1339
+ console.error(error);
1340
+ response.writeHead(500, {
1341
+ ...corsHeaders,
1342
+ "content-type": "application/json",
1343
+ });
1344
+ response.end(JSON.stringify({ error: "Internal Server Error" }));
1345
+ }
1346
+ }
1347
+ `
1348
+ : null;
1349
+ const server = `import "dotenv/config";
1350
+ import { createApp } from "./app.${extension}";
300
1351
 
301
1352
  const port${typeAnnotation} = Number(process.env.PORT ?? 4000);
1353
+ const host = process.env.HOST ?? "localhost";
302
1354
  const app = createApp();
303
- app.listen(port, () => {
304
- console.log(\`Backend listening at http://localhost:\${port}\`);
1355
+ const server = app.listen(port, host, () => {
1356
+ console.log(\`Backend listening at http://\${host}:\${port}\`);
305
1357
  });
1358
+ for (const signal of ["SIGINT", "SIGTERM"]) {
1359
+ process.once(signal, () => {
1360
+ server.close((error) => {
1361
+ if (error) {
1362
+ console.error("Unable to close the backend server:", error);
1363
+ process.exitCode = 1;
1364
+ }
1365
+ });
1366
+ });
1367
+ }
306
1368
  `;
307
- return { app, server };
1369
+ return { app, server, basicHandler };
308
1370
  }
309
1371
 
310
1372
  async function createBackend(serverRoot) {
311
- const language = await selectOption("Select a language for the backend:", [
312
- { label: "JavaScript", value: "js" },
313
- { label: "TypeScript", value: "ts" },
314
- ]);
315
- const framework = await selectOption("Select a backend framework:", [
316
- { label: "Basic Node.js — no additional framework", value: "basic" },
317
- { label: "Express — install Express and dotenv", value: "express" },
318
- ]);
319
- const structure = useDefaultStructure
320
- ? "simple"
321
- : await selectOption("Select a backend folder structure:", [
322
- { label: "Simple — standard folders (default)", value: "simple" },
323
- { label: "Module-based — organized by feature", value: "module" },
324
- ]);
1373
+ const language =
1374
+ languageOption ??
1375
+ (await chooseOption("Select a language for the backend:", [
1376
+ { label: "JavaScript", value: "js" },
1377
+ { label: "TypeScript", value: "ts" },
1378
+ ], 0, "yellow"));
1379
+ const framework =
1380
+ backendOption && backendOption !== "none"
1381
+ ? backendOption
1382
+ : await chooseOption("Select a backend framework:", [
1383
+ { label: "Basic Node.js — no additional framework", value: "basic" },
1384
+ { label: "Express — install Express, CORS, and dotenv (default)", value: "express" },
1385
+ ], 1, "yellow");
1386
+ const structure = structureOption
1387
+ ? structureOption
1388
+ : useDefaultStructure
1389
+ ? "simple"
1390
+ : await chooseOption("Select a backend folder structure:", [
1391
+ { label: "Simple — standard folders", value: "simple" },
1392
+ { label: "Module-based — organized by feature (default)", value: "module" },
1393
+ ], 1, "yellow");
325
1394
  const typed = language === "ts";
326
- let { app, server } = backendFiles(language, framework);
1395
+ let { app, server, basicHandler } = backendFiles(language, framework);
327
1396
  const sourceRoot = join(serverRoot, "src");
328
1397
  const folders =
329
1398
  structure === "simple"
330
1399
  ? ["routes", "controllers", "middleware", "config"]
331
1400
  : ["module", "config", "middleware", "utils"];
332
1401
  for (const folder of folders) {
333
- await mkdir(join(sourceRoot, folder), { recursive: true });
1402
+ const folderPath = join(sourceRoot, folder);
1403
+ await mkdir(folderPath, { recursive: true });
1404
+ await writeFile(join(folderPath, ".gitkeep"), "");
334
1405
  }
335
1406
  if (structure === "module") {
336
- const request = typed
337
- ? framework === "express"
338
- ? "request: import('express').Request"
339
- : "request: import('node:http').IncomingMessage"
340
- : "request";
341
- const response = typed
342
- ? framework === "express"
343
- ? "response: import('express').Response"
344
- : "response: import('node:http').ServerResponse"
345
- : "response";
346
1407
  const router =
347
1408
  framework === "express"
348
1409
  ? `import { Router } from "express";
349
1410
 
350
1411
  export const mainRouter = Router();
1412
+ mainRouter.get("/", (_request, response) => {
1413
+ response.json({ message: "Backend is running" });
1414
+ });
351
1415
  mainRouter.get("/api/health", (_request, response) => {
352
1416
  response.json({ status: "ok" });
353
1417
  });
354
1418
  `
355
- : `export function handleRequest(${request}, ${response}) {
356
- response.writeHead(200, { "content-type": "application/json" });
357
- response.end(JSON.stringify({ message: "Backend is running" }));
358
- }
1419
+ : `export { handleRequest } from "./basicHandler.${language}";
359
1420
  `;
360
1421
  await writeFile(join(sourceRoot, `mainRouter.${language}`), router);
361
1422
  app =
362
1423
  framework === "express"
363
- ? `import express from "express";
1424
+ ? `import cors from "cors";
1425
+ import express from "express";
364
1426
  import { mainRouter } from "./mainRouter.${language}";
365
1427
 
366
1428
  export function createApp() {
367
1429
  const app = express();
1430
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1431
+ .split(",")
1432
+ .map((origin) => origin.trim());
1433
+ app.use((request, response, next) => {
1434
+ const origin = request.headers.origin;
1435
+ if (origin && !origins.includes("*") && origins.includes(origin)) {
1436
+ response.vary("Origin");
1437
+ }
1438
+ next();
1439
+ });
1440
+ app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
368
1441
  app.use(express.json());
369
1442
  app.use(mainRouter);
1443
+ app.use((_request, response) => {
1444
+ response.status(404).json({ error: "Not Found" });
1445
+ });
1446
+ app.use((${expressErrorHandlerParameters(language)}) => {
1447
+ console.error(error);
1448
+ response.status(500).json({ error: "Internal Server Error" });
1449
+ });
370
1450
  return app;
371
1451
  }
372
1452
  `
@@ -378,13 +1458,29 @@ export function createApp() {
378
1458
  }
379
1459
  `;
380
1460
  }
1461
+ if (basicHandler) {
1462
+ await writeFile(join(sourceRoot, `basicHandler.${language}`), basicHandler);
1463
+ }
381
1464
  await writeFile(join(sourceRoot, `app.${language}`), app);
382
1465
  await writeFile(join(sourceRoot, `server.${language}`), server);
383
1466
 
384
1467
  const scripts = typed
385
- ? { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
386
- : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
387
- const dependencies = framework === "express" ? { express: "^5", dotenv: "^16" } : {};
1468
+ ? framework === "basic"
1469
+ ? {
1470
+ dev: `tsx watch src/server.${language}`,
1471
+ start: `tsx src/server.${language}`,
1472
+ }
1473
+ : { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
1474
+ : framework === "basic"
1475
+ ? {
1476
+ dev: `node --watch src/server.${language}`,
1477
+ start: `node src/server.${language}`,
1478
+ }
1479
+ : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
1480
+ const dependencies =
1481
+ framework === "express"
1482
+ ? { express: "^5", cors: "^2.8.5", dotenv: "^16" }
1483
+ : { dotenv: "^16" };
388
1484
  const packageJson = {
389
1485
  name: serverFolder,
390
1486
  version: "1.0.0",
@@ -395,7 +1491,9 @@ export function createApp() {
395
1491
  ? {
396
1492
  dependencies: { ...dependencies, tsx: "^4" },
397
1493
  devDependencies: {
398
- ...(framework === "express" ? { "@types/express": "^5" } : {}),
1494
+ ...(framework === "express"
1495
+ ? { "@types/cors": "^2.8.19", "@types/express": "^5" }
1496
+ : {}),
399
1497
  "@types/node": "^22",
400
1498
  typescript: "^5",
401
1499
  },
@@ -429,27 +1527,48 @@ export function createApp() {
429
1527
  }
430
1528
  await writeFile(
431
1529
  join(serverRoot, ".env"),
432
- "# Local backend environment variables\nPORT=4000\n",
1530
+ "# Local backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
433
1531
  { flag: "wx" },
434
1532
  );
1533
+ await writeFile(
1534
+ join(serverRoot, ".env.example"),
1535
+ "# Backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
1536
+ );
435
1537
  }
436
1538
 
437
1539
  await updateIfOutdated();
438
1540
 
439
1541
  try {
440
1542
  await mkdir(root);
1543
+ rootCreated = true;
1544
+ process.on("SIGINT", handleCreationSignal);
1545
+ process.on("SIGTERM", handleCreationSignal);
441
1546
  } catch (error) {
442
1547
  if (error.code === "EEXIST") console.error(`The destination already exists: ${root}`);
443
1548
  else console.error(`Unable to create project directory: ${error.message}`);
444
1549
  process.exit(1);
445
1550
  }
446
1551
 
1552
+ let installFailed = false;
447
1553
  try {
448
1554
  console.log(`\nCreating the frontend in ${clientFolder} with create-vite...\n`);
449
1555
  const viteArgs =
450
1556
  packageManager === "pnpm"
451
- ? ["create", "vite@latest", clientFolder, "--no-immediate"]
452
- : ["create", "vite@latest", "--", clientFolder, "--no-immediate"];
1557
+ ? [
1558
+ "create",
1559
+ "vite@latest",
1560
+ clientFolder,
1561
+ "--no-immediate",
1562
+ ...(templateOption ? ["--template", templateOption] : []),
1563
+ ]
1564
+ : [
1565
+ "create",
1566
+ "vite@latest",
1567
+ "--",
1568
+ clientFolder,
1569
+ "--no-immediate",
1570
+ ...(templateOption ? ["--template", templateOption] : []),
1571
+ ];
453
1572
  await run(packageManager, viteArgs, root);
454
1573
 
455
1574
  const clientRoot = join(root, clientFolder);
@@ -469,32 +1588,55 @@ try {
469
1588
  "# Local frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
470
1589
  { flag: "wx" },
471
1590
  );
472
-
473
- const includeServer = await selectOption(
474
- "Would you like to add a separate backend server?",
475
- [
476
- { label: "Yes — include a backend workspace", value: true },
477
- { label: "No — create a frontend-only project (default)", value: false },
478
- ],
479
- 1,
1591
+ await writeFile(
1592
+ join(clientRoot, ".env.example"),
1593
+ "# Frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
480
1594
  );
1595
+
1596
+ const includeServer =
1597
+ backendOption !== undefined
1598
+ ? backendOption !== "none"
1599
+ : await chooseOption(
1600
+ "Would you like to add a separate backend server?",
1601
+ [
1602
+ { label: "Yes — include a backend workspace", value: true },
1603
+ { label: "No — create a frontend-only project", value: false },
1604
+ ],
1605
+ 0,
1606
+ "yellow",
1607
+ );
481
1608
  const workspaces = [clientFolder];
482
1609
  if (includeServer) {
1610
+ await scaffoldBackendStatus(clientRoot);
483
1611
  await createBackend(join(root, serverFolder));
484
1612
  workspaces.push(serverFolder);
485
1613
  }
486
1614
 
487
1615
  await mkdir(join(root, "scripts"), { recursive: true });
488
- await Promise.all(["dev.mjs", "run-app.mjs", "install-info.mjs"].map(copyScript));
1616
+ await Promise.all(
1617
+ ["dev.mjs", "run-app.mjs", "install-info.mjs", "add-dependency.mjs"].map(copyScript),
1618
+ );
489
1619
  const rootPackage = {
490
1620
  name: projectName,
491
1621
  version: "1.0.0",
492
1622
  private: true,
1623
+ engines: { node: ">=20.6" },
493
1624
  workspaces,
494
1625
  scripts: {
495
1626
  preinstall: "node scripts/install-info.mjs",
496
- dev: "node scripts/dev.mjs",
1627
+ postinstall: "node scripts/install-info.mjs --complete",
1628
+ dev: `node scripts/dev.mjs${exposeClient ? " --host" : ""}`,
1629
+ build:
1630
+ packageManager === "pnpm"
1631
+ ? "pnpm -r --if-present run build"
1632
+ : "npm run build --workspaces --if-present",
1633
+ lint:
1634
+ packageManager === "pnpm"
1635
+ ? "pnpm -r --if-present run lint"
1636
+ : "npm run lint --workspaces --if-present",
497
1637
  client: "node scripts/run-app.mjs client",
1638
+ adD: "node scripts/add-dependency.mjs",
1639
+ "add-dependency": "node scripts/add-dependency.mjs",
498
1640
  ...(includeServer ? { server: "node scripts/run-app.mjs server" } : {}),
499
1641
  },
500
1642
  type: "module",
@@ -503,19 +1645,23 @@ try {
503
1645
  },
504
1646
  };
505
1647
  await writeFile(join(root, "package.json"), `${JSON.stringify(rootPackage, null, 2)}\n`);
506
- await writeFile(
507
- join(root, "pnpm-workspace.yaml"),
508
- [
509
- "packages:",
510
- ...workspaces.map((workspace) => ` - ${workspace}`),
511
- "",
512
- "allowBuilds:",
513
- " esbuild: true",
514
- " sharp: false",
515
- " unrs-resolver: false",
516
- "",
517
- ].join("\n"),
518
- );
1648
+ if (packageManager === "pnpm") {
1649
+ await writeFile(
1650
+ join(root, "pnpm-workspace.yaml"),
1651
+ [
1652
+ "packages:",
1653
+ ...workspaces.map((workspace) => ` - ${workspace}`),
1654
+ "",
1655
+ "onlyBuiltDependencies: [esbuild]",
1656
+ "",
1657
+ "allowBuilds:",
1658
+ " esbuild: true",
1659
+ " sharp: false",
1660
+ " unrs-resolver: false",
1661
+ "",
1662
+ ].join("\n"),
1663
+ );
1664
+ }
519
1665
  await writeFile(
520
1666
  join(root, ".gitignore"),
521
1667
  [
@@ -534,16 +1680,85 @@ try {
534
1680
  "npm-debug.log*",
535
1681
  "pnpm-debug.log*",
536
1682
  "yarn-debug.log*",
1683
+ ".dev.log",
1684
+ ".dev.lock",
1685
+ ".install-state",
537
1686
  "",
538
1687
  ].join("\n"),
539
1688
  );
540
1689
 
541
1690
  console.log(`\nInstalling dependencies for ${workspaces.join(" and ")}...`);
542
- await run(packageManager, ["install"], root);
1691
+ try {
1692
+ await run(packageManager, ["install"], root, {
1693
+ ...process.env,
1694
+ VANILLA_VITE_ALLOW_INSTALL: "1",
1695
+ });
1696
+ } catch (error) {
1697
+ installFailed = true;
1698
+ await rm(join(root, ".install-state"), { force: true });
1699
+ console.error(
1700
+ `Dependency installation failed: ${error.message}\nRetry with:\n cd "${projectName}" && ${packageManager} install`,
1701
+ );
1702
+ }
1703
+ rootCreated = false;
1704
+ process.off("SIGINT", handleCreationSignal);
1705
+ process.off("SIGTERM", handleCreationSignal);
1706
+ if (!hasOption("no-git")) {
1707
+ const repositoryCheck = spawnSync(
1708
+ "git",
1709
+ ["rev-parse", "--is-inside-work-tree"],
1710
+ { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
1711
+ );
1712
+ if (repositoryCheck.status === 0 && repositoryCheck.stdout.trim() === "true") {
1713
+ console.log("Skipping Git initialization because this project is already inside a Git work tree.");
1714
+ } else {
1715
+ const initializeGit = await chooseOption(
1716
+ "Would you like to initialize Git and create an initial commit?",
1717
+ [
1718
+ { label: "Yes — initialize Git and commit the project", value: true },
1719
+ { label: "No", value: false },
1720
+ ],
1721
+ 0,
1722
+ );
1723
+ if (initializeGit) {
1724
+ try {
1725
+ await run("git", ["init"], root);
1726
+ await run("git", ["add", "-A"], root);
1727
+ await run("git", ["commit", "-m", "Initial commit"], root);
1728
+ } catch (error) {
1729
+ console.error(`Unable to create the initial Git commit: ${error.message}`);
1730
+ }
1731
+ }
1732
+ }
1733
+ }
543
1734
  console.log(
544
- `\nProject created successfully: ${projectName}/\n\nTo get started:\n cd ${projectName}\n ${packageManager} dev`,
1735
+ `\nProject created successfully: ${projectName}/\n${
1736
+ installFailed
1737
+ ? "Install dependencies with the retry command above.\n"
1738
+ : noStart
1739
+ ? "Skipping the development server.\n"
1740
+ : "Starting the development server...\n"
1741
+ }`,
545
1742
  );
546
1743
  } catch (error) {
547
- console.error(`\nProject creation failed: ${error.message}`);
548
- process.exit(1);
1744
+ if (!creationCancelled) {
1745
+ await removeIncompleteProject();
1746
+ console.error(`\nProject creation failed: ${error.message}`);
1747
+ process.exit(1);
1748
+ }
1749
+ }
1750
+
1751
+ if (!creationCancelled && !noStart && !installFailed) {
1752
+ try {
1753
+ await run(
1754
+ packageManager,
1755
+ packageManager === "pnpm" ? ["dev"] : ["run", "dev"],
1756
+ root,
1757
+ );
1758
+ } catch (error) {
1759
+ console.error(
1760
+ `\nProject created successfully, but the development server could not be started: ${error.message}`,
1761
+ );
1762
+ process.exitCode = 1;
1763
+ }
549
1764
  }