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

add-to-app.ts

474 lines14.1 KB

1import { basename, resolve } from 'node:path'
2​
3import { CONFIG_FILE } from './constants.js'
4import { finalizeAddOns } from './add-ons.js'
5import { getFrameworkById } from './frameworks.js'
6import { createMemoryEnvironment } from './environment.js'
7import { createApp } from './create-app.js'
8import {
9 readConfigFileFromEnvironment,
10 writeConfigFileToEnvironment,
11} from './config-file.js'
12import { formatCommand } from './utils.js'
13import { detectPnpmVersion, packageManagerInstall } from './package-manager.js'
14import {
15 isBase64,
16 recursivelyGatherFilesFromEnvironment,
17} from './file-helpers.js'
18import { mergePackageJSON } from './package-json.js'
19import {
20 mergePnpmWorkspace,
21 pnpmBuildDependencies,
22 standalonePnpmNpmrc,
23} from './pnpm-workspace.js'
24import { runSpecialSteps } from './special-steps/index.js'
25import { loadStarter } from './custom-add-ons/starter.js'
26import { setupIntent } from './integrations/intent.js'
27​
28import type { AddOn, Environment, Options } from './types.js'
29import type { PersistedOptions } from './config-file.js'
30​
31const ENV_FILE_NAMES = new Set(['.env', '.env.local', '.env.example'])
32const ENV_VARIABLE_PATTERN = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/
33​
34function mergeEnvFileContents(existing: string, generated: string) {
35 const declaredVariables = new Set<string>()
36 for (const line of existing.split(/\r?\n/)) {
37 const match = line.match(ENV_VARIABLE_PATTERN)
38 if (match) {
39 declaredVariables.add(match[1])
40 }
41 }
42​
43 const additions: Array<string> = []
44 for (const block of generated.split(/\r?\n(?:[ \t]*\r?\n)+/)) {
45 const blockLines = block.split(/\r?\n/)
46 while (blockLines.at(-1) === '') {
47 blockLines.pop()
48 }
49 const lines: Array<string> = []
50 let addedVariableCount = 0
51 for (const line of blockLines) {
52 const match = line.match(ENV_VARIABLE_PATTERN)
53 if (!match) {
54 lines.push(line)
55 continue
56 }
57 if (declaredVariables.has(match[1])) {
58 continue
59 }
60​
61 declaredVariables.add(match[1])
62 addedVariableCount++
63 lines.push(line)
64 }
65​
66 if (addedVariableCount > 0) {
67 additions.push(lines.join('\n'))
68 }
69 }
70​
71 if (additions.length === 0) {
72 return existing
73 }
74​
75 const separator = existing.length
76 ? existing.endsWith('\n\n')
77 ? ''
78 : existing.endsWith('\n')
79 ? '\n'
80 : '\n\n'
81 : ''
82 const trailingNewline = generated.endsWith('\n') ? '\n' : ''
83 return `${existing}${separator}${additions.join('\n\n')}${trailingNewline}`
85​
86export async function hasPendingGitChanges(
87 environment: Environment,
88 cwd: string,
89) {
90 const { stdout } = await environment.execute(
91 'git',
92 ['status', '--porcelain'],
93 cwd,
94 )
95 return stdout.length > 0
97​
98async function createOptions(
99 json: PersistedOptions,
100 addOns: Array<string>,
101 targetDir: string,
102): Promise<Options> {
103 const framework = getFrameworkById(json.framework)
104 const bundler = json.bundler ?? 'vite'
105​
106 const starter = json.starter ? await loadStarter(json.starter) : undefined
107 const chosenAddOns = await finalizeAddOns(framework!, json.mode!, [
108 ...json.chosenAddOns,
109 ...addOns,
110 ], bundler)
111​
112 if (bundler === 'rsbuild') {
113 assertNoExclusiveAddOnConflicts(chosenAddOns)
114 }
115​
116 return {
117 ...json,
118 framework,
119 bundler,
120 tailwind:
121 (json.tailwind ?? true) ||
122 chosenAddOns.some((addOn) => addOn.tailwind === true),
123 addOns: true,
124 chosenAddOns,
125 targetDir,
126 starter,
127 intent: json.intent ?? false,
128 } as Options
130​
131function assertNoExclusiveAddOnConflicts(addOns: Array<AddOn>) {
132 const selectedByExclusiveGroup = new Map<string, AddOn>()
133​
134 for (const addOn of addOns) {
135 for (const exclusive of addOn.exclusive ?? []) {
136 const selected = selectedByExclusiveGroup.get(exclusive)
137 if (selected && selected.id !== addOn.id) {
138 throw new Error(
139 `Cannot combine ${selected.name} and ${addOn.name}. Add-ons in the "${exclusive}" group are mutually exclusive.`,
140 )
141 }
142 selectedByExclusiveGroup.set(exclusive, addOn)
143 }
144 }
146​
147async function runCreateApp(options: Required<Options>, packageManagerVersion?: string) {
148 const { environment, output } = createMemoryEnvironment(options.targetDir)
149 await createApp(environment, options, { existingProject: true, packageManagerVersion })
150 return output
152​
153export async function getCurrentConfiguration(
154 environment: Environment,
155 cwd: string,
156) {
157 const persistedOptions = await readConfigFileFromEnvironment(environment, cwd)
158 if (!persistedOptions) {
159 environment.error(
160 'There is no .cta.json file in your project.',
161 'This is probably because this was created with an older version of create-tsrouter-app.',
162 )
163 return undefined
164 }
165​
166 return persistedOptions
168​
169export async function writeFiles(
170 environment: Environment,
171 cwd: string,
172 output: {
173 files: Record<string, string>
174 deletedFiles: Array<string>
175 },
176 forced: boolean,
177) {
178 const toRelativePath = (filePath: string) => {
179 const normalizedFilePath = filePath.replace(/\\/g, '/')
180 const normalizedCwd = cwd.replace(/\\/g, '/')
181 const cwdWithoutDrive = normalizedCwd.replace(/^[a-zA-Z]:/, '')
182 const cwdWithoutDriveNoLeading = cwdWithoutDrive.replace(/^\/+/, '')
183​
184 if (normalizedFilePath === normalizedCwd) {
185 return ''
186 }
187 if (normalizedFilePath.startsWith(`${normalizedCwd}/`)) {
188 return normalizedFilePath.slice(normalizedCwd.length + 1)
189 }
190 if (normalizedFilePath === cwdWithoutDrive) {
191 return ''
192 }
193 if (normalizedFilePath.startsWith(`${cwdWithoutDrive}/`)) {
194 return normalizedFilePath.slice(cwdWithoutDrive.length + 1)
195 }
196 if (normalizedFilePath === cwdWithoutDriveNoLeading) {
197 return ''
198 }
199 if (normalizedFilePath.startsWith(`${cwdWithoutDriveNoLeading}/`)) {
200 return normalizedFilePath.slice(cwdWithoutDriveNoLeading.length + 1)
201 }
202​
203 return normalizedFilePath.replace(/^\/+/, '')
204 }
205​
206 const relativeOutputFiles = Object.keys(output.files).reduce<
207 Record<string, string>
208 >((acc, filePath) => {
209 acc[toRelativePath(filePath)] = output.files[filePath]
210 return acc
211 }, {})
212​
213 const currentFiles = await recursivelyGatherFilesFromEnvironment(
214 environment,
215 cwd,
216 false,
217 )
218​
219 // Ignored files still need merge and overwrite protection when targeted.
220 const outputTargets = new Set(Object.keys(relativeOutputFiles))
221 if (Object.prototype.hasOwnProperty.call(relativeOutputFiles, 'pnpm-workspace.yaml')) {
222 outputTargets.add('.npmrc')
223 }
224 for (const relativeFile of outputTargets) {
225 const target = resolve(cwd, relativeFile)
226 if (
227 !Object.prototype.hasOwnProperty.call(currentFiles, relativeFile) &&
228 environment.exists(target) &&
229 !environment.isDirectory(target)
230 ) {
231 currentFiles[relativeFile] = await environment.readFile(target)
232 }
233 }
234​
235 for (const [relativeFile, generatedContents] of Object.entries(
236 relativeOutputFiles,
237 )) {
238 if (relativeFile === 'pnpm-workspace.yaml') {
239 const generatedPackage = relativeOutputFiles['package.json']
240 if (generatedPackage) {
241 const currentPackage = currentFiles['package.json'] ? JSON.parse(currentFiles['package.json']) : {}
242 const mergedPackage = mergePackageJSON(currentPackage, JSON.parse(generatedPackage))
243 relativeOutputFiles[relativeFile] = await mergePnpmWorkspace(currentFiles[relativeFile] ?? generatedContents, pnpmBuildDependencies(mergedPackage), pnpmBuildDependencies(currentPackage))
244 const npmrc = await standalonePnpmNpmrc(
245 currentFiles[relativeFile],
246 relativeOutputFiles[relativeFile],
247 relativeOutputFiles['.npmrc'] ?? currentFiles['.npmrc'],
248 )
249 if (npmrc !== undefined) relativeOutputFiles['.npmrc'] = npmrc
250 }
251 }
252 if (
253 ENV_FILE_NAMES.has(basename(relativeFile)) &&
254 relativeFile in currentFiles
255 ) {
256 relativeOutputFiles[relativeFile] = mergeEnvFileContents(
257 currentFiles[relativeFile],
258 generatedContents,
259 )
260 }
261 }
262​
263 const overwrittenFiles: Array<string> = []
264 const changedFiles: Array<string> = []
265 for (const relativeFile of Object.keys(relativeOutputFiles)) {
266 if (Object.prototype.hasOwnProperty.call(currentFiles, relativeFile)) {
267 if (currentFiles[relativeFile] !== relativeOutputFiles[relativeFile]) {
268 overwrittenFiles.push(relativeFile)
269 }
270 } else {
271 changedFiles.push(relativeFile)
272 }
273 }
274​
275 const deletedFiles = output.deletedFiles
276 .map(toRelativePath)
277 .filter((file) => environment.exists(resolve(cwd, file)))
278​
279 if (!forced && (overwrittenFiles.length || deletedFiles.length)) {
280 environment.warn(
281 'The following files will be changed or deleted',
282 [...overwrittenFiles, ...deletedFiles].join('\n'),
283 )
284 const shouldContinue = await environment.confirm('Do you want to continue?')
285 if (!shouldContinue) {
286 throw new Error('User cancelled')
287 }
288 }
289​
290 for (const relativeFilePath of deletedFiles) {
291 await environment.deleteFile(resolve(cwd, relativeFilePath))
292 }
293​
294 environment.startStep({
295 id: 'write-files',
296 type: 'file',
297 message: 'Writing add-on files...',
298 })
299​
300 for (const file of [...changedFiles, ...overwrittenFiles]) {
301 const fName = basename(file)
302 const contents = relativeOutputFiles[file]
303 if (fName === 'package.json') {
304 const currentJson = JSON.parse(
305 await environment.readFile(resolve(cwd, file)),
306 )
307 const newJSON = mergePackageJSON(currentJson, JSON.parse(contents))
308 await environment.writeFile(
309 resolve(cwd, file),
310 JSON.stringify(newJSON, null, 2),
311 )
312 } else if (fName !== CONFIG_FILE) {
313 if (isBase64(contents)) {
314 await environment.writeFileBase64(resolve(cwd, file), contents)
315 } else {
316 await environment.writeFile(resolve(cwd, file), contents)
317 }
318 }
319 }
320​
321 environment.finishStep('write-files', 'Add-on files written')
323​
324export async function runNewCommands(
325 environment: Environment,
326 originalOptions: PersistedOptions,
327 cwd: string,
328 output: {
329 commands: Array<{
330 command: string
331 args: Array<string>
332 }>
333 },
334 packageManagerVersion?: string,
335) {
336 const originalOutput = await runCreateApp({
337 ...(await createOptions(originalOptions, [], cwd)),
338 } as Required<Options>, packageManagerVersion)
339​
340 const originalCommands = new Set(
341 originalOutput.commands.map((c) => [c.command, ...c.args].join(' ')),
342 )
343​
344 for (const command of output.commands) {
345 const commandString = [command.command, ...command.args].join(' ')
346 if (!originalCommands.has(commandString)) {
347 environment.startStep({
348 id: 'run-commands',
349 type: 'command',
350 message: `Running ${formatCommand({ command: command.command, args: command.args })}...`,
351 })
352 await environment.execute(command.command, command.args, cwd, {
353 inherit: true,
354 })
355 environment.finishStep('run-commands', 'Setup commands complete')
356 }
357 }
359​
360export async function addToApp(
361 environment: Environment,
362 addOns: Array<string>,
363 cwd: string,
364 options?: {
365 forced?: boolean
366 intent?: boolean
367 },
368) {
369 const persistedOptions = await getCurrentConfiguration(environment, cwd)
370 if (!persistedOptions) {
371 return
372 }
373​
374 if (!options?.forced && (await hasPendingGitChanges(environment, cwd))) {
375 environment.error(
376 'You have pending git changes.',
377 'Please commit or stash them before adding add-ons.',
378 )
379 return
380 }
381​
382 environment.intro(`Adding ${addOns.join(', ')} to the project...`)
383 environment.startStep({
384 id: 'processing-new-app-setup',
385 type: 'file',
386 message: 'Processing new app setup...',
387 })
388​
389 const newOptions = await createOptions(persistedOptions, addOns, cwd)
390 const needsBuildApproval = newOptions.chosenAddOns.some((addOn) => addOn.command?.allowBuilds?.length) || newOptions.starter?.command?.allowBuilds?.length
391 const packageManagerVersion = newOptions.packageManager === 'pnpm' && needsBuildApproval
392 ? await detectPnpmVersion(environment, cwd)
393 : undefined
394​
395 const output = await runCreateApp({
396 ...newOptions,
397 targetDir: cwd,
398 } as Required<Options>, packageManagerVersion)
399​
400 await writeFiles(environment, cwd, output, !!options?.forced)
401​
402 environment.finishStep(
403 'processing-new-app-setup',
404 'Application files written',
405 )
406​
407 // Run any special steps for the new add-ons
408​
409 const specialSteps = new Set<string>([])
410 for (const addOn of newOptions.chosenAddOns) {
411 for (const step of addOn.addOnSpecialSteps || []) {
412 if (addOns.includes(addOn.id)) {
413 specialSteps.add(step)
414 }
415 }
416 }
417 if (specialSteps.size) {
418 await runSpecialSteps(environment, newOptions, Array.from(specialSteps))
419 }
420​
421 // Install dependencies
422​
423 environment.startStep({
424 id: 'install-dependencies',
425 type: 'package-manager',
426 message: `Installing dependencies via ${newOptions.packageManager}...`,
427 })
428 const s = environment.spinner()
429 s.start(`Installing dependencies via ${newOptions.packageManager}...`)
430 await packageManagerInstall(
431 environment,
432 newOptions.targetDir,
433 newOptions.packageManager,
434 undefined,
435 { updateLockfile: true },
436 )
437 s.stop(`Installed dependencies`)
438 environment.finishStep('install-dependencies', 'Dependencies installed')
439​
440 // Run any post-init special steps for the new add-ons
441 const postInitSpecialSteps = new Set<string>([])
442 for (const addOn of newOptions.chosenAddOns) {
443 for (const step of addOn.postInitSpecialSteps || []) {
444 if (addOns.includes(addOn.id)) {
445 postInitSpecialSteps.add(step)
446 }
447 }
448 }
449 if (postInitSpecialSteps.size) {
450 await runSpecialSteps(
451 environment,
452 newOptions,
453 Array.from(postInitSpecialSteps),
454 )
455 }
456​
457 // Handle new commands
458​
459 await runNewCommands(environment, persistedOptions, cwd, output, packageManagerVersion)
460​
461 const intent = options?.intent ?? persistedOptions.intent ?? true
462 newOptions.intent = intent
463 await setupIntent(environment, cwd, newOptions)
464​
465 environment.startStep({
466 id: 'write-config-file',
467 type: 'file',
468 message: 'Writing config file...',
469 })
470 writeConfigFileToEnvironment(environment, newOptions)
471 environment.finishStep('write-config-file', 'Config file written')
472​
473 environment.outro(`Add-ons ${addOns.join(', ')} added!`)