@cellajs/create-cella 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 CellaJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ import './src/index.js';
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@cellajs/create-cella",
3
+ "version": "0.0.2",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "description": "Intuivive TypeScript template to build local-first web apps. Implementation-ready. MIT license.",
7
+ "keywords": [
8
+ "template",
9
+ "monorepo",
10
+ "fullstack",
11
+ "typescript",
12
+ "hono",
13
+ "drizzle",
14
+ "shadcn",
15
+ "postgres",
16
+ "react",
17
+ "vite",
18
+ "pwa",
19
+ "cli"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/cellajs/cella",
27
+ "directory": "cli/create-cella"
28
+ },
29
+ "homepage": "https://cellajs.com",
30
+ "author": "CellaJS <info@cellajs.com>",
31
+ "engines": {
32
+ "node": ">=20.14.0"
33
+ },
34
+ "type": "module",
35
+ "main": "index.js",
36
+ "bin": {
37
+ "create-cella": "index.js"
38
+ },
39
+ "dependencies": {
40
+ "@inquirer/prompts": "^6.0.1",
41
+ "commander": "^12.1.0",
42
+ "cross-spawn": "^7.0.3",
43
+ "giget": "^1.2.3",
44
+ "picocolors": "^1.1.0",
45
+ "validate-npm-package-name": "^5.0.1",
46
+ "yocto-spinner": "^0.1.0"
47
+ },
48
+ "scripts": {
49
+ "create": "node index.js"
50
+ }
51
+ }
package/src/cli.js ADDED
@@ -0,0 +1,88 @@
1
+ import { basename, resolve } from 'node:path'
2
+ import { Command, InvalidArgumentError } from 'commander'
3
+
4
+ import { NAME } from './constants.js'
5
+
6
+ import { packageJson } from './utils/package-json.js'
7
+ import { validateProjectName } from './utils/validate-project-name.js'
8
+
9
+ // Initialize CLI variables
10
+ let directory = null;
11
+ let newBranchName = null;
12
+ let createNewBranch = null;
13
+ const packageManager = 'pnpm';
14
+
15
+ // Set up the CLI command using Commander
16
+ export const command = new Command(NAME)
17
+ .version(packageJson.version, '-v, --version', `Output the current version of ${NAME}.`)
18
+ .argument('[directory]', 'The directory name for the new project.')
19
+ .usage('[directory] [options]')
20
+ .helpOption('-h, --help', 'Display this help message.')
21
+ .option(
22
+ '--skip-new-branch',
23
+ 'Skip creating a new branch during initialization.',
24
+ false,
25
+ )
26
+ .option(
27
+ '--skip-install',
28
+ 'Skip the installation of packages.',
29
+ false,
30
+ )
31
+ .option(
32
+ '--skip-clean',
33
+ 'Skip cleaning the `cella` template.',
34
+ false,
35
+ )
36
+ .option(
37
+ '--skip-git',
38
+ 'Skip initializing a git repository.',
39
+ false,
40
+ )
41
+ .option(
42
+ '--new-branch-name <name>',
43
+ 'Specify a new branch name to create and use.',
44
+ (name) => {
45
+ if (typeof name === 'string') {
46
+ name = name.trim();
47
+ }
48
+
49
+ if (name) {
50
+ const validation = validateProjectName(basename(resolve(name)))
51
+ if (!validation.valid) throw new InvalidArgumentError(`Invalid branch name: ${validation.problems[0]}`);
52
+
53
+ createNewBranch = true;
54
+ newBranchName = name;
55
+ }
56
+ },
57
+ )
58
+ .action((name) => {
59
+ if (typeof name === 'string') {
60
+ name = name.trim()
61
+ }
62
+
63
+ if (name) {
64
+ const validation = validateProjectName(basename(resolve(name)));
65
+ if (!validation.valid) throw new InvalidArgumentError(`Invalid project name: ${validation.problems[0]}`);
66
+
67
+ directory = name;
68
+ }
69
+ })
70
+ .parse();
71
+
72
+ // Gather the CLI options and arguments
73
+ const options = command.opts({
74
+ skipNewBranch: false,
75
+ skipClean: false,
76
+ skipGit: false,
77
+ skipInstall: false,
78
+ });
79
+
80
+ // Export the CLI configuration for use in other modules
81
+ export const cli = {
82
+ options,
83
+ args: command.args,
84
+ directory,
85
+ newBranchName,
86
+ createNewBranch,
87
+ packageManager,
88
+ };
@@ -0,0 +1,31 @@
1
+ export const NAME = 'create-cella'
2
+
3
+ // URL of the template repository
4
+ export const TEMPLATE_URL = 'github:cellajs/cella';
5
+
6
+ // Files or folders to be removed from the template after downloading
7
+ export const TO_REMOVE = [
8
+ 'info',
9
+ './cli/create-cella'
10
+ ];
11
+
12
+ // Specific folder contents to be cleaned out from the template
13
+ export const TO_CLEAN = [
14
+ './backend/drizzle'
15
+ ];
16
+
17
+ // Files to copy/paste after downloading
18
+ export const TO_COPY = {
19
+ './backend/.env.example': './backend/.env',
20
+ './tus/.env.example': './tus/.env',
21
+ './info/QUICKSTART.md': 'README.md',
22
+ };
23
+
24
+ // ASCII title for the CLI output
25
+ export const CELLA_TITLE = `
26
+ _ _
27
+ ▒▓█████▓▒ ___ ___| | | __ _
28
+ ▒▓█ █▓▒ / __/ _ \\ | |/ _\` |
29
+ ▒▓█ █▓▒ | (_| __/ | | (_| |
30
+ ▒▓█████▓▒ \\___\\___|_|_|\\__,_|
31
+ `;
package/src/create.js ADDED
@@ -0,0 +1,148 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { existsSync } from 'node:fs'
3
+ import { join, relative } from 'node:path';
4
+ import colors from 'picocolors';
5
+ import { downloadTemplate } from "giget";
6
+ import yoctoSpinner from 'yocto-spinner';
7
+
8
+ import { TEMPLATE_URL} from './constants.js';
9
+
10
+ import { install } from './utils/run-package-manager-command.js';
11
+ import { cleanTemplate } from './utils/clean-template.js';
12
+ import { runGitCommand } from './utils/run-git-command.js';
13
+
14
+ export async function create({
15
+ projectName,
16
+ targetFolder,
17
+ newBranchName,
18
+ skipInstall,
19
+ skipGit,
20
+ skipClean,
21
+ packageManager,
22
+ }) {
23
+ // Save the original working directory
24
+ const originalCwd = process.cwd();
25
+
26
+ console.info();
27
+
28
+ // Create the target folder if it doesn't exist
29
+ const createFolderSpinner = yoctoSpinner({
30
+ text: 'Creating project folder',
31
+ }).start();
32
+
33
+ await mkdir(targetFolder, { recursive: true });
34
+ process.chdir(targetFolder);
35
+
36
+ createFolderSpinner.success('Project folder created');
37
+
38
+ // Download the template from the specified URL
39
+ const downloadSpinner = yoctoSpinner({
40
+ text: 'Downloading `cella` template',
41
+ }).start();
42
+
43
+ await downloadTemplate(TEMPLATE_URL, {
44
+ cwd: process.cwd(),
45
+ dir: targetFolder,
46
+ force: true,
47
+ provider: "github",
48
+ });
49
+
50
+ downloadSpinner.success('`cella` template downloaded');
51
+
52
+ // Clean the template if the skipClean flag is not set
53
+ if (!skipClean) {
54
+ const cleanSpinner = yoctoSpinner({
55
+ text: 'cleaning `cella` template',
56
+ }).start();
57
+
58
+ try {
59
+ await cleanTemplate({
60
+ targetFolder,
61
+ projectName,
62
+ })
63
+ cleanSpinner.success('`cella` template cleaned')
64
+ } catch (e) {
65
+ console.error(e);
66
+ cleanSpinner.error('Failed to clean `cella` template');
67
+ process.exit(1);
68
+ }
69
+ } else {
70
+ console.info(`${colors.yellow('⚠')} --skip-clean > Skip cleaning \`cella\` template'`)
71
+ }
72
+
73
+ // Install dependencies if the skipInstall flag is not set
74
+ if (!skipInstall) {
75
+ const installSpinner = yoctoSpinner({
76
+ text: 'installing dependencies',
77
+ }).start();
78
+
79
+ try {
80
+ await install(packageManager)
81
+ installSpinner.success('Dependencies installed');
82
+ } catch (e) {
83
+ console.error(e);
84
+ installSpinner.error('Failed to install dependencies');
85
+ process.exit(1);
86
+ }
87
+ } else {
88
+ console.info(`${colors.yellow('⚠')} --skip-install > Skip installing dependencies`)
89
+ }
90
+
91
+ // Initialize Git repository if skipGit flag is not set
92
+ if (!skipGit) {
93
+ const gitSpinner = yoctoSpinner({
94
+ text: 'initializing git repository',
95
+ }).start();
96
+
97
+ const gitFolderPath = join(targetFolder, '.git');
98
+
99
+ if (!existsSync(gitFolderPath)) {
100
+ try {
101
+ // Run Git commands to initialize the repository and make the first commit
102
+ await runGitCommand({ targetFolder, command: 'init' });
103
+ await runGitCommand({ targetFolder, command: 'add .' });
104
+ await runGitCommand({ targetFolder, command: 'commit -m "Initial commit"' });
105
+
106
+ // If a new branch name is specified, create and checkout the branch
107
+ if (newBranchName) {
108
+ await runGitCommand({ targetFolder, command: `branch ${newBranchName}` });
109
+ await runGitCommand({ targetFolder, command: `checkout ${newBranchName}` });
110
+ gitSpinner.success(`Git repository initialized, initial commit created, and new branch ${newBranchName} created`);
111
+ } else {
112
+ gitSpinner.success('Git repository initialized and initial commit created');
113
+ }
114
+
115
+ } catch (e) {
116
+ console.error(e);
117
+ gitSpinner.error('Failed to initialize Git repository or create branch');
118
+ process.exit(1);
119
+ }
120
+ } else {
121
+ gitSpinner.warning('Git repository already initialized > Skip git init')
122
+ }
123
+ } else {
124
+ console.info(`${colors.yellow('⚠')} --skip-git > Skip git init`)
125
+ }
126
+
127
+ // Final success message indicating project creation
128
+ console.info()
129
+ console.info(`${colors.green('Success')} Created ${projectName} at ${targetFolder}`)
130
+ console.info()
131
+
132
+ // Check if the working directory needs to be changed
133
+ const needsCd = originalCwd !== targetFolder;
134
+ if (needsCd) {
135
+ // Calculate the relative path between the original working directory and the target folder
136
+ const relativePath = relative(originalCwd, targetFolder);
137
+
138
+ console.info('now go to your project using:')
139
+ console.info(colors.cyan(` cd ./${relativePath}`)); // Adding './' to make it clear it's a relative path
140
+ console.info()
141
+ }
142
+ console.info(`${needsCd ? 'then ' : ''}quick start with:`)
143
+ console.info(colors.cyan(` ${packageManager} quick`))
144
+ console.info()
145
+
146
+ console.info('Read the readme in project root for more info on how to get started!')
147
+ console.info(`Enjoy building ${projectName} using cella! 🎉`)
148
+ }
package/src/index.js ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { basename, resolve } from 'node:path'
4
+ import { existsSync } from 'node:fs'
5
+
6
+ import { input, confirm, select } from '@inquirer/prompts';
7
+
8
+ import { cli } from './cli.js'
9
+ import { validateProjectName } from './utils/validate-project-name.js'
10
+ import { isEmptyDirectory } from './utils/is-empty-directory.js'
11
+ import { create } from './create.js'
12
+ import { CELLA_TITLE } from './constants.js'
13
+
14
+ async function main() {
15
+ console.info(CELLA_TITLE);
16
+
17
+ // Skip creating a new branch if --skipNewBranch flag is provided or git is skipped
18
+ if (cli.options.skipNewBranch || cli.options.skipGit) {
19
+ cli.createNewBranch = false;
20
+ cli.newBranchName = null;
21
+ }
22
+
23
+ // Skip installing packages if --skipInstall flag is provided
24
+ if (cli.options.skipInstall === true) {
25
+ cli.options.skipInstall = true;
26
+ }
27
+
28
+ // Skip cleaning the template if --skipClean flag is provided
29
+ if (cli.options.skipClean === true) {
30
+ cli.options.skipClean = true;
31
+ }
32
+
33
+ // Skip initializing git if --skipGit flag is provided
34
+ if (cli.options.skipGit === true) {
35
+ cli.options.skipGit = true;
36
+ }
37
+
38
+ // Prompt for project name if not provided
39
+ if (!cli.directory) {
40
+ cli.directory = await input({
41
+ message: 'Enter your project name',
42
+ default: 'my-cella-app',
43
+ validate: (name) => {
44
+ const validation = validateProjectName(basename(resolve(name)));
45
+ return validation.valid ? true : `Invalid project name: ${validation.problems[0]}`;
46
+ },
47
+ });
48
+ }
49
+
50
+ // Prompt to create a new branch besides the main branch (if not skipped)
51
+ if (cli.createNewBranch === null) {
52
+ cli.createNewBranch = await confirm({
53
+ message: 'Would you like to create a new branch (besides "main")?',
54
+ default: true,
55
+ });
56
+ }
57
+
58
+ // Prompt for new branch name, only if user opted to create a new branch
59
+ if (!cli.newBranchName && cli.createNewBranch) {
60
+ cli.newBranchName = await input({
61
+ message: 'Enter the new branch name',
62
+ default: 'development',
63
+ validate: (name) => {
64
+ const validation = validateProjectName(basename(resolve(name)))
65
+ return validation.valid ? true : `Invalid branch name: ${validation.problems[0]}`;
66
+ },
67
+ });
68
+ }
69
+
70
+ const targetFolder = resolve(cli.directory)
71
+ const projectName = basename(targetFolder)
72
+
73
+ // Check if the target folder exists and is not empty
74
+ if (existsSync(targetFolder) && !(await isEmptyDirectory(targetFolder))) {
75
+ const dirName = cli.directory === '.' ? 'Current directory' : `Target directory "${targetFolder}"`;
76
+ const message = `${dirName} is not empty. Please choose how you would like to proceed:`;
77
+
78
+ const action = await select({
79
+ message,
80
+ choices: [
81
+ { name: 'Cancel and exit', value: 'cancel' },
82
+ { name: 'Ignore existing files and continue', value: 'ignore' },
83
+ ],
84
+ });
85
+ if (action === 'cancel') {
86
+ process.exit(1);
87
+ }
88
+ }
89
+
90
+ // Proceed with the project creation
91
+ await create({
92
+ projectName,
93
+ targetFolder,
94
+ newBranchName: cli.newBranchName,
95
+ skipInstall: cli.options.skipInstall,
96
+ skipGit: cli.options.skipGit,
97
+ skipClean: cli.options.skipClean,
98
+ packageManager: cli.packageManager,
99
+ });
100
+ }
101
+
102
+ main().catch(console.error)
@@ -0,0 +1,99 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import colors from 'picocolors';
4
+
5
+ import { TO_CLEAN, TO_REMOVE, TO_COPY } from '../constants.js';
6
+
7
+ /**
8
+ * Cleans the specified template by removing designated folders and files.
9
+ * @param {Object} params - Parameters containing targetFolder.
10
+ * @param {string} params.targetFolder - The folder to clean.
11
+ */
12
+ export async function cleanTemplate({
13
+ targetFolder,
14
+ projectName,
15
+ }) {
16
+ // Change the current working directory to targetFolder if not already set
17
+ if (process.cwd() !== targetFolder) {
18
+ process.chdir(targetFolder);
19
+ }
20
+
21
+ return new Promise(async (resolve, reject) => {
22
+ try {
23
+ // Copy specified files
24
+ for (const [src, dest] of Object.entries(TO_COPY)) {
25
+ const srcAbsolutePath = path.resolve(targetFolder, src);
26
+ const destAbsolutePath = path.resolve(targetFolder, dest);
27
+ await copyFile(srcAbsolutePath, destAbsolutePath);
28
+ }
29
+
30
+ // Clean specified folder contents
31
+ await Promise.all(TO_CLEAN.map(folderPath => {
32
+ const absolutePath = path.resolve(targetFolder, folderPath);
33
+ return removeFolderContents(absolutePath);
34
+ }));
35
+
36
+ // Remove specified files and folders
37
+ await Promise.all(TO_REMOVE.map(filePath => {
38
+ const absolutePath = path.resolve(targetFolder, filePath);
39
+ return removeFileOrFolder(absolutePath);
40
+ }));
41
+
42
+ resolve();
43
+ } catch (err) {
44
+ reject(`Error during the cleaning process: ${err}`);
45
+ }
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Removes all contents within a specified folder.
51
+ * @param {string} folderPath - The path of the folder to clean.
52
+ */
53
+ export async function removeFolderContents(folderPath) {
54
+ // List all files in the folder
55
+ const files = await fs.readdir(folderPath);
56
+
57
+ await Promise.all(files.map(async (file) => {
58
+ const filePath = path.join(folderPath, file);
59
+
60
+ // Get the file or folder statistics
61
+ const stat = await fs.lstat(filePath);
62
+
63
+ // If it's a directory, remove it and all its contents
64
+ if (stat.isDirectory()) {
65
+ await fs.rm(filePath, { recursive: true, force: true });
66
+ } else {
67
+ // If it's a file, remove it
68
+ await fs.rm(filePath);
69
+ }
70
+ }));
71
+ }
72
+
73
+ /**
74
+ * Removes a specified file or folder.
75
+ * @param {string} pathToRemove - The path to the file or folder to remove.
76
+ */
77
+ export async function removeFileOrFolder(pathToRemove) {
78
+ await fs.rm(pathToRemove, { recursive: true, force: true });
79
+ }
80
+
81
+ // Helper function to copy files if the source exists
82
+ export async function copyFile(src, dest) {
83
+ try {
84
+ // Check if the source file exists
85
+ await fs.access(src);
86
+
87
+ // Ensure the destination directory exists
88
+ await fs.mkdir(path.dirname(dest), { recursive: true });
89
+
90
+ // Copy the file
91
+ await fs.copyFile(src, dest);
92
+ } catch (err) {
93
+ if (err.code === 'ENOENT') {
94
+ console.info(`\n${colors.yellow('⚠')} Source file "${src}" does not exist > Skip copy`);
95
+ } else {
96
+ throw err;
97
+ }
98
+ }
99
+ }
@@ -0,0 +1,15 @@
1
+ import { readdir } from 'node:fs/promises'
2
+
3
+ /**
4
+ * Checks if a directory is empty or only contains a .git directory.
5
+ *
6
+ * @param {string} path - The path of the directory to check.
7
+ * @returns {Promise<boolean>} - Resolves to true if the directory is empty or contains only a .git folder, false otherwise.
8
+ * @throws {Error} - Throws an error if the path is not a directory or if there's an issue reading the directory.
9
+ */
10
+ export async function isEmptyDirectory(path) {
11
+ const files = await readdir(path);
12
+
13
+ // Check if directory is empty or contains only the .git directory
14
+ return files.length === 0 || (files.length === 1 && files[0] === '.git');
15
+ }
@@ -0,0 +1,22 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ /**
6
+ * Reads and parses the package.json file located in the root directory.
7
+ *
8
+ * @returns {Promise<object>} - A promise that resolves to the parsed package.json object.
9
+ * @throws {Error} - Throws an error if the package.json file cannot be found or read, or if the JSON is invalid.
10
+ */
11
+ async function readPackageJson() {
12
+ const PACKAGE_JSON_FILE = resolve(
13
+ fileURLToPath(import.meta.url),
14
+ '../../../package.json',
15
+ );
16
+
17
+ const packageJson = await readFile(PACKAGE_JSON_FILE, 'utf-8')
18
+ return JSON.parse(packageJson)
19
+ }
20
+
21
+ // Load the package.json at module initialization
22
+ export const packageJson = await readPackageJson()
@@ -0,0 +1,39 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ /**
4
+ * Executes a Git command in the specified target folder.
5
+ *
6
+ * @param {Object} options - Options for running the Git command.
7
+ * @param {string} options.targetFolder - The folder in which to run the command.
8
+ * @param {string} options.command - The Git command to execute (e.g., 'init', 'commit -m "message"', etc.).
9
+ * @returns {Promise<void>} - A promise that resolves if the command executes successfully; otherwise, it rejects with an error message.
10
+ * @throws {Error} - Throws an error if the Git command fails or if there is an error starting the process.
11
+ */
12
+ export async function runGitCommand({ targetFolder, command }) {
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(`git ${command}`, [], {
15
+ cwd: targetFolder,
16
+ shell: true,
17
+ timeout: 60000,
18
+ });
19
+
20
+ // Handle process errors
21
+ child.on("error", (error) => {
22
+ reject(error);
23
+ });
24
+
25
+ // Handle command exit
26
+ child.on("exit", (code) => {
27
+ if (code === 0) {
28
+ resolve();
29
+ } else {
30
+ reject(`Git command failed with exit code ${code}`);
31
+ }
32
+ });
33
+
34
+ // Swallow stdout and stderr
35
+ child.stdout.on("data", () => {});
36
+ child.stderr.on("data", () => {});
37
+ });
38
+ }
39
+
@@ -0,0 +1,56 @@
1
+ import spawn from 'cross-spawn'
2
+
3
+ /**
4
+ * Executes a command using the specified package manager (e.g., pnpm).
5
+ *
6
+ * @param {string} packageManager - The package manager to use (e.g., 'pnpm').
7
+ * @param {Array<string>} args - The arguments to pass to the package manager command.
8
+ * @param {Object} [env={}] - Additional environment variables to set during command execution.
9
+ * @returns {Promise<void>} - A promise that resolves if the command executes successfully; otherwise, it rejects with an error message.
10
+ */
11
+ export async function runPackageManagerCommand(packageManager, args, env = {} ) {
12
+ return new Promise((resolve, reject) => {
13
+ const child = spawn(packageManager, args, {
14
+ env: {
15
+ ...process.env,
16
+ ...env,
17
+ },
18
+ stdio: ['pipe', 'pipe', 'pipe'],
19
+ });
20
+
21
+ // Buffer for capturing stderr and stdout output
22
+ let stderrBuffer = ''
23
+ let stdoutBuffer = ''
24
+
25
+ // Capture stderr output
26
+ child.stderr?.on('data', (data) => {
27
+ stderrBuffer += data
28
+ });
29
+
30
+ // Capture stdout output
31
+ child.stdout?.on('data', (data) => {
32
+ stdoutBuffer += data
33
+ });
34
+
35
+ // Handle process exit
36
+ child.on('close', (code) => {
37
+ if (code !== 0) {
38
+ reject(`"${packageManager} ${args.join(' ')}" failed ${stdoutBuffer} ${stderrBuffer}` );
39
+ return;
40
+ }
41
+ resolve();
42
+ });
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Installs dependencies using the specified package manager.
48
+ *
49
+ * @param {string} packageManager - The package manager to use for installation (e.g., ''pnpm').
50
+ * @returns {Promise<void>} - A promise that resolves if the installation completes successfully; otherwise, it rejects with an error.
51
+ */
52
+ export async function install(packageManager) {
53
+ return runPackageManagerCommand(packageManager, ['install'], {
54
+ NODE_ENV: 'development',
55
+ });
56
+ }
@@ -0,0 +1,28 @@
1
+ import validate from 'validate-npm-package-name'
2
+
3
+ /**
4
+ * Validates a project name according to npm package naming conventions.
5
+ *
6
+ * @param {string} name - The name of the project to validate.
7
+ * @returns {Object} - An object containing the validation result and any associated problems.
8
+ * @returns {boolean} return.valid - Indicates if the project name is valid.
9
+ * @returns {Array<string>} return.problems - A list of errors and warnings associated with the project name.
10
+ */
11
+ export function validateProjectName(name) {
12
+ // Validate the project name
13
+ const nameValidation = validate(name);
14
+
15
+ // If the name is valid for new packages, return valid status
16
+ if (nameValidation.validForNewPackages) {
17
+ return { valid: true, problems: [] };
18
+ }
19
+
20
+ // Return validation result with errors and warnings
21
+ return {
22
+ valid: false,
23
+ problems: [
24
+ ...(nameValidation.errors || []),
25
+ ...(nameValidation.warnings || []),
26
+ ],
27
+ }
28
+ }