create-vanilla-vite 0.0.0-stage → 1.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.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # Vanilla Vite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create a Vite app with the official interactive setup. Choose React or any other offered template, and optionally add a Node.js or Express backend in the same npm or pnpm workspace.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/create-vanilla-vite)](https://www.npmjs.com/package/create-vanilla-vite)
6
+ [![npm downloads](https://img.shields.io/npm/dm/create-vanilla-vite)](https://www.npmjs.com/package/create-vanilla-vite)
7
+ [![GitHub repository](https://img.shields.io/badge/GitHub-Wasib--2005%2Fvanilla--vite-181717?logo=github)](https://github.com/Wasib-2005/vanilla-vite)
8
+
9
+ **Links:** [npm package](https://www.npmjs.com/package/create-vanilla-vite) · [GitHub repository](https://github.com/Wasib-2005/vanilla-vite) · [Report an issue](https://github.com/Wasib-2005/vanilla-vite/issues)
10
+
11
+ ## Requirements
12
+
13
+ - Node.js 20 or newer
14
+ - npm or pnpm
15
+
16
+ ## Create a project
17
+
18
+ With pnpm:
19
+
20
+ ```bash
21
+ pnpm create vanilla-vite@latest my-app
22
+ ```
23
+
24
+ With npm:
25
+
26
+ ```bash
27
+ npm create vanilla-vite@latest my-app
28
+ ```
29
+
30
+ Omit the project name to enter it when prompted:
31
+
32
+ ```bash
33
+ pnpm create vanilla-vite@latest
34
+ # or
35
+ npm create vanilla-vite@latest
36
+ ```
37
+
38
+ The generator starts the official `create-vite@latest` wizard in `my-app-client`. Choose **React** for a React application, then select JavaScript or TypeScript. You can instead choose any other template offered by Vite. Afterward, choose whether to add a backend (frontend-only is the default). The frontend wizard may install dependencies temporarily; the generator removes nested install files and Git metadata, configures one shared workspace, and installs all dependencies from the project root.
39
+
40
+ The optional backend supports JavaScript or TypeScript, either basic Node.js or Express, and a simple or module-based folder layout. Both layouts create the `src/app` and `src/server` entry points. The simple layout has `routes`, `controllers`, `middleware`, and `config` folders; the module-based layout has `module`, `config`, `middleware`, and `utils` folders plus `mainRouter`. Express adds Express and dotenv, enables JSON parsing, and provides `GET /api/health`, returning `{ "status": "ok" }`.
41
+
42
+ Pass `--default` after the project name to use the simple backend folder layout without prompting:
43
+
44
+ ```bash
45
+ pnpm create vanilla-vite@latest my-app --default
46
+ npm create vanilla-vite@latest my-app --default
47
+ ```
48
+
49
+ The generated project structure is:
50
+
51
+ ```text
52
+ my-app/
53
+ ├── my-app-client/ # Vite app; choose React or another Vite template
54
+ ├── my-app-server/ # optional backend
55
+ ├── scripts/
56
+ ├── package.json
57
+ └── pnpm-workspace.yaml # used by pnpm; npm uses package.json workspaces
58
+ ```
59
+
60
+ The frontend gets a `.env.local` file with `VITE_API_URL=http://localhost:4000`. If you choose a backend, it gets a `.env` file with `PORT=4000`. Both are ignored by Git.
61
+
62
+ ## Run the project
63
+
64
+ From the project root:
65
+
66
+ ```bash
67
+ pnpm dev
68
+ # or
69
+ npm run dev
70
+ ```
71
+
72
+ This starts the frontend and, if selected, the backend together. In an interactive terminal, press `r` to restart both apps, `c` to clear the terminal, or Ctrl+C to stop.
73
+
74
+ Run one workspace individually:
75
+
76
+ ```bash
77
+ pnpm client
78
+ pnpm server
79
+ ```
80
+
81
+ Or with npm:
82
+
83
+ ```bash
84
+ npm run client
85
+ npm run server
86
+ ```
87
+
88
+ The server commands are only available if you chose a backend. Add `-dev` to run a workspace in development mode, for example `pnpm client -dev` or `pnpm server -dev`.
89
+
90
+ ## Add dependencies
91
+
92
+ With pnpm:
93
+
94
+ ```bash
95
+ pnpm client add <package>
96
+ pnpm server add <package>
97
+ ```
98
+
99
+ With npm:
100
+
101
+ ```bash
102
+ npm install <package> --workspace=my-app-client
103
+ npm install <package> --workspace=my-app-server
104
+ ```
105
+
106
+ ## Development
107
+
108
+ To test the source before publishing:
109
+
110
+ ```bash
111
+ pnpm exec node ./bin/create-template.mjs my-app
112
+ # or
113
+ npm exec -- node ./bin/create-template.mjs my-app
114
+ ```
115
+
116
+ ## License
117
+
118
+ ISC
@@ -0,0 +1,448 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { spawn } from "node:child_process";
5
+ import { emitKeypressEvents } from "node:readline";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { stdin, stdout } from "node:process";
8
+ import { join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const args = process.argv.slice(2);
12
+ const useDefaultStructure = args.includes("--default");
13
+ let projectName = args.find((arg) => !arg.startsWith("--"));
14
+ const validProjectName = (name) => /^[a-z0-9][a-z0-9_-]*$/.test(name);
15
+
16
+ if (!projectName && stdin.isTTY) {
17
+ const prompt = createInterface({ input: stdin, output: stdout });
18
+ try {
19
+ do {
20
+ projectName = (await prompt.question("Project name: ")).trim();
21
+ if (!validProjectName(projectName)) {
22
+ console.error("Use lowercase letters, numbers, hyphens, or underscores.");
23
+ }
24
+ } while (!validProjectName(projectName));
25
+ } finally {
26
+ prompt.close();
27
+ }
28
+ }
29
+
30
+ if (!projectName || !validProjectName(projectName)) {
31
+ console.error("Usage: create-vanilla-vite <lowercase-project-name>");
32
+ if (!projectName && !stdin.isTTY) {
33
+ console.error("Run this command in an interactive terminal to be prompted for a name.");
34
+ }
35
+ process.exit(1);
36
+ }
37
+
38
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
39
+ ? "pnpm"
40
+ : "npm";
41
+ const root = resolve(process.cwd(), projectName);
42
+ const clientFolder = `${projectName}-client`;
43
+ const serverFolder = `${projectName}-server`;
44
+ const packageRoot = fileURLToPath(new URL("../", import.meta.url));
45
+ const scriptRoot = fileURLToPath(new URL("../scripts/", import.meta.url));
46
+
47
+ async function updateIfOutdated() {
48
+ const { version: installedVersion } = JSON.parse(
49
+ await readFile(join(packageRoot, "package.json"), "utf8"),
50
+ );
51
+ const registry = (process.env.npm_config_registry || "https://registry.npmjs.org")
52
+ .replace(/\/$/, "");
53
+
54
+ let latestVersion;
55
+ try {
56
+ const response = await fetch(`${registry}/create-vanilla-vite/latest`, {
57
+ signal: AbortSignal.timeout(3000),
58
+ });
59
+ if (!response.ok) throw new Error(`registry returned HTTP ${response.status}`);
60
+ latestVersion = (await response.json()).version;
61
+ if (typeof latestVersion !== "string") {
62
+ throw new Error("registry response did not include a version");
63
+ }
64
+ } catch (error) {
65
+ console.warn(`\nCould not check for CLI updates: ${error.message}`);
66
+ return;
67
+ }
68
+
69
+ if (installedVersion === latestVersion) return;
70
+ if (!stdin.isTTY) {
71
+ console.warn(
72
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}). Run ${packageManager} create vanilla-vite@latest to use it.`,
73
+ );
74
+ return;
75
+ }
76
+
77
+ console.warn(
78
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}).`,
79
+ );
80
+ const useLatest = await selectOption("Which version would you like to use?", [
81
+ { label: `Use the latest version (${latestVersion})`, value: true },
82
+ { label: `Continue with the current version (${installedVersion})`, value: false },
83
+ ]);
84
+ if (!useLatest) return;
85
+
86
+ const updateArgs =
87
+ packageManager === "pnpm"
88
+ ? ["dlx", "create-vanilla-vite@latest", ...args]
89
+ : [
90
+ "exec",
91
+ "--yes",
92
+ "--package=create-vanilla-vite@latest",
93
+ "--",
94
+ "create-vanilla-vite",
95
+ ...args,
96
+ ];
97
+ try {
98
+ await run(packageManager, updateArgs, process.cwd());
99
+ } catch (error) {
100
+ console.error(`Unable to start the latest CLI version: ${error.message}`);
101
+ process.exit(1);
102
+ }
103
+ process.exit(0);
104
+ }
105
+
106
+ function run(command, commandArgs, cwd) {
107
+ return new Promise((resolveRun, rejectRun) => {
108
+ const child = spawn(command, commandArgs, { cwd, stdio: "inherit" });
109
+ child.once("error", rejectRun);
110
+ child.once("close", (code, signal) => {
111
+ if (code === 0) resolveRun();
112
+ else {
113
+ rejectRun(
114
+ new Error(`${command} exited ${signal ? `from ${signal}` : `with code ${code}`}`),
115
+ );
116
+ }
117
+ });
118
+ });
119
+ }
120
+
121
+ async function selectOption(question, options, defaultIndex = 0) {
122
+ if (!stdin.isTTY) return options[defaultIndex].value;
123
+ let selected = defaultIndex;
124
+ emitKeypressEvents(stdin);
125
+
126
+ return new Promise((resolveSelection) => {
127
+ function render() {
128
+ stdout.write(`\r\x1b[2K${question}\n`);
129
+ for (const [index, option] of options.entries()) {
130
+ stdout.write(` ${index === selected ? "❯" : " "} ${option.label}\n`);
131
+ }
132
+ stdout.write(" Use ↑/↓ to select, Enter to confirm, or Esc to keep the default.\n");
133
+ stdout.write(`\x1b[${options.length + 2}A`);
134
+ }
135
+
136
+ function finish(value) {
137
+ stdin.off("keypress", onKeypress);
138
+ stdin.setRawMode(false);
139
+ stdin.pause();
140
+ stdout.write(`\x1b[${options.length + 2}B\n`);
141
+ resolveSelection(value);
142
+ }
143
+
144
+ function onKeypress(_input, key) {
145
+ if (key?.name === "up" || key?.name === "down") {
146
+ selected =
147
+ (selected + (key.name === "down" ? 1 : options.length - 1)) %
148
+ options.length;
149
+ render();
150
+ } else if (key?.name === "return") finish(options[selected].value);
151
+ else if (key?.name === "escape" || (key?.ctrl && key.name === "c")) {
152
+ finish(options[defaultIndex].value);
153
+ }
154
+ }
155
+
156
+ stdin.setRawMode(true);
157
+ stdin.resume();
158
+ stdin.on("keypress", onKeypress);
159
+ render();
160
+ });
161
+ }
162
+
163
+ async function copyScript(name) {
164
+ const source = await readFile(join(scriptRoot, name), "utf8");
165
+ await writeFile(join(root, "scripts", name), source);
166
+ }
167
+
168
+ function backendFiles(language, framework) {
169
+ const extension = language;
170
+ const typeAnnotation = language === "ts" ? ": number" : "";
171
+ const request = language === "ts"
172
+ ? framework === "express"
173
+ ? "request: import('express').Request"
174
+ : "request: import('node:http').IncomingMessage"
175
+ : "request";
176
+ const response = language === "ts"
177
+ ? framework === "express"
178
+ ? "response: import('express').Response"
179
+ : "response: import('node:http').ServerResponse"
180
+ : "response";
181
+ const app =
182
+ framework === "express"
183
+ ? `import express from "express";
184
+
185
+ export function createApp() {
186
+ const app = express();
187
+ app.use(express.json());
188
+ app.get("/", (_request, response) => response.json({ message: "Backend is running" }));
189
+ app.get("/api/health", (_request, response) => response.json({ status: "ok" }));
190
+ return app;
191
+ }
192
+ `
193
+ : `import { createServer } from "node:http";
194
+
195
+ export function createApp() {
196
+ return createServer((${request}, ${response}) => {
197
+ response.writeHead(200, { "content-type": "application/json" });
198
+ response.end(JSON.stringify({ message: "Backend is running" }));
199
+ });
200
+ }
201
+ `;
202
+ const server = `${framework === "express" ? 'import "dotenv/config";\n' : ""}import { createApp } from "./app.${extension}";
203
+
204
+ const port${typeAnnotation} = Number(process.env.PORT ?? 4000);
205
+ const app = createApp();
206
+ app.listen(port, () => {
207
+ console.log(\`Backend listening at http://localhost:\${port}\`);
208
+ });
209
+ `;
210
+ return { app, server };
211
+ }
212
+
213
+ async function createBackend(serverRoot) {
214
+ const language = await selectOption("Select a language for the backend:", [
215
+ { label: "JavaScript", value: "js" },
216
+ { label: "TypeScript", value: "ts" },
217
+ ]);
218
+ const framework = await selectOption("Select a backend framework:", [
219
+ { label: "Basic Node.js — no additional framework", value: "basic" },
220
+ { label: "Express — install Express and dotenv", value: "express" },
221
+ ]);
222
+ const structure = useDefaultStructure
223
+ ? "simple"
224
+ : await selectOption("Select a backend folder structure:", [
225
+ { label: "Simple — standard folders (default)", value: "simple" },
226
+ { label: "Module-based — organized by feature", value: "module" },
227
+ ]);
228
+ const typed = language === "ts";
229
+ let { app, server } = backendFiles(language, framework);
230
+ const sourceRoot = join(serverRoot, "src");
231
+ const folders =
232
+ structure === "simple"
233
+ ? ["routes", "controllers", "middleware", "config"]
234
+ : ["module", "config", "middleware", "utils"];
235
+ for (const folder of folders) {
236
+ await mkdir(join(sourceRoot, folder), { recursive: true });
237
+ }
238
+ if (structure === "module") {
239
+ const request = typed
240
+ ? framework === "express"
241
+ ? "request: import('express').Request"
242
+ : "request: import('node:http').IncomingMessage"
243
+ : "request";
244
+ const response = typed
245
+ ? framework === "express"
246
+ ? "response: import('express').Response"
247
+ : "response: import('node:http').ServerResponse"
248
+ : "response";
249
+ const router =
250
+ framework === "express"
251
+ ? `import { Router } from "express";
252
+
253
+ export const mainRouter = Router();
254
+ mainRouter.get("/api/health", (_request, response) => {
255
+ response.json({ status: "ok" });
256
+ });
257
+ `
258
+ : `export function handleRequest(${request}, ${response}) {
259
+ response.writeHead(200, { "content-type": "application/json" });
260
+ response.end(JSON.stringify({ message: "Backend is running" }));
261
+ }
262
+ `;
263
+ await writeFile(join(sourceRoot, `mainRouter.${language}`), router);
264
+ app =
265
+ framework === "express"
266
+ ? `import express from "express";
267
+ import { mainRouter } from "./mainRouter.${language}";
268
+
269
+ export function createApp() {
270
+ const app = express();
271
+ app.use(express.json());
272
+ app.use(mainRouter);
273
+ return app;
274
+ }
275
+ `
276
+ : `import { createServer } from "node:http";
277
+ import { handleRequest } from "./mainRouter.${language}";
278
+
279
+ export function createApp() {
280
+ return createServer(handleRequest);
281
+ }
282
+ `;
283
+ }
284
+ await writeFile(join(sourceRoot, `app.${language}`), app);
285
+ await writeFile(join(sourceRoot, `server.${language}`), server);
286
+
287
+ const scripts = typed
288
+ ? { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
289
+ : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
290
+ const dependencies = framework === "express" ? { express: "^5", dotenv: "^16" } : {};
291
+ const packageJson = {
292
+ name: serverFolder,
293
+ version: "1.0.0",
294
+ private: true,
295
+ type: "module",
296
+ scripts,
297
+ ...(typed
298
+ ? {
299
+ dependencies: { ...dependencies, tsx: "^4" },
300
+ devDependencies: {
301
+ ...(framework === "express" ? { "@types/express": "^5" } : {}),
302
+ "@types/node": "^22",
303
+ typescript: "^5",
304
+ },
305
+ }
306
+ : Object.keys(dependencies).length
307
+ ? { dependencies }
308
+ : {}),
309
+ };
310
+ await writeFile(join(serverRoot, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`);
311
+ if (typed) {
312
+ await writeFile(
313
+ join(serverRoot, "tsconfig.json"),
314
+ `${JSON.stringify(
315
+ {
316
+ compilerOptions: {
317
+ target: "ES2022",
318
+ module: "NodeNext",
319
+ moduleResolution: "NodeNext",
320
+ strict: true,
321
+ esModuleInterop: true,
322
+ skipLibCheck: true,
323
+ noEmit: true,
324
+ allowImportingTsExtensions: true,
325
+ },
326
+ include: ["**/*.ts"],
327
+ },
328
+ null,
329
+ 2,
330
+ )}\n`,
331
+ );
332
+ }
333
+ await writeFile(
334
+ join(serverRoot, ".env"),
335
+ "# Local backend environment variables\nPORT=4000\n",
336
+ { flag: "wx" },
337
+ );
338
+ }
339
+
340
+ await updateIfOutdated();
341
+
342
+ try {
343
+ await mkdir(root);
344
+ } catch (error) {
345
+ if (error.code === "EEXIST") console.error(`The destination already exists: ${root}`);
346
+ else console.error(`Unable to create project directory: ${error.message}`);
347
+ process.exit(1);
348
+ }
349
+
350
+ try {
351
+ console.log(`\nCreating the frontend in ${clientFolder} with create-vite...\n`);
352
+ const viteArgs =
353
+ packageManager === "pnpm"
354
+ ? ["create", "vite@latest", clientFolder, "--no-immediate"]
355
+ : ["create", "vite@latest", "--", clientFolder, "--no-immediate"];
356
+ await run(packageManager, viteArgs, root);
357
+
358
+ const clientRoot = join(root, clientFolder);
359
+ await Promise.all(
360
+ [".git", "node_modules", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"].map(
361
+ (entry) => rm(join(clientRoot, entry), { recursive: true, force: true }),
362
+ ),
363
+ );
364
+ const clientPackagePath = join(clientRoot, "package.json");
365
+ const clientPackage = JSON.parse(await readFile(clientPackagePath, "utf8"));
366
+ clientPackage.scripts ??= {};
367
+ clientPackage.scripts.start ??= clientPackage.scripts.dev;
368
+ await writeFile(clientPackagePath, `${JSON.stringify(clientPackage, null, 2)}\n`);
369
+ await writeFile(
370
+ join(clientRoot, ".env.local"),
371
+ "# Local frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
372
+ { flag: "wx" },
373
+ );
374
+
375
+ const includeServer = await selectOption(
376
+ "Would you like to add a separate backend server?",
377
+ [
378
+ { label: "Yes — include a backend workspace", value: true },
379
+ { label: "No — create a frontend-only project (default)", value: false },
380
+ ],
381
+ 1,
382
+ );
383
+ const workspaces = [clientFolder];
384
+ if (includeServer) {
385
+ await createBackend(join(root, serverFolder));
386
+ workspaces.push(serverFolder);
387
+ }
388
+
389
+ await mkdir(join(root, "scripts"), { recursive: true });
390
+ await Promise.all(["dev.mjs", "run-app.mjs", "install-info.mjs"].map(copyScript));
391
+ const rootPackage = {
392
+ name: projectName,
393
+ version: "1.0.0",
394
+ private: true,
395
+ workspaces,
396
+ scripts: {
397
+ preinstall: "node scripts/install-info.mjs",
398
+ dev: "node scripts/dev.mjs",
399
+ client: "node scripts/run-app.mjs client",
400
+ ...(includeServer ? { server: "node scripts/run-app.mjs server" } : {}),
401
+ },
402
+ type: "module",
403
+ };
404
+ await writeFile(join(root, "package.json"), `${JSON.stringify(rootPackage, null, 2)}\n`);
405
+ await writeFile(
406
+ join(root, "pnpm-workspace.yaml"),
407
+ [
408
+ "packages:",
409
+ ...workspaces.map((workspace) => ` - ${workspace}`),
410
+ "",
411
+ "allowBuilds:",
412
+ " esbuild: true",
413
+ " sharp: false",
414
+ " unrs-resolver: false",
415
+ "",
416
+ ].join("\n"),
417
+ );
418
+ await writeFile(
419
+ join(root, ".gitignore"),
420
+ [
421
+ "# Dependencies",
422
+ "node_modules/",
423
+ "",
424
+ "# Build output",
425
+ "**/dist/",
426
+ "**/coverage/",
427
+ "",
428
+ "# Local environment files",
429
+ "**/.env*",
430
+ "!**/.env.example",
431
+ "",
432
+ "# Logs",
433
+ "npm-debug.log*",
434
+ "pnpm-debug.log*",
435
+ "yarn-debug.log*",
436
+ "",
437
+ ].join("\n"),
438
+ );
439
+
440
+ console.log(`\nInstalling dependencies for ${workspaces.join(" and ")}...`);
441
+ await run(packageManager, ["install"], root);
442
+ console.log(
443
+ `\nProject created successfully: ${projectName}/\n\nTo get started:\n cd ${projectName}\n ${packageManager} dev`,
444
+ );
445
+ } catch (error) {
446
+ console.error(`\nProject creation failed: ${error.message}`);
447
+ process.exit(1);
448
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "create-vanilla-vite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Scaffold a React or Vite app with an optional Node.js or Express backend",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Wasib-2005/vanilla-vite.git"
9
+ },
10
+ "homepage": "https://github.com/Wasib-2005/vanilla-vite#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/Wasib-2005/vanilla-vite/issues"
13
+ },
14
+ "bin": {
15
+ "create-vanilla-vite": "./bin/create-template.mjs"
16
+ },
17
+ "files": [
18
+ "bin/",
19
+ "scripts/",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "keywords": [
26
+ "create",
27
+ "create-vite",
28
+ "react",
29
+ "vite",
30
+ "scaffold",
31
+ "generator",
32
+ "starter",
33
+ "fullstack",
34
+ "full-stack",
35
+ "monorepo",
36
+ "pnpm",
37
+ "npm",
38
+ "node",
39
+ "nodejs",
40
+ "express",
41
+ "typescript",
42
+ "javascript",
43
+ "cli"
44
+ ],
45
+ "license": "ISC"
46
+ }
@@ -0,0 +1,132 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = fileURLToPath(new URL("../", import.meta.url));
7
+ const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
8
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
9
+ ? "pnpm"
10
+ : "npm";
11
+ const apps = project.workspaces.map((workspace) => ({
12
+ name: workspace.endsWith("-client") ? "client" : "server",
13
+ workspace,
14
+ }));
15
+ const colors = { client: 36, server: 35, dev: 90 };
16
+ const children = [];
17
+ let stopping = false;
18
+ let restarting = false;
19
+
20
+ function log(name, message, write = console.log) {
21
+ const prefix = `[${name}]`;
22
+ write(
23
+ `${process.env.NO_COLOR === undefined && process.stdout.isTTY ? `\x1b[${colors[name]}m${prefix}\x1b[0m` : prefix} ${message}`,
24
+ );
25
+ }
26
+
27
+ function start({ name, workspace }) {
28
+ const args =
29
+ packageManager === "pnpm"
30
+ ? ["--filter", workspace, "run", "dev"]
31
+ : ["run", "dev", "--workspace", workspace];
32
+ const child = spawn(packageManager, args, {
33
+ cwd: root,
34
+ detached: process.platform !== "win32",
35
+ stdio: ["ignore", "pipe", "pipe"],
36
+ });
37
+ children.push(child);
38
+ for (const stream of [child.stdout, child.stderr]) {
39
+ stream.setEncoding("utf8");
40
+ stream.on("data", (chunk) => {
41
+ for (const line of chunk.split(/\r?\n/).filter(Boolean)) log(name, line);
42
+ });
43
+ }
44
+ child.once("error", (error) => {
45
+ log(name, `Unable to start: ${error.message}`, console.error);
46
+ process.exitCode = 1;
47
+ void stop();
48
+ });
49
+ child.once("close", (code) => {
50
+ if (!stopping && !restarting) {
51
+ process.exitCode = code ?? 1;
52
+ void stop();
53
+ }
54
+ });
55
+ }
56
+
57
+ function signalChild(child, signal) {
58
+ try {
59
+ if (process.platform !== "win32" && child.pid) {
60
+ process.kill(-child.pid, signal);
61
+ } else if (child.exitCode === null && child.signalCode === null) {
62
+ child.kill(signal);
63
+ }
64
+ } catch (error) {
65
+ if (error.code !== "ESRCH") throw error;
66
+ }
67
+ }
68
+
69
+ function waitForClose(child, timeout) {
70
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
71
+ return new Promise((resolve) => {
72
+ const timer = setTimeout(() => {
73
+ child.off("close", onClose);
74
+ resolve();
75
+ }, timeout);
76
+ const onClose = () => {
77
+ clearTimeout(timer);
78
+ resolve();
79
+ };
80
+ child.once("close", onClose);
81
+ });
82
+ }
83
+
84
+ async function stopChildren() {
85
+ const running = [...children];
86
+ for (const child of running) signalChild(child, "SIGINT");
87
+ await Promise.all(running.map((child) => waitForClose(child, 3000)));
88
+ for (const child of running) signalChild(child, "SIGTERM");
89
+ await Promise.all(running.map((child) => waitForClose(child, 1000)));
90
+ for (const child of running) signalChild(child, "SIGKILL");
91
+ await Promise.all(running.map((child) => waitForClose(child, 1000)));
92
+ children.length = 0;
93
+ }
94
+
95
+ async function stop() {
96
+ if (stopping) return;
97
+ stopping = true;
98
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
99
+ process.stdin.pause();
100
+ await stopChildren();
101
+ }
102
+
103
+ async function restart() {
104
+ if (restarting || stopping) return;
105
+ restarting = true;
106
+ log("dev", "Restarting application processes...");
107
+ await stopChildren();
108
+ if (stopping) return;
109
+ restarting = false;
110
+ for (const app of apps) start(app);
111
+ log("dev", "Application processes restarted.");
112
+ }
113
+
114
+ for (const app of apps) start(app);
115
+
116
+ for (const signal of ["SIGINT", "SIGTERM"]) {
117
+ process.once(signal, () => void stop());
118
+ }
119
+
120
+ if (process.stdin.isTTY) {
121
+ console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
122
+ process.stdin.setRawMode(true);
123
+ process.stdin.resume();
124
+ process.stdin.on("data", (key) => {
125
+ if (key.includes("\u0003")) void stop();
126
+ else if (key.toString().toLowerCase() === "r") void restart();
127
+ else if (key.toString().toLowerCase() === "c") {
128
+ process.stdout.write("\x1b[2J\x1b[H");
129
+ console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
130
+ }
131
+ });
132
+ }
@@ -0,0 +1,25 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const root = fileURLToPath(new URL("../", import.meta.url));
6
+ const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
7
+
8
+ console.log("Installing workspace dependencies:");
9
+ for (const workspace of project.workspaces) {
10
+ const manifest = JSON.parse(
11
+ await readFile(join(root, workspace, "package.json"), "utf8"),
12
+ );
13
+ const dependencies = {
14
+ ...manifest.dependencies,
15
+ ...manifest.devDependencies,
16
+ };
17
+ console.log(`\n${manifest.name} (${workspace}):`);
18
+ if (!Object.keys(dependencies).length) {
19
+ console.log(" No dependencies declared.");
20
+ continue;
21
+ }
22
+ for (const [name, version] of Object.entries(dependencies)) {
23
+ console.log(` - ${name}@${version}`);
24
+ }
25
+ }
@@ -0,0 +1,45 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const [app, ...args] = process.argv.slice(2);
7
+ const root = fileURLToPath(new URL("../", import.meta.url));
8
+ const { workspaces } = JSON.parse(
9
+ await readFile(join(root, "package.json"), "utf8"),
10
+ );
11
+ const workspace = workspaces.find((name) => name.endsWith(`-${app}`));
12
+
13
+ if (!workspace || !["client", "server"].includes(app)) {
14
+ console.error("Usage: npm|pnpm client|server [ -dev | add <package...> ]");
15
+ process.exit(1);
16
+ }
17
+
18
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
19
+ ? "pnpm"
20
+ : "npm";
21
+ let commandArgs;
22
+ if (args[0] === "add" && args.length > 1) {
23
+ commandArgs =
24
+ packageManager === "pnpm"
25
+ ? ["--filter", workspace, "add", ...args.slice(1)]
26
+ : ["install", ...args.slice(1), "--workspace", workspace];
27
+ } else if (args.length === 0 || (args.length === 1 && args[0] === "-dev")) {
28
+ const script = args[0] === "-dev" ? "dev" : "start";
29
+ commandArgs =
30
+ packageManager === "pnpm"
31
+ ? ["--filter", workspace, "run", script]
32
+ : ["run", script, "--workspace", workspace];
33
+ } else {
34
+ console.error(`Usage: ${packageManager} ${app} [ -dev | add <package...> ]`);
35
+ process.exit(1);
36
+ }
37
+
38
+ const child = spawn(packageManager, commandArgs, { cwd: root, stdio: "inherit" });
39
+ child.once("error", (error) => {
40
+ console.error(`Unable to run ${packageManager}: ${error.message}`);
41
+ process.exitCode = 1;
42
+ });
43
+ child.once("exit", (code, signal) => {
44
+ process.exitCode = code ?? (signal ? 1 : 0);
45
+ });