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

index.ts

429 lines12.6 KB

1import { dirname, resolve } from 'node:path'
2import { fileURLToPath } from 'node:url'
3import express from 'express'
4import cors from 'cors'
5import chalk from 'chalk'
6import multer from 'multer'
7​
8import {
9 AddOnCompiledSchema,
10 StarterCompiledSchema,
11 handleSpecialURL,
12} from '@tanstack/cta-engine'
13​
14import { ai, maxIterations, toStreamResponse } from '@tanstack/ai'
15import { openaiText, openaiTranscription, openaiTTS } from '@tanstack/ai-openai'
16​
17import { selectAddOnsToolDef, unselectAddOnsToolDef } from './ai-tools.js'
18​
19import { addToAppWrapper } from './engine-handling/add-to-app-wrapper.js'
20import { createAppWrapper } from './engine-handling/create-app-wrapper.js'
21import { generateInitialPayload } from './engine-handling/generate-initial-payload.js'
22import { setServerEnvironment } from './engine-handling/server-environment.js'
23​
24import type { ServerEnvironment } from './engine-handling/server-environment.js'
25import type { Environment } from '@tanstack/cta-engine'
26​
27export function launchUI(
28 options: Partial<ServerEnvironment> & {
29 port?: number
30 environmentFactory?: () => Environment
31 webBase?: string
32 showDeploymentOptions?: boolean
33 },
34) {
35 const { port: requestedPort, webBase, ...rest } = options
36 setServerEnvironment(rest)
37​
38 const app = express()
39​
40 app.use(cors())
41 app.use(express.json())
42 app.use(express.urlencoded({ extended: true }))
43​
44 // Multer for file uploads (audio transcription)
45 const upload = multer({ storage: multer.memoryStorage() })
46​
47 // Add headers required for WebContainer (SharedArrayBuffer support)
48 app.use((req, res, next) => {
49 res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
50 res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
51 next()
52 })
53​
54 const packagePath = resolve(dirname(fileURLToPath(import.meta.url)), '..')
55​
56 const launchUI = !process.env.CTA_DISABLE_UI
57 if (launchUI) {
58 app.use(express.static(webBase || resolve(packagePath, 'dist')))
59 }
60​
61 app.post('/api/add-to-app', async (req, res) => {
62 await addToAppWrapper(req.body.addOns, {
63 response: res,
64 environmentFactory: options.environmentFactory,
65 })
66 })
67​
68 app.post('/api/create-app', async (req, res) => {
69 await createAppWrapper(req.body.options, {
70 response: res,
71 environmentFactory: options.environmentFactory,
72 })
73 })
74​
75 app.post('/api/dry-run-add-to-app', async (req, res) => {
76 try {
77 res.send(
78 await addToAppWrapper(req.body.addOns, {
79 dryRun: true,
80 environmentFactory: options.environmentFactory,
81 }),
82 )
83 } catch {
84 res.send({
85 files: {},
86 commands: [],
87 deletedFiles: [],
88 })
89 }
90 })
91​
92 app.post('/api/dry-run-create-app', async (req, res) => {
93 try {
94 res.send(
95 await createAppWrapper(req.body.options, {
96 dryRun: true,
97 environmentFactory: options.environmentFactory,
98 }),
99 )
100 } catch {
101 res.send({
102 files: {},
103 commands: [],
104 deletedFiles: [],
105 })
106 }
107 })
108​
109 app.get('/api/initial-payload', async (_req, res) => {
110 res.send(await generateInitialPayload())
111 })
112​
113 app.get('/api/load-remote-add-on', async (req, res) => {
114 const { url } = req.query
115 if (!url) {
116 res.status(400).send('URL is required')
117 return
118 }
119 try {
120 const fixedUrl = handleSpecialURL(url as string)
121 const response = await fetch(fixedUrl)
122 const data = await response.json()
123 const parsed = AddOnCompiledSchema.safeParse(data)
124 if (!parsed.success) {
125 res.status(400).json({ error: 'Invalid add-on data' })
126 } else {
127 res.json({
128 id: fixedUrl,
129 name: parsed.data.name,
130 description: parsed.data.description,
131 version: parsed.data.version,
132 author: parsed.data.author,
133 license: parsed.data.license,
134 link: parsed.data.link,
135 smallLogo: parsed.data.smallLogo,
136 logo: parsed.data.logo,
137 type: parsed.data.type,
138 modes: parsed.data.modes,
139 })
140 }
141 } catch {
142 res.status(500).send('Failed to load add-on')
143 }
144 })
145​
146 app.get('/api/load-starter', async (req, res) => {
147 const { url } = req.query
148 if (!url) {
149 res.status(400).send('URL is required')
150 return
151 }
152 try {
153 const fixedUrl = handleSpecialURL(url as string)
154 const response = await fetch(fixedUrl)
155 const data = await response.json()
156 const parsed = StarterCompiledSchema.safeParse(data)
157 if (!parsed.success) {
158 res.status(400).json({ error: 'Invalid starter data' })
159 } else {
160 res.json({
161 url: fixedUrl,
162 id: parsed.data.id,
163 name: parsed.data.name,
164 description: parsed.data.description,
165 version: parsed.data.version,
166 author: parsed.data.author,
167 license: parsed.data.license,
168 dependsOn: parsed.data.dependsOn,
169 mode: parsed.data.mode,
170 typescript: parsed.data.typescript,
171 tailwind: parsed.data.tailwind,
172 banner: parsed.data.banner
173 ? fixedUrl.replace('starter.json', parsed.data.banner)
174 : undefined,
175 })
176 }
177 } catch {
178 res.status(500).send('Failed to load starter')
179 }
180 })
181​
182 app.post('/api/shutdown', (_req, res) => {
183 setTimeout(() => {
184 process.exit(0)
185 }, 50)
186 res.send({ shutdown: true })
187 })
188​
189 // AI Chat endpoint - only available if OPENAI_API_KEY is set
190 app.get('/api/ai-enabled', (_req, res) => {
191 const hasKey = !!process.env.OPENAI_API_KEY
192 const keyPreview = process.env.OPENAI_API_KEY
193 ? `${process.env.OPENAI_API_KEY.slice(0, 7)}...${process.env.OPENAI_API_KEY.slice(-4)}`
194 : 'not set'
195 console.log(
196 `[AI] Checking if AI is enabled: ${hasKey} (key: ${keyPreview})`,
197 )
198 res.json({ enabled: hasKey })
199 })
200​
201 // Transcription endpoint - convert audio to text
202 app.post('/api/transcription', upload.single('audio'), async (req, res) => {
203 if (!process.env.OPENAI_API_KEY) {
204 res.status(403).json({ error: 'AI features are not available' })
205 return
206 }
207​
208 try {
209 const audioFile = req.file
210 const model = (req.body.model as string) || 'whisper-1'
211 const language = req.body.language as string | undefined
212​
213 if (!audioFile) {
214 res.status(400).json({ error: 'Audio file is required' })
215 return
216 }
217​
218 console.log('[AI] Transcription request received, model:', model)
219​
220 // Create a File object from the buffer
221 const file = new File(
222 [audioFile.buffer],
223 audioFile.originalname || 'audio.webm',
224 {
225 type: audioFile.mimetype || 'audio/webm',
226 },
227 )
228​
229 const adapter = openaiTranscription()
230 const result = (await ai({
231 adapter: adapter as any,
232 model: model as any,
233 audio: file,
234 language: language || undefined,
235 responseFormat: 'verbose_json',
236 })) as any
237​
238 console.log(
239 '[AI] Transcription complete:',
240 result.text?.slice(0, 50) + '...',
241 )
242​
243 res.json({
244 id: result.id,
245 model: result.model,
246 text: result.text,
247 language: result.language,
248 duration: result.duration,
249 segments: result.segments,
250 words: result.words,
251 })
252 } catch (error: any) {
253 console.error('[AI] Transcription error:', error?.message)
254 res.status(500).json({ error: error.message || 'Transcription failed' })
255 }
256 })
257​
258 // Text-to-Speech endpoint - convert text to audio
259 app.post('/api/tts', async (req, res) => {
260 if (!process.env.OPENAI_API_KEY) {
261 res.status(403).json({ error: 'AI features are not available' })
262 return
263 }
264​
265 try {
266 const {
267 text,
268 voice = 'nova',
269 model = 'tts-1',
270 format = 'mp3',
271 speed = 1.0,
272 } = req.body
273​
274 if (!text || text.trim().length === 0) {
275 res.status(400).json({ error: 'Text is required' })
276 return
277 }
278​
279 console.log('[AI] TTS request received, voice:', voice, 'model:', model)
280​
281 const adapter = openaiTTS()
282 const result = (await ai({
283 adapter: adapter as any,
284 model: model as any,
285 text,
286 voice,
287 format,
288 speed,
289 })) as any
290​
291 console.log('[AI] TTS complete, format:', result.format)
292​
293 res.json({
294 id: result.id,
295 model: result.model,
296 audio: result.audio,
297 format: result.format,
298 contentType: result.contentType,
299 duration: result.duration,
300 })
301 } catch (error: any) {
302 console.error('[AI] TTS error:', error?.message)
303 res.status(500).json({ error: error.message || 'TTS failed' })
304 }
305 })
306​
307 app.post('/api/ai-chat', (req, res) => {
308 if (!process.env.OPENAI_API_KEY) {
309 res.status(403).json({ error: 'AI chat is not available' })
310 return
311 }
312​
313 const abortController = new AbortController()
314​
315 try {
316 const { messages, addOns, data } = req.body
317​
318 // Get all add-ons from request (for system prompt)
319 const allAddOns = addOns || data?.addOns || []
320 console.log(
321 '[AI Chat] Request received, add-ons in prompt:',
322 allAddOns.length,
323 )
324​
325 // Build add-ons reference section for system prompt
326 let addOnsReference = ''
327 if (allAddOns.length > 0) {
328 addOnsReference = `
329​
330## AVAILABLE ADD-ONS
331​
332${allAddOns
333 .map(
334 (a: any) => `### ${a.name} (id: \`${a.id}\`)
335- **Type**: ${a.type}
336- **Description**: ${a.aiDescription || a.description}`,
337 )
338 .join('\n\n')}`
339 }
340​
341 const SYSTEM_PROMPT = `You are a helpful AI assistant for TanStack Create App, a tool that helps developers scaffold new applications with various add-ons and configurations.
342​
343Your role is to help users configure their application by selecting the right add-ons based on their requirements. You have access to the following tools:
344​
3451. **selectAddOns** - Select/enable add-ons by their IDs
3462. **unselectAddOns** - Unselect/disable add-ons by their IDs
347​
348WORKFLOW:
3491. Review the AVAILABLE ADD-ONS section below to understand what's available
3502. Based on the user's requirements, suggest appropriate add-ons
3513. When the user confirms, use selectAddOns or unselectAddOns to make changes
3524. The tools will report which add-ons were successfully changed
353​
354IMPORTANT:
355- Be helpful and explain the purpose of each add-on you recommend
356- If an add-on can't be selected (not available or already selected), the tool will let you know
357- Be concise but friendly in your responses
358​
359Common add-on categories:
360- **Toolchain**: Build tools and development setup (e.g., Biome, ESLint)
361- **Add-on**: Feature add-ons like authentication, API integrations, state management
362- **Deployment**: Deployment adapters for various platforms (e.g., Vercel, Netlify, Cloudflare)
363- **Example**: Example code and templates${addOnsReference}`
364​
365 console.log('[AI Chat] System prompt:\n', SYSTEM_PROMPT)
366​
367 const stream = ai({
368 adapter: openaiText(),
369 model: 'gpt-4o',
370 tools: [selectAddOnsToolDef, unselectAddOnsToolDef],
371 systemPrompts: [SYSTEM_PROMPT],
372 agentLoopStrategy: maxIterations(10),
373 messages,
374 abortController,
375 })
376​
377 // Handle the stream response
378 const streamResponse = toStreamResponse(stream as AsyncIterable<any>, {
379 abortController,
380 })
381​
382 // Set headers from the stream response
383 res.setHeader('Content-Type', 'text/event-stream')
384 res.setHeader('Cache-Control', 'no-cache')
385 res.setHeader('Connection', 'keep-alive')
386​
387 // Pipe the stream body to the response
388 if (streamResponse.body) {
389 const reader = streamResponse.body.getReader()
390 const pump = async () => {
391 try {
392 while (true) {
393 const { done, value } = await reader.read()
394 if (done) {
395 res.end()
396 break
397 }
398 res.write(value)
399 }
400 } catch (error: any) {
401 if (error.name !== 'AbortError') {
402 console.error('[AI Chat] Stream error:', error?.message)
403 }
404 res.end()
405 }
406 }
407 pump()
408 } else {
409 res.status(500).json({ error: 'Failed to create stream' })
410 }
411 } catch (error: any) {
412 console.error('[AI Chat] Error:', error?.message)
413 if (error.name === 'AbortError' || abortController.signal.aborted) {
414 res.status(499).end()
415 return
416 }
417 res.status(500).json({ error: error.message || 'An error occurred' })
418 }
419 })
420​
421 const port = requestedPort || process.env.PORT || 8080
422 app.listen(port, () => {
423 console.log(
424 `🔥 ${chalk.blueBright(`Create TanStack ${launchUI ? 'App' : 'API'}`)} is running on ${chalk.underline(
425 `http://localhost:${port}`,
426 )}`,
427 )
428 })