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

edge-create-app.ts

685 lines20.7 KB

1import { createPackageJSON } from './edge-package-json.js'
2import { writePnpmWorkspace } from './pnpm-workspace.js'
3import { createTemplateFile } from './edge-template-file.js'
4import { formatCommand } from './utils.js'
5import { isBase64, isDemoFilePath } from './edge-file-helpers.js'
6import { basenamePath, joinPaths, normalizePath } from './edge-path.js'
7import { resolvePackageJSONLatest } from './npm-resolver.js'
8import { writeConfigFileToEnvironment } from './edge-config-file.js'
9import {
10 INTENT_PACKAGE,
11 detectPnpmVersion,
12 getPackageManagerExecuteCommand,
13 getPackageManagerInstallCommand,
14 getPackageManagerScriptCommand,
15 intentCommand,
16 packageManagerInstall,
17 translateExecuteCommand,
18 validatePackageManagerSupport,
19} from './package-manager.js'
20import { normalizeAndValidateBundlerOptions } from './build-tools.js'
21​
22import type { Environment, FileBundleHandler, Options } from './types.js'
23​
24function stripExamplesFromOptions(options: Options): Options {
25 const includeExamples =
26 options.projectPreset !== 'blank' && options.includeExamples !== false
27​
28 if (includeExamples) {
29 return options
30 }
31​
32 const chosenAddOns = options.chosenAddOns
33 .filter((addOn) => addOn.type !== 'example')
34 .map((addOn) => {
35 const filteredRoutes = (addOn.routes || []).filter(
36 (route) =>
37 !isDemoFilePath(route.path) &&
38 !(route.url && route.url.startsWith('/demo')),
39 )
40​
41 const filteredIntegrations = (addOn.integrations || []).filter(
42 (integration) => !isDemoFilePath(integration.path),
43 )
44​
45 return {
46 ...addOn,
47 routes: filteredRoutes,
48 integrations: filteredIntegrations,
49 getFiles: async () => {
50 const files = await addOn.getFiles()
51 return files.filter((file) => !isDemoFilePath(file))
52 },
53 getDeletedFiles: async () => {
54 const deletedFiles = await addOn.getDeletedFiles()
55 return deletedFiles.filter((file) => !isDemoFilePath(file))
56 },
57 }
58 })
59​
60 return {
61 ...options,
62 includeExamples: false,
63 chosenAddOns,
64 }
66​
67async function writeFiles(
68 environment: Environment,
69 options: Options,
70 context: { existingProject?: boolean } = {},
71) {
72 const workspaceWasPresent = environment.exists(
73 joinPaths(options.targetDir, 'pnpm-workspace.yaml'),
74 )
75 const templateFileFromContent = createTemplateFile(environment, options)
76​
77 async function writeFileBundle(bundle: FileBundleHandler) {
78 const files = await bundle.getFiles()
79​
80 for (const file of files) {
81 const contents = await bundle.getFileContents(file)
82​
83 if (isBase64(contents)) {
84 await environment.writeFileBase64(
85 joinPaths(options.targetDir, file),
86 contents,
87 )
88 } else {
89 await templateFileFromContent(file, contents)
90 }
91 }
92​
93 const deletedFiles = await bundle.getDeletedFiles()
94 for (const file of deletedFiles) {
95 await environment.deleteFile(joinPaths(options.targetDir, file))
96 }
97 }
98​
99 environment.startStep({
100 id: 'write-framework-files',
101 type: 'file',
102 message: 'Writing framework files...',
103 })
104 await writeFileBundle(options.framework)
105 environment.finishStep('write-framework-files', 'Framework files written')
106​
107 let wroteAddonFiles = false
108 for (const type of ['add-on', 'example', 'toolchain', 'deployment']) {
109 for (const phase of ['setup', 'add-on', 'example']) {
110 for (const addOn of options.chosenAddOns.filter(
111 (addOn) => addOn.phase === phase && addOn.type === type,
112 )) {
113 environment.startStep({
114 id: 'write-addon-files',
115 type: 'file',
116 message: `Writing ${addOn.name} files...`,
117 })
118 await writeFileBundle(addOn)
119 wroteAddonFiles = true
120 }
121 }
122 }
123 if (wroteAddonFiles) {
124 environment.finishStep('write-addon-files', 'Add-on files written')
125 }
126​
127 if (options.starter) {
128 environment.startStep({
129 id: 'write-starter-files',
130 type: 'file',
131 message: 'Writing starter files...',
132 })
133 await writeFileBundle(options.starter)
134 environment.finishStep('write-starter-files', 'Starter files written')
135 }
136​
137 environment.startStep({
138 id: 'write-package-json',
139 type: 'file',
140 message: 'Writing package.json...',
141 })
142 const packageJSON = await resolvePackageJSONLatest(createPackageJSON(options))
143 await writePnpmWorkspace(
144 environment,
145 joinPaths(options.targetDir, 'pnpm-workspace.yaml'),
146 options.packageManager,
147 packageJSON,
148 { ...context, workspaceWasPresent },
149 )
150 await environment.writeFile(
151 joinPaths(options.targetDir, './package.json'),
152 JSON.stringify(packageJSON, null, 2),
153 )
154 environment.finishStep('write-package-json', 'Package.json written')
155​
156 environment.startStep({
157 id: 'write-config-file',
158 type: 'file',
159 message: 'Writing config file...',
160 })
161 await writeConfigFileToEnvironment(environment, options)
162 environment.finishStep('write-config-file', 'Config file written')
164​
165async function runSpecialSteps(
166 environment: Environment,
167 options: Options,
168 specialSteps: Array<string>,
169) {
170 if (!specialSteps.length) {
171 return
172 }
173​
174 environment.startStep({
175 id: 'special-steps',
176 type: 'command',
177 message: 'Running special steps...',
178 })
179​
180 for (const step of specialSteps) {
181 if (step === 'rimraf-node-modules') {
182 await environment.rimraf(joinPaths(options.targetDir, 'node_modules'))
183 for (const lockFile of [
184 'package-lock.json',
185 'yarn.lock',
186 'pnpm-lock.yaml',
187 ]) {
188 const lockFilePath = joinPaths(options.targetDir, lockFile)
189 if (environment.exists(lockFilePath)) {
190 await environment.deleteFile(lockFilePath)
191 }
192 }
193 continue
194 }
195​
196 if (step === 'post-init-script') {
197 const packageJsonPath = joinPaths(options.targetDir, 'package.json')
198 if (!environment.exists(packageJsonPath)) {
199 environment.warn(
200 'Warning',
201 'No package.json found, skipping post-create-init script',
202 )
203 continue
204 }
205​
206 const packageJson = JSON.parse(await environment.readFile(packageJsonPath))
207 const postCreateInit = packageJson.scripts?.['post-create-init']
208 if (postCreateInit) {
209 const { command, args } = getPackageManagerScriptCommand(
210 options.packageManager,
211 ['post-create-init'],
212 )
213 await environment.execute(command, args, options.targetDir, {
214 inherit: true,
215 })
216 }
217 continue
218 }
219​
220 environment.error(`Special step ${step} not found`)
221 }
222​
223 environment.finishStep('special-steps', 'Special steps complete')
225​
226async function installShadcnComponents(
227 environment: Environment,
228 targetDir: string,
229 options: Options,
230) {
231 if (!options.chosenAddOns.find((a) => a.id === 'shadcn')) {
232 return
233 }
234​
235 const shadcnComponents = new Set<string>()
236 for (const addOn of options.chosenAddOns) {
237 if (addOn.shadcnComponents) {
238 for (const component of addOn.shadcnComponents) {
239 shadcnComponents.add(component)
240 }
241 }
242 }
243 if (options.starter?.shadcnComponents) {
244 for (const component of options.starter.shadcnComponents) {
245 shadcnComponents.add(component)
246 }
247 }
248​
249 if (shadcnComponents.size > 0) {
250 environment.startStep({
251 id: 'install-shadcn-components',
252 type: 'command',
253 message: `Installing shadcn components (${Array.from(shadcnComponents).join(', ')})...`,
254 })
255​
256 const { command, args } = getPackageManagerExecuteCommand(
257 options.packageManager,
258 'shadcn@latest',
259 ['add', '--silent', '--yes', ...Array.from(shadcnComponents)],
260 )
261 await environment.execute(command, args, normalizePath(targetDir))
262​
263 environment.finishStep(
264 'install-shadcn-components',
265 'Shadcn components installed',
266 )
267 }
269​
270async function setupIntent(
271 environment: Environment,
272 targetDir: string,
273 options: Options,
274) {
275 if (!options.intent) {
276 return false
277 }
278​
279 if (options.install === false) {
280 environment.startStep({
281 id: 'setup-intent',
282 type: 'info',
283 message: 'Skipping TanStack Intent setup...',
284 })
285 environment.finishStep(
286 'setup-intent',
287 'TanStack Intent setup skipped: dependencies not installed',
288 )
289 return false
290 }
291​
292 environment.startStep({
293 id: 'setup-intent',
294 type: 'command',
295 message: 'Setting up TanStack Intent skill discovery...',
296 })
297​
298 const { command, args } = getPackageManagerExecuteCommand(
299 options.packageManager,
300 INTENT_PACKAGE,
301 ['install'],
302 )
303 const result = await environment.execute(command, args, normalizePath(targetDir))
304 environment.finishStep(
305 'setup-intent',
306 result.failed ? 'TanStack Intent setup failed' : 'TanStack Intent configured',
307 )
308 return !result.failed
310​
311async function runCommandsAndInstallDependencies(
312 environment: Environment,
313 options: Options,
314 packageManagerVersion?: string,
315) {
316 const needsBuildApproval =
317 options.chosenAddOns.some((addOn) => addOn.command?.allowBuilds?.length) ||
318 options.starter?.command?.allowBuilds?.length
319 if (
320 options.packageManager === 'pnpm' &&
321 needsBuildApproval &&
322 packageManagerVersion === undefined
323 ) {
324 packageManagerVersion = await detectPnpmVersion(environment, options.targetDir)
325 }
326​
327 const s = environment.spinner()
328​
329 if (options.git) {
330 s.start('Initializing git repository...')
331 environment.startStep({
332 id: 'initialize-git-repository',
333 type: 'command',
334 message: 'Initializing git repository...',
335 })
336​
337 await environment.execute('git', ['init'], normalizePath(options.targetDir))
338​
339 environment.finishStep(
340 'initialize-git-repository',
341 'Initialized git repository',
342 )
343 s.stop('Initialized git repository')
344 }
345​
346 const specialSteps = new Set<string>()
347 for (const addOn of options.chosenAddOns) {
348 for (const step of addOn.createSpecialSteps || []) {
349 specialSteps.add(step)
350 }
351 }
352 if (specialSteps.size) {
353 await runSpecialSteps(environment, options, Array.from(specialSteps))
354 }
355​
356 if (options.install !== false) {
357 s.start(`Installing dependencies via ${options.packageManager}...`)
358 environment.startStep({
359 id: 'install-dependencies',
360 type: 'package-manager',
361 message: `Installing dependencies via ${options.packageManager}...`,
362 })
363 await packageManagerInstall(
364 environment,
365 options.targetDir,
366 options.packageManager,
367 )
368 environment.finishStep('install-dependencies', 'Installed dependencies')
369 s.stop('Installed dependencies')
370 } else {
371 s.start('Skipping dependency installation...')
372 environment.startStep({
373 id: 'skip-dependencies',
374 type: 'info',
375 message: 'Skipping dependency installation...',
376 })
377 environment.finishStep('skip-dependencies', 'Dependency installation skipped')
378 s.stop('Dependency installation skipped')
379 }
380​
381 const postInitSpecialSteps = new Set<string>()
382 for (const addOn of options.chosenAddOns) {
383 for (const step of addOn.postInitSpecialSteps || []) {
384 postInitSpecialSteps.add(step)
385 }
386 }
387 if (postInitSpecialSteps.size) {
388 await runSpecialSteps(
389 environment,
390 options,
391 Array.from(postInitSpecialSteps),
392 )
393 }
394​
395 for (const phase of ['setup', 'add-on', 'example']) {
396 for (const addOn of options.chosenAddOns.filter(
397 (addOn) =>
398 addOn.phase === phase && addOn.command && addOn.command.command,
399 )) {
400 s.start(`Running commands for ${addOn.name}...`)
401 const translated = translateExecuteCommand(options.packageManager, {
402 command: addOn.command!.command,
403 args: addOn.command!.args || [],
404 allowBuilds: addOn.command!.allowBuilds,
405 }, packageManagerVersion)
406 const cmd = formatCommand(translated)
407 environment.startStep({
408 id: 'run-commands',
409 type: 'command',
410 message: cmd,
411 })
412 await environment.execute(
413 translated.command,
414 translated.args,
415 options.targetDir,
416 { inherit: true },
417 )
418 environment.finishStep('run-commands', 'Setup commands complete')
419 s.stop(`${addOn.name} commands complete`)
420 }
421 }
422​
423 if (
424 options.starter &&
425 options.starter.command &&
426 options.starter.command.command
427 ) {
428 s.start(`Setting up starter ${options.starter.name}...`)
429 const starterTranslated = translateExecuteCommand(options.packageManager, {
430 command: options.starter.command.command,
431 args: options.starter.command.args || [],
432 allowBuilds: options.starter.command.allowBuilds,
433 }, packageManagerVersion)
434 const cmd = formatCommand(starterTranslated)
435 environment.startStep({
436 id: 'run-starter-command',
437 type: 'command',
438 message: cmd,
439 })
440​
441 await environment.execute(
442 starterTranslated.command,
443 starterTranslated.args,
444 options.targetDir,
445 { inherit: true },
446 )
447​
448 environment.finishStep('run-starter-command', 'Starter command complete')
449 s.stop(`${options.starter.name} commands complete`)
450 }
451​
452 await installShadcnComponents(environment, options.targetDir, options)
453 const intentConfigured = await setupIntent(environment, options.targetDir, options)
454​
455 if (shouldGenerateRoutes(options)) {
456 s.start('Generating route tree...')
457 const command = getPackageManagerScriptCommand(options.packageManager, [
458 'generate-routes',
459 ])
460 const cmd = formatCommand(command)
461 environment.startStep({
462 id: 'generate-routes',
463 type: 'command',
464 message: cmd,
465 })
466 await environment.execute(
467 command.command,
468 command.args,
469 options.targetDir,
470 {
471 inherit: true,
472 },
473 )
474 environment.finishStep('generate-routes', 'Route tree generated')
475 s.stop('Route tree generated')
476 }
477​
478 return intentConfigured
480​
481function shouldGenerateRoutes(options: Options) {
482 return (
483 options.install !== false &&
484 options.mode === 'file-router' &&
485 (options.framework.id === 'react' || options.framework.id === 'solid')
486 )
488​
489async function seedEnvValues(environment: Environment, options: Options) {
490 const envVarValues = options.envVarValues || {}
491 const entries = Object.entries(envVarValues)
492 if (entries.length === 0) return
493​
494 const envLocalPath = joinPaths(options.targetDir, '.env.local')
495 if (!environment.exists(envLocalPath)) {
496 return
497 }
498​
499 let envContents = await environment.readFile(envLocalPath)
500 for (const [key, value] of entries) {
501 const escapedValue = value.replace(/\n/g, '\\n')
502 const nextLine = `${key}=${escapedValue}`
503 const pattern = new RegExp(`^${key}=.*$`, 'm')
504​
505 if (pattern.test(envContents)) {
506 envContents = envContents.replace(pattern, nextLine)
507 } else {
508 envContents += `${envContents.endsWith('\n') ? '' : '\n'}${nextLine}\n`
509 }
510 }
511​
512 await environment.writeFile(envLocalPath, envContents)
514​
515async function writeEnvExample(environment: Environment, options: Options) {
516 const envExamplePath = joinPaths(options.targetDir, '.env.example')
517 const existing = environment.exists(envExamplePath)
518 ? await environment.readFile(envExamplePath)
519 : ''
520​
521 const declared = new Set<string>()
522 for (const match of existing.matchAll(/^([A-Z_][A-Z0-9_]*)=/gm)) {
523 declared.add(match[1])
524 }
525​
526 const sections: Array<string> = []
527 for (const addOn of options.chosenAddOns) {
528 const lines: Array<string> = []
529 for (const envVar of addOn.envVars || []) {
530 if (declared.has(envVar.name)) continue
531 declared.add(envVar.name)
532 if (envVar.description) {
533 const required = envVar.required ? ' (required)' : ''
534 lines.push(`# ${envVar.description}${required}`)
535 }
536 lines.push(`${envVar.name}=`)
537 }
538 if (lines.length > 0) {
539 sections.push(`# ${addOn.name}\n${lines.join('\n')}`)
540 }
541 }
542​
543 if (sections.length === 0) return
544​
545 const additions = sections.join('\n\n')
546 const newContent = existing
547 ? `${existing.trimEnd()}\n\n${additions}\n`
548 : `${additions}\n`
549​
550 await environment.writeFile(envExamplePath, newContent)
552​
553const SHIPPING_CATEGORIES = new Set(['auth', 'database', 'orm', 'deploy'])
554​
555function buildNextSteps(options: Options, intentConfigured: boolean): string {
556 const collectedEnv = new Set(Object.keys(options.envVarValues || {}))
557 const listedEnvVars = new Set<string>()
558 const envVarLines: Array<string> = []
559 const docLines: Array<string> = []
560​
561 for (const addOn of options.chosenAddOns) {
562 if (addOn.link && addOn.category && SHIPPING_CATEGORIES.has(addOn.category)) {
563 docLines.push(` - ${addOn.name} (${addOn.category}): ${addOn.link}`)
564 }
565​
566 for (const envVar of addOn.envVars || []) {
567 if (listedEnvVars.has(envVar.name)) continue
568 listedEnvVars.add(envVar.name)
569 const required = envVar.required ? ' (required)' : ''
570 const status = collectedEnv.has(envVar.name)
571 ? ' - already set from your input'
572 : ' - needs a value'
573 const desc = envVar.description ? ` - ${envVar.description}` : ''
574 envVarLines.push(` - ${envVar.name}${required}${desc}${status}`)
575 }
576 }
577​
578 const sections: Array<string> = []
579 if (envVarLines.length > 0) {
580 sections.push(
581 `Environment variables (review/fill in .env.local before deploying):\n${envVarLines.join('\n')}`,
582 )
583 }
584 if (docLines.length > 0) {
585 sections.push(`Docs for the integrations you picked:\n${docLines.join('\n')}`)
586 }
587 if (options.intent) {
588 if (options.install === false) {
589 const installCommand = formatCommand(
590 getPackageManagerInstallCommand(options.packageManager),
591 )
592 sections.push(
593 `TanStack Intent setup was skipped because dependency installation was skipped.\nInstall dependencies, then generate agent guidance:\n % ${installCommand}\n % ${intentCommand(options.packageManager, ['install', '--map'])}`,
594 )
595 } else if (intentConfigured) {
596 sections.push(
597 `Working with an AI agent? Your agent config (AGENTS.md / CLAUDE.md) was wired up by TanStack Intent\nso your agent can discover skills for the libraries you installed, on demand:\n - ${intentCommand(options.packageManager, ['list'])}\n - ${intentCommand(options.packageManager, ['load', '<package>#<skill>'])}\nTry asking your agent:\n - "migrate this Next.js page to TanStack Start"\n - "add a protected /dashboard route"\n - "show me how to use TanStack Router search params"`,
598 )
599 }
600 }
601​
602 return sections.length > 0 ? `\nNext steps:\n\n${sections.join('\n\n')}\n` : ''
604​
605function report(
606 environment: Environment,
607 options: Options,
608 intentConfigured: boolean,
609) {
610 const warnings: Array<string> = []
611 for (const addOn of options.chosenAddOns) {
612 if (addOn.warning) {
613 warnings.push(addOn.warning)
614 }
615 }
616​
617 if (warnings.length > 0) {
618 environment.warn('Warnings', warnings.join('\n'))
619 }
620​
621 const errors = [...environment.getErrors()]
622 if (options.intent && options.install !== false && !intentConfigured) {
623 const retryCommand = intentCommand(options.packageManager, ['install'])
624 if (!errors.some((error) => error.includes(retryCommand))) {
625 errors.push(`TanStack Intent setup failed. To retry, run ${retryCommand} in your project.`)
626 }
627 }
628 let errorStatement = ''
629 if (errors.length) {
630 errorStatement = `
631​
632Errors were encountered during the creation of your app:
633​
634${errors.join('\n')}`
635 }
636​
637 const targetDir = normalizePath(options.targetDir)
638 const isCurrentDirectory = targetDir === '.'
639 const locationMessage = isCurrentDirectory
640 ? `Your ${environment.appName} app is ready.`
641 : `Your ${environment.appName} app is ready in '${basenamePath(targetDir)}'.`
642 const cdInstruction = isCurrentDirectory
643 ? ''
644 : `% cd ${options.projectName}
646​
647 const nextSteps = buildNextSteps(options, intentConfigured)
648 const readmeDescription =
649 options.projectPreset === 'blank'
650 ? 'running, building, adding routes, and selected integrations.'
651 : 'testing, styling, adding routes, etc.'
652​
653 environment.outro(
654 `${locationMessage}
655​
656Use the following commands to start your app:
657${cdInstruction}% ${formatCommand(
658 getPackageManagerScriptCommand(options.packageManager, ['dev']),
659 )}
660${nextSteps}
661Please read the README.md file for information on ${readmeDescription}${errorStatement}`,
662 )
664​
665export async function createApp(
666 environment: Environment,
667 options: Options,
668 context: { existingProject?: boolean; packageManagerVersion?: string } = {},
669) {
670 validatePackageManagerSupport(options.packageManager, options.chosenAddOns)
671 const effectiveOptions = stripExamplesFromOptions(normalizeAndValidateBundlerOptions(options))
672​
673 environment.startRun()
674 await writeFiles(environment, effectiveOptions, context)
675 await seedEnvValues(environment, effectiveOptions)
676 await writeEnvExample(environment, effectiveOptions)
677 const intentConfigured = await runCommandsAndInstallDependencies(
678 environment,
679 effectiveOptions,
680 context.packageManagerVersion,
681 )
682 environment.finishRun()
683​
684 report(environment, effectiveOptions, intentConfigured)