Open History to see the last commit
1import { resolve } from 'node:path'
2
3import {
4 createApp,
5 createDefaultEnvironment,
6 createMemoryEnvironment,
7 finalizeAddOns,
8 getFrameworkById,
9 loadStarter,
10} from '@tanstack/cta-engine'
11
12import { TMP_TARGET_DIR } from '../constants.js'
13
14import { cleanUpFileArray, cleanUpFiles } from './file-helpers.js'
15import { getApplicationMode, getProjectPath } from './server-environment.js'
16
17import type {
18 Environment,
19 Options,
20 SerializedOptions,
21 Starter,
22} from '@tanstack/cta-engine'
23
24import type { Response } from 'express'
25
26export async function createAppWrapper(
27 projectOptions: SerializedOptions,
28 opts: {
29 dryRun?: boolean
30 response?: Response
31 environmentFactory?: () => Environment
32 },
33) {
34 const framework = getFrameworkById(projectOptions.framework)!
35 if (!framework) {
36 throw new Error(`Framework ${projectOptions.framework} not found`)
37 }
38
39 let starter: Starter | undefined
40 const addOns: Array<string> = [...projectOptions.chosenAddOns]
41 if (projectOptions.starter) {
42 starter = await loadStarter(projectOptions.starter)
43 if (starter)
44 for (const addOn of starter.dependsOn ?? []) {
45 addOns.push(addOn)
46 }
47 }
48 const chosenAddOns = await finalizeAddOns(
49 framework,
50 projectOptions.mode,
51 addOns,
52 )
53
54 const projectPath = getProjectPath()
55 const targetDir = opts.dryRun
56 ? TMP_TARGET_DIR
57 : getApplicationMode() === 'add'
58 ? projectOptions.targetDir
59 : resolve(projectPath, projectOptions.projectName)
60
61 const options: Options = {
62 ...projectOptions,
63 targetDir,
64 starter,
65 framework,
66 chosenAddOns,
67 }
68
69 function createEnvironment() {
70 if (opts.dryRun) {
71 return createMemoryEnvironment(targetDir)
72 }
73 return {
74 environment: opts.environmentFactory?.() ?? createDefaultEnvironment(),
75 output: { files: {}, deletedFiles: [], commands: [] },
76 }
77 }
78
79 const { environment, output } = createEnvironment()
80
81 if (opts.response) {
82 opts.response.writeHead(200, {
83 'Content-Type': 'text/plain',
84 'Transfer-Encoding': 'chunked',
85 })
86
87 environment.startStep = ({ id, type, message }) => {
88 opts.response!.write(
89 JSON.stringify({
90 msgType: 'start',
91 id,
92 type,
93 message,
94 }) + '\n',
95 )
96 }
97 environment.finishStep = (id, message) => {
98 opts.response!.write(
99 JSON.stringify({
100 msgType: 'finish',
101 id,
102 message,
103 }) + '\n',
104 )
105 }
106
107 await createApp(environment, options)
108 opts.response.end()
109 } else {
110 await createApp(environment, options)
111
112 output.files = cleanUpFiles(output.files, targetDir)
113 output.deletedFiles = cleanUpFileArray(output.deletedFiles, targetDir)
114
115 return output
116 }
117}