import fs from 'node:fs'; import path, { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { autocomplete, cancel, groupMultiselect, isCancel, log, multiselect, note, outro, select, taskLog, text, } from '@clack/prompts'; import { determineAgent } from '@vercel/detect-agent'; import deepmerge from 'deepmerge'; import minimist from 'minimist'; import { color, logger } from 'rslog'; import { x, xSync } from 'tinyexec'; import { getAgentCreateCommand, replaceCreateCommand, } from './package-manager.js'; import { isNpmTemplate, resolveCustomTemplate } from './template-manager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); export { autocomplete, groupMultiselect, multiselect, select, text }; export { xSync }; // Export npm template utilities export { isNpmTemplate, resolveCustomTemplate, resolveNpmTemplate, sanitizeCacheKey, } from './template-manager.js'; function cancelAndExit() { cancel('Operation cancelled'); process.exit(0); } export function checkCancel(value: unknown) { if (isCancel(value)) { cancelAndExit(); } return value as T; } /** * 1. Input: 'foo' * Output: folder `/foo`, `package.json#name` -> `foo` * * 2. Input: 'foo/bar' * Output: folder -> `/foo/bar` folder, `package.json#name` -> `bar` * * 3. Input: '@scope/foo' * Output: folder -> `/@scope/bar` folder, `package.json#name` -> `@scope/foo` * * 4. Input: './foo/bar' * Output: folder -> `/foo/bar` folder, `package.json#name` -> `bar` * * 5. Input: '/root/path/to/foo' * Output: folder -> `'/root/path/to/foo'` folder, `package.json#name` -> `foo` */ function formatProjectName(input: string) { const formatted = input.trim().replace(/\/+$/g, ''); return { packageName: formatted.startsWith('@') ? formatted : path.basename(formatted), targetDir: formatted, }; } function pkgFromUserAgent(userAgent: string | undefined) { if (!userAgent) return undefined; const pkgSpec = userAgent.split(' ')[0]; const pkgSpecArr = pkgSpec.split('/'); return { name: pkgSpecArr[0], version: pkgSpecArr[1], }; } const PACKAGE_MANAGER_FILES = [ { file: 'pnpm-workspace.yaml', packageManager: 'pnpm' }, ]; function getPackageManagerSkipFiles(packageManager: string) { return PACKAGE_MANAGER_FILES.filter( (item) => item.packageManager !== packageManager, ).map((item) => item.file); } function isEmptyDir(path: string) { const files = fs.readdirSync(path); return files.length === 0 || (files.length === 1 && files[0] === '.git'); } function parseToolsOption(tools: Argv['tools']) { if (typeof tools === 'undefined') { return null; } const toolsArr = Array.isArray(tools) ? tools : [tools]; return toolsArr .flatMap((tool) => tool.split(',')) .map((tool) => tool.trim()) .filter(Boolean); } function parseSkillsOption(skills: Argv['skill']) { if (typeof skills === 'undefined') { return null; } const skillsArr = Array.isArray(skills) ? skills : [skills]; return skillsArr .flatMap((skill) => skill.split(',')) .map((skill) => skill.trim()) .filter(Boolean); } export type Argv = { help?: boolean; dir?: string; template?: string; git?: boolean; override?: boolean; tools?: string | string[]; skill?: string | string[]; packageName?: string; 'package-name'?: string; templateVersion?: string; 'template-version'?: string; }; export type GitContext = { /** Whether Git initialization is enabled for the generated project. */ gitEnabled: boolean; /** Whether the generated project is the root of its Git worktree. */ isGitRoot: boolean; }; export type GitResolvedContext = GitContext & { templateName: string; distFolder: string; }; export type TemplateCreateContext = { /** Absolute path to the project directory. */ distFolder: string; packageName: string; packageManager: string; gitEnabled: boolean; /** Whether overwriting was requested or confirmed by the user. */ override: boolean; }; export type Template = | string | { name: string; /** * Create a project using an external CLI or custom generation logic. * Replaces the toolkit's built-in project setup. */ create: (context: TemplateCreateContext) => void | Promise; }; export type BuiltinToolName = 'eslint' | 'rslint' | 'biome' | 'prettier'; export const BUILTIN_TOOLS: BuiltinToolName[] = [ 'eslint', 'rslint', 'biome', 'prettier', ]; type ToolOption = { value: string; label: string; hint?: string; }; const BUILTIN_TOOL_OPTIONS: Array = [ { value: 'rslint', label: 'Rslint - linting' }, { value: 'eslint', label: 'ESLint - linting' }, { value: 'prettier', label: 'Prettier - formatting' }, { value: 'biome', label: 'Biome - linting & formatting' }, ]; function resolveBuiltinTools( builtinTools: BuiltinToolName[] | undefined, ): BuiltinToolName[] { if (Array.isArray(builtinTools)) { const selectedTools = new Set(builtinTools); return BUILTIN_TOOLS.filter((tool) => selectedTools.has(tool)); } return [...BUILTIN_TOOLS]; } function logHelpMessage( name: string, templates: Template[], git: boolean, builtinTools: BuiltinToolName[] | undefined, extraTools?: ExtraTool[], extraSkills?: ExtraSkill[], ) { const toolsList: string[] = resolveBuiltinTools(builtinTools); // Keep help output exhaustive for discoverability. `skill.when` only gates // the interactive prompt, not the documented list of available skills. const skillsList = (extraSkills ?? []) .map((skill) => skill.value) .filter(Boolean); const hasSkills = skillsList.length > 0; if (extraTools) { for (const tool of extraTools) { if (!tool.value) { continue; } if (tool.order === 'pre') { toolsList.unshift(tool.value); } else { toolsList.push(tool.value); } } } const hasTools = toolsList.length > 0; const options: [flags: string, description: string][] = [ ['-h, --help', 'display help for command'], ['-d, --dir ', 'create project in specified directory'], ['-t, --template ', 'specify the template to use'], ]; if (git) { options.push(['--no-git', 'skip Git repository initialization']); } if (hasTools) { options.push(['--tools ', 'add additional tools, comma separated']); } if (hasSkills) { options.push(['--skill ', 'add optional skills, comma separated']); } options.push( ['--override', 'override files in target directory'], ['--package-name ', 'specify the package name'], ['--template-version ', 'specify the npm template version'], ); const optionWidth = Math.max(...options.map(([flags]) => flags.length)); const optionLines = options .map( ([flags, description]) => ` ${flags.padEnd(optionWidth)} ${description}`, ) .join('\n'); const helpSections = [ `Usage: create-${name} [dir] [options]`, '', 'Options:', optionLines, '', `Available templates: ${templates.map((template) => (typeof template === 'string' ? template : template.name)).join(', ')}`, ]; if (hasTools) { helpSections.push('', `Optional tools: ${toolsList.join(', ')}`); } if (hasSkills) { helpSections.push('', `Optional skills: ${skillsList.join(', ')}`); } logger.log(helpSections.join('\n')); } async function getTools( { tools, dir, template }: Argv, builtinTools: BuiltinToolName[] | undefined, extraTools?: ExtraTool[], templateName?: string, ) { // Check if tools are specified via CLI options const parsedTools = parseToolsOption(tools); const enabledBuiltinTools = resolveBuiltinTools(builtinTools); const enabledBuiltinToolSet = new Set(enabledBuiltinTools); // Filter extraTools based on templateName const filteredExtraTools = extraTools?.filter((tool) => { const when = tool.when ?? (() => true); return templateName ? when({ templateName }) : true; }); if (parsedTools !== null) { const toolsArr = parsedTools.filter( (tool) => enabledBuiltinToolSet.has(tool) || filteredExtraTools?.some((extraTool) => extraTool.value === tool), ); return toolsArr; } // skip tools selection when using CLI options if (dir && template) { return []; } const options: ToolOption[] = BUILTIN_TOOL_OPTIONS.filter(({ value }) => enabledBuiltinToolSet.has(value), ); if (filteredExtraTools) { const normalize = (tool: ExtraTool) => ({ value: tool.value, label: tool.label, hint: tool.command, }); options.unshift( ...filteredExtraTools .filter((tool) => tool.order === 'pre') .map(normalize), ); options.push( ...filteredExtraTools .filter((tool) => tool.order !== 'pre') .map(normalize), ); } if (options.length === 0) { return []; } return checkCancel( await multiselect({ message: 'Select additional tools (Use to select, to continue)', options, required: false, }), ); } function filterExtraSkills( extraSkills: ExtraSkill[] | undefined, templateName?: string, tools: string[] = [], ) { // `skill.when` only affects the interactive prompt. Explicit `--skill` // values are handled separately in `getSkills`. return extraSkills?.filter((extraSkill) => { const when = extraSkill.when ?? (() => true); return templateName ? when({ templateName, tools }) : true; }); } function orderExtraSkills(extraSkills: ExtraSkill[] | undefined) { if (!extraSkills) { return []; } return [ ...extraSkills.filter((extraSkill) => extraSkill.order === 'pre'), ...extraSkills.filter( (extraSkill) => typeof extraSkill.order === 'undefined', ), ...extraSkills.filter((extraSkill) => extraSkill.order === 'post'), ]; } async function getSkills( { skill, dir, template }: Argv, extraSkills?: ExtraSkill[], templateName?: string, tools: string[] = [], promptMultiselect: typeof multiselect = multiselect, ) { const parsedSkills = parseSkillsOption(skill); const filteredExtraSkills = filterExtraSkills( extraSkills, templateName, tools, ); if (parsedSkills !== null) { // Treat explicit `--skill` values as authoritative as long as they refer to // a declared skill. `skill.when` only hides options from the prompt. return parsedSkills.filter((value: string) => extraSkills?.some((extraSkill) => extraSkill.value === value), ); } if (dir && template) { return []; } if (!filteredExtraSkills?.length) { return []; } const orderedExtraSkills = orderExtraSkills(filteredExtraSkills); return checkCancel( await promptMultiselect({ message: 'Select optional skills (Use to select, to continue)', options: orderedExtraSkills.map((extraSkill) => ({ value: extraSkill.value, label: extraSkill.label, hint: extraSkill.source, })), required: false, }), ); } function upperFirst(str: string) { return str.charAt(0).toUpperCase() + str.slice(1); } export type ESLintTemplateName = | 'vanilla-js' | 'vanilla-ts' | 'react-js' | 'react-ts' | 'vue-ts' | 'vue-js' | 'svelte-js' | 'svelte-ts'; export type RslintTemplateName = 'vanilla-js' | 'vanilla-ts' | 'react-js' | 'react-ts'; const readJSON = async (path: string) => JSON.parse(await fs.promises.readFile(path, 'utf-8')); const readPackageJson = async (filePath: string) => readJSON(path.join(filePath, 'package.json')); const parseArgv = (processArgv: string[]) => { const argv = minimist(processArgv.slice(2), { alias: { h: 'help', d: 'dir', t: 'template' }, boolean: ['git'], default: { git: true }, }); // Set dir to first argument if not specified via `--dir` if (!argv.dir && argv._[0]) { argv.dir = argv._[0]; } if (argv['package-name']) { argv.packageName = argv['package-name']; } // Handle template-version alias if (argv['template-version']) { argv.templateVersion = argv['template-version']; } return argv; }; function validateCustomTemplateOptions(argv: Argv, templateName: string) { const unsupportedOptions: string[] = []; if (argv.tools !== undefined) { unsupportedOptions.push('--tools'); } if (argv.skill !== undefined) { unsupportedOptions.push('--skill'); } const templateVersion = argv.templateVersion ?? argv['template-version']; if (templateVersion !== undefined) { unsupportedOptions.push('--template-version'); } if (unsupportedOptions.length) { throw new Error( `Template "${templateName}" does not support ${unsupportedOptions.join(', ')}. Remove the unsupported options and use the template's setup flow instead.`, ); } } type ExtraTool = { /** * The value of the multiselect option. */ value: string; /** * The label of the multiselect option. */ label: string; /** * The action to perform when the tool is selected. */ action?: (context: { templateName: string; packageManager: string; distFolder: string; skipFiles: string[]; addAgentsMdSearchDirs: (dir: string) => void; }) => unknown; /** * The custom command to run when the tool is selected. */ command?: string; /** * Specify where to display this tool. * If undefined, the tool will be displayed after built-in tools. */ order?: 'pre' | 'post'; /** * Condition to determine whether this tool should be displayed. * If returns false, the tool will not be shown in the selection. * @default () => true */ when?: (context: { templateName: string }) => boolean; }; type ExtraSkill = { value: string; label: string; source: string; skill?: string; /** * Controls whether the skill is shown in the interactive prompt for the * selected template/tools. Explicit `--skill` values and `--help` remain * unfiltered so CLI input stays authoritative and help stays discoverable. */ when?: (context: { templateName: string; tools: string[] }) => boolean; order?: 'pre' | 'post'; }; async function runCommand( command: string, cwd: string, packageManager: string, ) { command = replaceCreateCommand(command, packageManager); const result = await x(command, [], { nodeOptions: { shell: true, stdio: 'inherit', cwd, }, }); if (result.exitCode !== 0) { const details = [result.stderr, result.stdout] .filter(Boolean) .join('\n') .trim(); throw new Error( `Failed to run command: ${command}${details ? `\n${details}` : ''}`, ); } } async function runSkillCommand(skills: ExtraSkill[], cwd: string) { const [firstSkill] = skills; // `skills add` accepts repeated `--skill` flags for a single source. const installArgs = skills.flatMap((skill) => [ '--skill', skill.skill ?? skill.value, ]); const args = [ '-y', 'skills', 'add', firstSkill.source, '--agent', 'universal', '--yes', '--copy', ...installArgs, ]; const command = `npx ${args.join(' ')}`; log.info(`Running skill install command: ${color.dim(command)}`); const skillLabel = skills.map((skill) => skill.value).join(', '); const skillNoun = skills.length === 1 ? 'skill' : 'skills'; const installationTaskLog = taskLog({ title: `Installing ${skillNoun} ${skillLabel}`, }); const proc = x('npx', args, { nodeOptions: { cwd, stdio: 'pipe', }, }); for await (const line of proc) { installationTaskLog.message(line); } const result = await proc; if (result.exitCode !== 0) { const quotedSkillLabel = skills .map((skill) => `"${skill.value}"`) .join(', '); const message = `Failed to install ${skillNoun} ${quotedSkillLabel} from "${firstSkill.source}" using command: ${command}`; installationTaskLog.error(message); throw new Error(message); } installationTaskLog.success(`Installed ${skillNoun} ${skillLabel}`); } function detectGitRoot(cwd: string): boolean | null { try { const result = xSync( 'git', ['rev-parse', '--is-inside-work-tree', '--show-prefix'], { nodeOptions: { cwd } }, ); if (result.exitCode !== 0) { return null; } const [insideWorkTree, prefix] = result.stdout.split(/\r?\n/u); return insideWorkTree === 'true' ? prefix === '' : null; } catch { return null; } } function initGit(cwd: string) { const currentIsGitRoot = detectGitRoot(cwd); if (currentIsGitRoot !== null) { // Reuse the current repository instead of creating a nested one. return currentIsGitRoot; } try { const result = xSync('git', ['init'], { nodeOptions: { cwd }, }); if (result.exitCode === 0) { log.success('Initialized Git repository'); return true; } const details = result.stderr.trim(); log.warn( `Failed to initialize Git repository.${details ? ` ${details}` : ''}`, ); } catch (error) { const details = error instanceof Error ? error.message : String(error); log.warn(`Failed to initialize Git repository. ${details}`); } return false; } async function resolveGit({ gitEnabled, distFolder, templateName, onGitResolved, }: { gitEnabled: boolean; distFolder: string; templateName: string; onGitResolved?: (context: GitResolvedContext) => void | Promise; }) { let projectIsGitRoot = false; if (gitEnabled) { projectIsGitRoot = initGit(distFolder); } else if (onGitResolved) { projectIsGitRoot = detectGitRoot(distFolder) ?? false; } if (onGitResolved) { await onGitResolved({ templateName, distFolder, gitEnabled, isGitRoot: projectIsGitRoot, }); } } function logNextStepsAndOutro( noteInformation: string[] | undefined, targetDir: string, packageManager: string, ) { const nextSteps = noteInformation ? noteInformation : [ `1. ${color.cyan(`cd ${targetDir}`)}`, `2. ${color.cyan(`${packageManager} install`)}`, `3. ${color.cyan(`${packageManager} run dev`)}`, ]; if (nextSteps.length) { note(nextSteps.map((step) => color.reset(step)).join('\n'), 'Next steps'); } outro('All set, happy coding!'); } export async function create({ name, root, templates, skipFiles, getTemplateName, getPackageManager, mapESLintTemplate, mapRslintTemplate, version, banner, noteInformation, git = true, onGitResolved, builtinTools, extraTools, extraSkills, argv: processArgv = process.argv, }: { name: string; root: string; skipFiles?: string[]; templates: Template[]; getTemplateName: (argv: Argv) => Promise; /** * Specify the package manager for the selected template. * Return undefined to use the package manager detected from the user agent, * falling back to npm when no user agent is available. */ getPackageManager?: (context: { templateName: string }) => string | undefined; /** * Map the template name to the ESLint template name. * If not provided, defaults to 'vanilla-ts' for all templates. */ mapESLintTemplate?: ( templateName: string, context: { distFolder: string }, ) => ESLintTemplateName | null; /** * Map the template name to the Rslint template name. * If not provided, defaults to 'vanilla-ts' for all templates. */ mapRslintTemplate?: ( templateName: string, context: { distFolder: string }, ) => RslintTemplateName | null; version?: Record | string; /** * The complete text to display in the startup greeting. * Omit this option to use `Create Project`. */ banner?: string; noteInformation?: string[]; /** * Whether to initialize a Git repository by default when the target directory * is not already inside one. Users can opt out with `--no-git`. * * @default true */ git?: boolean; /** * Runs after template files are copied and the optional Git initialization * has been resolved. */ onGitResolved?: (context: GitResolvedContext) => void | Promise; /** * Controls which built-in tools are available. * * Omit this option to enable all built-in tools. Pass an empty array to * disable them, or list the built-in tools that should remain available. * Additional tools are configured separately with `extraTools`. * * @default BUILTIN_TOOLS */ builtinTools?: BuiltinToolName[]; /** * Specify additional tools. */ extraTools?: ExtraTool[]; extraSkills?: ExtraSkill[]; /** * For test purpose, override the default argv (process.argv). */ argv?: string[]; }) { const argv = parseArgv(processArgv); if (argv.help) { logHelpMessage(name, templates, git, builtinTools, extraTools, extraSkills); return; } logger.greet(`\n◆ ${banner ?? `Create ${upperFirst(name)} Project`}`); const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent); const detectedPackageManager = pkgInfo ? pkgInfo.name : 'npm'; const { isAgent } = await determineAgent(); if (isAgent) { console.log(''); logger.info( `To create a project non-interactively, run: ${getAgentCreateCommand(name, detectedPackageManager)} --template