Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

cli.ts

557 lines17.2 KB

1import fs from 'node:fs'
2import { resolve } from 'node:path'
3import { Command, InvalidArgumentError } from 'commander'
4import { intro, log } from '@clack/prompts'
5import chalk from 'chalk'
6import semver from 'semver'
7​
8import {
9 SUPPORTED_PACKAGE_MANAGERS,
10 addToApp,
11 compileAddOn,
12 compileStarter,
13 createApp,
14 createSerializedOptions,
15 getAllAddOns,
16 getFrameworkByName,
17 getFrameworks,
18 initAddOn,
19 initStarter,
20} from '@tanstack/cta-engine'
21​
22import { launchUI } from '@tanstack/cta-ui'
23​
24import { runMCPServer } from './mcp.js'
25​
26import { promptForAddOns, promptForCreateOptions } from './options.js'
27import { normalizeOptions } from './command-line.js'
28​
29import { createUIEnvironment } from './ui-environment.js'
30import { convertTemplateToMode } from './utils.js'
31​
32import type { CliOptions, TemplateOptions } from './types.js'
33import type { Options, PackageManager } from '@tanstack/cta-engine'
34​
35// This CLI assumes that all of the registered frameworks have the same set of toolchains, deployments, modes, etc.
36​
37export function cli({
38 name,
39 appName,
40 forcedMode,
41 forcedAddOns = [],
42 defaultTemplate = 'javascript',
43 forcedDeployment,
44 defaultFramework,
45 craCompatible = false,
46 webBase,
47 showDeploymentOptions = false,
48}: {
49 name: string
50 appName: string
51 forcedMode?: string
52 forcedAddOns?: Array<string>
53 forcedDeployment?: string
54 defaultTemplate?: TemplateOptions
55 defaultFramework?: string
56 craCompatible?: boolean
57 webBase?: string
58 showDeploymentOptions?: boolean
59}) {
60 const environment = createUIEnvironment(appName, false)
61​
62 const program = new Command()
63​
64 const availableFrameworks = getFrameworks().map((f) => f.name)
65​
66 const toolchains = new Set<string>()
67 for (const framework of getFrameworks()) {
68 for (const addOn of framework.getAddOns()) {
69 if (addOn.type === 'toolchain') {
70 toolchains.add(addOn.id)
71 }
72 }
73 }
74​
75 const deployments = new Set<string>()
76 for (const framework of getFrameworks()) {
77 for (const addOn of framework.getAddOns()) {
78 if (addOn.type === 'deployment') {
79 deployments.add(addOn.id)
80 }
81 }
82 }
83​
84 let defaultMode: string | undefined = forcedMode
85 const supportedModes = new Set<string>()
86 for (const framework of getFrameworks()) {
87 for (const mode of Object.keys(framework.supportedModes)) {
88 supportedModes.add(mode)
89 }
90 }
91 if (defaultMode && !supportedModes.has(defaultMode)) {
92 throw new InvalidArgumentError(
93 `Invalid mode: ${defaultMode}. The following are allowed: ${Array.from(
94 supportedModes,
95 ).join(', ')}`,
96 )
97 }
98 if (supportedModes.size < 2) {
99 defaultMode = Array.from(supportedModes)[0]
100 }
101​
102 program.name(name).description(`CLI to create a new ${appName} application`)
103​
104 program
105 .command('pin-versions')
106 .description('Pin versions of the TanStack libraries')
107 .action(async () => {
108 if (!fs.existsSync('package.json')) {
109 console.error('package.json not found')
110 return
111 }
112 const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
113​
114 const packages: Record<string, string> = {
115 '@tanstack/react-router': '',
116 '@tanstack/router-generator': '',
117 '@tanstack/react-router-devtools': '',
118 '@tanstack/react-start': '',
119 '@tanstack/react-start-config': '',
120 '@tanstack/router-plugin': '',
121 '@tanstack/react-start-client': '',
122 '@tanstack/react-start-plugin': '1.115.0',
123 '@tanstack/react-start-server': '',
124 '@tanstack/start-server-core': '1.115.0',
125 }
126​
127 function sortObject(obj: Record<string, string>): Record<string, string> {
128 return Object.keys(obj)
129 .sort()
130 .reduce<Record<string, string>>((acc, key) => {
131 acc[key] = obj[key]
132 return acc
133 }, {})
134 }
135​
136 if (!packageJson.dependencies['@tanstack/react-start']) {
137 console.error('@tanstack/react-start not found in dependencies')
138 return
139 }
140 let changed = 0
141 const startVersion = packageJson.dependencies[
142 '@tanstack/react-start'
143 ].replace(/^\^/, '')
144 for (const pkg of Object.keys(packages)) {
145 if (!packageJson.dependencies[pkg]) {
146 packageJson.dependencies[pkg] = packages[pkg].length
147 ? semver.maxSatisfying(
148 [startVersion, packages[pkg]],
149 `^${packages[pkg]}`,
150 )!
151 : startVersion
152 changed++
153 } else {
154 if (packageJson.dependencies[pkg].startsWith('^')) {
155 packageJson.dependencies[pkg] = packageJson.dependencies[
156 pkg
157 ].replace(/^\^/, '')
158 changed++
159 }
160 }
161 }
162 packageJson.dependencies = sortObject(packageJson.dependencies)
163 if (changed > 0) {
164 fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2))
165 console.log(
166 `${changed} packages updated.
167​
168Remove your node_modules directory and package lock file and re-install.`,
169 )
170 } else {
171 console.log(
172 'No changes needed. The relevant TanStack packages are already pinned.',
173 )
174 }
175 })
176​
177 program
178 .command('add')
179 .argument(
180 '[add-on...]',
181 'Name of the add-ons (or add-ons separated by spaces or commas)',
182 )
183 .option('--forced', 'Force the add-on to be added', false)
184 .option('--ui', 'Add with the UI')
185 .action(async (addOns: Array<string>) => {
186 const parsedAddOns: Array<string> = []
187 for (const addOn of addOns) {
188 if (addOn.includes(',') || addOn.includes(' ')) {
189 parsedAddOns.push(
190 ...addOn.split(/[\s,]+/).map((addon) => addon.trim()),
191 )
192 } else {
193 parsedAddOns.push(addOn.trim())
194 }
195 }
196 if (program.opts().ui) {
197 launchUI({
198 mode: 'add',
199 addOns: parsedAddOns,
200 projectPath: resolve(process.cwd()),
201 forcedRouterMode: defaultMode,
202 forcedAddOns,
203 environmentFactory: () => createUIEnvironment(appName, false),
204 webBase,
205 showDeploymentOptions,
206 })
207 } else if (parsedAddOns.length < 1) {
208 const addOns = await promptForAddOns()
209 if (addOns.length) {
210 await addToApp(environment, addOns, resolve(process.cwd()), {
211 forced: program.opts().forced,
212 })
213 }
214 } else {
215 await addToApp(environment, parsedAddOns, resolve(process.cwd()), {
216 forced: program.opts().forced,
217 })
218 }
219 })
220​
221 const addOnCommand = program.command('add-on')
222 addOnCommand
223 .command('init')
224 .description('Initialize an add-on from the current project')
225 .action(async () => {
226 await initAddOn(environment)
227 })
228 addOnCommand
229 .command('compile')
230 .description('Update add-on from the current project')
231 .action(async () => {
232 await compileAddOn(environment)
233 })
234​
235 const starterCommand = program.command('starter')
236 starterCommand
237 .command('init')
238 .description('Initialize a project starter from the current project')
239 .action(async () => {
240 await initStarter(environment)
241 })
242 starterCommand
243 .command('compile')
244 .description('Compile the starter JSON file for the current project')
245 .action(async () => {
246 await compileStarter(environment)
247 })
248​
249 program.argument('[project-name]', 'name of the project')
250​
251 if (!defaultMode && craCompatible) {
252 program.option<'typescript' | 'javascript' | 'file-router'>(
253 '--template <type>',
254 'project template (typescript, javascript, file-router)',
255 (value) => {
256 if (
257 value !== 'typescript' &&
258 value !== 'javascript' &&
259 value !== 'file-router'
260 ) {
261 throw new InvalidArgumentError(
262 `Invalid template: ${value}. Only the following are allowed: typescript, javascript, file-router`,
263 )
264 }
265 return value
266 },
267 )
268 }
269​
270 if (!defaultFramework) {
271 program.option<string>(
272 '--framework <type>',
273 `project framework (${availableFrameworks.join(', ')})`,
274 (value) => {
275 if (
276 !availableFrameworks.some(
277 (f) => f.toLowerCase() === value.toLowerCase(),
278 )
279 ) {
280 throw new InvalidArgumentError(
281 `Invalid framework: ${value}. Only the following are allowed: ${availableFrameworks.join(', ')}`,
282 )
283 }
284 return value
285 },
286 defaultFramework || 'React',
287 )
288 }
289​
290 program
291 .option(
292 '--starter [url]',
293 'initialize this project from a starter URL',
294 false,
295 )
296 .option<PackageManager>(
297 `--package-manager <${SUPPORTED_PACKAGE_MANAGERS.join('|')}>`,
298 `Explicitly tell the CLI to use this package manager`,
299 (value) => {
300 if (!SUPPORTED_PACKAGE_MANAGERS.includes(value as PackageManager)) {
301 throw new InvalidArgumentError(
302 `Invalid package manager: ${value}. The following are allowed: ${SUPPORTED_PACKAGE_MANAGERS.join(
303 ', ',
304 )}`,
305 )
306 }
307 return value as PackageManager
308 },
309 )
310​
311 if (deployments.size > 0) {
312 program.option<string>(
313 `--deployment <${Array.from(deployments).join('|')}>`,
314 `Explicitly tell the CLI to use this deployment adapter`,
315 (value) => {
316 if (!deployments.has(value)) {
317 throw new InvalidArgumentError(
318 `Invalid adapter: ${value}. The following are allowed: ${Array.from(
319 deployments,
320 ).join(', ')}`,
321 )
322 }
323 return value
324 },
325 )
326 }
327​
328 if (toolchains.size > 0) {
329 program.option<string>(
330 `--toolchain <${Array.from(toolchains).join('|')}>`,
331 `Explicitly tell the CLI to use this toolchain`,
332 (value) => {
333 if (!toolchains.has(value)) {
334 throw new InvalidArgumentError(
335 `Invalid toolchain: ${value}. The following are allowed: ${Array.from(
336 toolchains,
337 ).join(', ')}`,
338 )
339 }
340 return value
341 },
342 )
343 }
344​
345 program
346 .option('--interactive', 'interactive mode', false)
347 .option('--tailwind', 'add Tailwind CSS', false)
348 .option<Array<string> | boolean>(
349 '--add-ons [...add-ons]',
350 'pick from a list of available add-ons (comma separated list)',
351 (value: string) => {
352 let addOns: Array<string> | boolean = !!value
353 if (typeof value === 'string') {
354 addOns = value.split(',').map((addon) => addon.trim())
355 }
356 return addOns
357 },
358 )
359 .option('--list-add-ons', 'list all available add-ons', false)
360 .option(
361 '--addon-details <addon-id>',
362 'show detailed information about a specific add-on',
363 )
364 .option('--no-git', 'do not create a git repository')
365 .option(
366 '--target-dir <path>',
367 'the target directory for the application root',
368 )
369 .option('--mcp', 'run the MCP server', false)
370 .option('--mcp-sse', 'run the MCP server in SSE mode', false)
371 .option('--ui', 'Add with the UI')
372 .option(
373 '--add-on-config <config>',
374 'JSON string with add-on configuration options',
375 )
376​
377 program.action(async (projectName: string, options: CliOptions) => {
378 if (options.listAddOns) {
379 const addOns = await getAllAddOns(
380 getFrameworkByName(options.framework || defaultFramework || 'React')!,
381 defaultMode ||
382 convertTemplateToMode(options.template || defaultTemplate),
383 )
384 let hasConfigurableAddOns = false
385 for (const addOn of addOns.filter((a) => !forcedAddOns.includes(a.id))) {
386 const hasOptions =
387 addOn.options && Object.keys(addOn.options).length > 0
388 const optionMarker = hasOptions ? '*' : ' '
389 if (hasOptions) hasConfigurableAddOns = true
390 console.log(
391 `${optionMarker} ${chalk.bold(addOn.id)}: ${addOn.description}`,
392 )
393 }
394 if (hasConfigurableAddOns) {
395 console.log('\n* = has configuration options')
396 }
397 } else if (options.addonDetails) {
398 const addOns = await getAllAddOns(
399 getFrameworkByName(options.framework || defaultFramework || 'React')!,
400 defaultMode ||
401 convertTemplateToMode(options.template || defaultTemplate),
402 )
403 const addOn = addOns.find((a) => a.id === options.addonDetails)
404 if (!addOn) {
405 console.error(`Add-on '${options.addonDetails}' not found`)
406 process.exit(1)
407 }
408​
409 console.log(
410 `${chalk.bold.cyan('Add-on Details:')} ${chalk.bold(addOn.name)}`,
411 )
412 console.log(`${chalk.bold('ID:')} ${addOn.id}`)
413 console.log(`${chalk.bold('Description:')} ${addOn.description}`)
414 console.log(`${chalk.bold('Type:')} ${addOn.type}`)
415 console.log(`${chalk.bold('Phase:')} ${addOn.phase}`)
416 console.log(`${chalk.bold('Supported Modes:')} ${addOn.modes.join(', ')}`)
417​
418 if (addOn.link) {
419 console.log(`${chalk.bold('Link:')} ${chalk.blue(addOn.link)}`)
420 }
421​
422 if (addOn.dependsOn && addOn.dependsOn.length > 0) {
423 console.log(
424 `${chalk.bold('Dependencies:')} ${addOn.dependsOn.join(', ')}`,
425 )
426 }
427​
428 if (addOn.options && Object.keys(addOn.options).length > 0) {
429 console.log(`\n${chalk.bold.yellow('Configuration Options:')}`)
430 for (const [optionName, option] of Object.entries(addOn.options)) {
431 if (option && typeof option === 'object' && 'type' in option) {
432 const opt = option as any
433 console.log(` ${chalk.bold(optionName)}:`)
434 console.log(` Label: ${opt.label}`)
435 if (opt.description) {
436 console.log(` Description: ${opt.description}`)
437 }
438 console.log(` Type: ${opt.type}`)
439 console.log(` Default: ${opt.default}`)
440 if (opt.type === 'select' && opt.options) {
441 console.log(` Available values:`)
442 for (const choice of opt.options) {
443 console.log(` - ${choice.value}: ${choice.label}`)
444 }
445 }
446 }
447 }
448 } else {
449 console.log(`\n${chalk.gray('No configuration options available')}`)
450 }
451​
452 if (addOn.routes && addOn.routes.length > 0) {
453 console.log(`\n${chalk.bold.green('Routes:')}`)
454 for (const route of addOn.routes) {
455 console.log(` ${chalk.bold(route.url)} (${route.name})`)
456 console.log(` File: ${route.path}`)
457 }
458 }
459 } else if (options.mcp || options.mcpSse) {
460 await runMCPServer(!!options.mcpSse, {
461 forcedMode: defaultMode,
462 forcedAddOns,
463 appName,
464 })
465 } else {
466 try {
467 const cliOptions = {
468 projectName,
469 ...options,
470 } as CliOptions
471​
472 cliOptions.framework = getFrameworkByName(
473 options.framework || defaultFramework || 'React',
474 )!.id
475​
476 if (defaultMode) {
477 cliOptions.template = defaultMode as TemplateOptions
478 }
479​
480 let finalOptions: Options | undefined
481 if (cliOptions.interactive) {
482 cliOptions.addOns = true
483 } else {
484 finalOptions = await normalizeOptions(
485 cliOptions,
486 defaultMode,
487 forcedAddOns,
488 { forcedDeployment },
489 )
490 }
491​
492 if (options.ui) {
493 const optionsFromCLI = await normalizeOptions(
494 cliOptions,
495 defaultMode,
496 forcedAddOns,
497 { disableNameCheck: true, forcedDeployment },
498 )
499 const options = {
500 ...createSerializedOptions(optionsFromCLI!),
501 projectName: 'my-app',
502 targetDir: resolve(process.cwd(), 'my-app'),
503 }
504 launchUI({
505 mode: 'setup',
506 options,
507 forcedRouterMode: defaultMode,
508 forcedAddOns,
509 environmentFactory: () => createUIEnvironment(appName, false),
510 webBase,
511 showDeploymentOptions,
512 })
513 return
514 }
515​
516 if (finalOptions) {
517 intro(`Creating a new ${appName} app in ${projectName}...`)
518 } else {
519 intro(`Let's configure your ${appName} application`)
520 finalOptions = await promptForCreateOptions(cliOptions, {
521 forcedMode: defaultMode,
522 forcedAddOns,
523 showDeploymentOptions,
524 })
525 }
526​
527 if (!finalOptions) {
528 throw new Error('No options were provided')
529 }
530​
531 // Determine target directory:
532 // 1. Use --target-dir if provided
533 // 2. Use targetDir from normalizeOptions if set (handles "." case)
534 // 3. If original projectName was ".", use current directory
535 // 4. Otherwise, use project name as subdirectory
536 if (options.targetDir) {
537 finalOptions.targetDir = options.targetDir
538 } else if (finalOptions.targetDir) {
539 // Keep the targetDir from normalizeOptions (handles "." case)
540 } else if (projectName === '.') {
541 finalOptions.targetDir = resolve(process.cwd())
542 } else {
543 finalOptions.targetDir = resolve(process.cwd(), finalOptions.projectName)
544 }
545​
546 await createApp(environment, finalOptions)
547 } catch (error) {
548 log.error(
549 error instanceof Error ? error.message : 'An unknown error occurred',
550 )
551 process.exit(1)
552 }
553 }
554 })
555​
556 program.parse()