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

environment.ts

220 lines6.7 KB

1import {
2 appendFile,
3 copyFile,
4 mkdir,
5 readFile,
6 readdir,
7 unlink,
8 writeFile,
9} from 'node:fs/promises'
10import { existsSync, statSync } from 'node:fs'
11import { dirname, resolve } from 'node:path'
12import { execa } from 'execa'
13import { rimraf } from 'rimraf'
14​
15import { createMemoryEnvironment as createEdgeMemoryEnvironment } from './edge-environment.js'
16import { getBinaryFile } from './file-helpers.js'
17​
18import type { Environment } from './types.js'
19​
20export type { MemoryEnvironmentOutput } from './edge-environment.js'
21​
22export function createDefaultEnvironment(
23 cancelSignal?: AbortSignal,
24): Environment {
25 let errors: Array<string> = []
26 return {
27 startRun: () => {
28 errors = []
29 },
30 finishRun: () => {},
31 getErrors: () => errors,
32​
33 appendFile: async (path: string, contents: string) => {
34 await mkdir(dirname(path), { recursive: true })
35 return appendFile(path, contents)
36 },
37 copyFile: async (from: string, to: string) => {
38 await mkdir(dirname(to), { recursive: true })
39 return copyFile(from, to)
40 },
41 writeFile: async (path: string, contents: string) => {
42 await mkdir(dirname(path), { recursive: true })
43 return writeFile(path, contents)
44 },
45 writeFileBase64: async (path: string, base64Contents: string) => {
46 await mkdir(dirname(path), { recursive: true })
47 return writeFile(path, getBinaryFile(base64Contents) as string)
48 },
49 getPackageManagerVersion: async (packageManager, cwd) => {
50 if (cancelSignal?.aborted) return undefined
51 // Cancel through stop() while Windows can still inspect the live tree.
52 const subprocess = execa(packageManager, ['--version'], {
53 cwd,
54 // Own the group so cleanup can include descendants holding pipes.
55 detached: process.platform !== 'win32',
56 })
57 let cleanup: Promise<undefined> | undefined
58 const stop = () => {
59 cleanup ??= (async () => {
60 if (subprocess.pid !== undefined) {
61 try {
62 if (process.platform === 'win32') {
63 if (
64 subprocess.exitCode === null &&
65 subprocess.signalCode === null
66 ) {
67 await execa(
68 'taskkill',
69 ['/PID', String(subprocess.pid), '/T', '/F'],
70 {
71 timeout: 5_000,
72 windowsHide: true,
73 },
74 )
75 }
76 } else {
77 process.kill(-subprocess.pid, 'SIGKILL')
78 }
79 } catch {
80 subprocess.kill('SIGKILL')
81 }
82 }
83 subprocess.stdout.destroy()
84 subprocess.stderr.destroy()
85 await subprocess.catch(() => undefined)
86 return undefined
87 })()
88 return cleanup
89 }
90 let timer: ReturnType<typeof setTimeout> | undefined
91 const timeout = new Promise<undefined>((resolveTimeout) => {
92 timer = setTimeout(() => {
93 void stop().then(() => resolveTimeout(undefined))
94 }, 15_000)
95 })
96 let onAbort: (() => void) | undefined
97 const cancellation = new Promise<undefined>((resolveCancellation) => {
98 onAbort = () => {
99 void stop().then(() => resolveCancellation(undefined))
100 }
101 cancelSignal?.addEventListener('abort', onAbort, { once: true })
102 if (cancelSignal?.aborted) onAbort()
103 })
104 try {
105 const result = await Promise.race([subprocess, timeout, cancellation])
106 return result?.stdout.trim()
107 } catch {
108 return undefined
109 } finally {
110 clearTimeout(timer)
111 if (onAbort) cancelSignal?.removeEventListener('abort', onAbort)
112 if (cleanup) await cleanup
113 }
114 },
115 execute: async (
116 command: string,
117 args: Array<string>,
118 cwd: string,
119 options?: { inherit?: boolean },
120 ) => {
121 try {
122 if (options?.inherit) {
123 // For commands that should show output directly to the user
124 await execa(command, args, {
125 cwd,
126 cancelSignal,
127 stdio: 'inherit',
128 })
129 return { stdout: '' }
130 } else {
131 // For commands where we need to capture output
132 const result = await execa(command, args, {
133 cwd,
134 cancelSignal,
135 })
136 return { stdout: result.stdout }
137 }
138 } catch {
139 errors.push(
140 `Command "${command} ${args.join(' ')}" did not run successfully. Please run this manually in your project.`,
141 )
142 return { stdout: '', failed: true }
143 }
144 },
145 deleteFile: async (path: string) => {
146 if (existsSync(path)) {
147 await unlink(path)
148 }
149 },
150​
151 readFile: async (path: string) => {
152 return (await readFile(path)).toString()
153 },
154 exists: (path: string) => existsSync(path),
155 isDirectory: (path: string) => statSync(path).isDirectory(),
156 readdir: async (path: string) => readdir(path),
157 rimraf: async (path: string) => {
158 await rimraf(path)
159 },
160​
161 appName: 'TanStack',
162​
163 startStep: () => {},
164 finishStep: () => {},
165​
166 intro: () => {},
167 outro: () => {},
168 info: () => {},
169 error: () => {},
170 warn: () => {},
171 confirm: () => Promise.resolve(true),
172 spinner: () => ({
173 start: () => {},
174 stop: () => {},
175 }),
176 }
178​
179export function createMemoryEnvironment(returnPathsRelativeTo: string = '') {
180 const { environment, output } = createEdgeMemoryEnvironment(
181 returnPathsRelativeTo,
182 )
183 const resolvePath = (path: string) => resolve(process.cwd(), path)
184​
185 const appendFile = environment.appendFile
186 environment.appendFile = (path, contents) =>
187 appendFile(resolvePath(path), contents)
188​
189 const copyFile = environment.copyFile
190 environment.copyFile = (from, to) =>
191 copyFile(resolvePath(from), resolvePath(to))
192​
193 const writeFile = environment.writeFile
194 environment.writeFile = (path, contents) =>
195 writeFile(resolvePath(path), contents)
196​
197 const writeFileBase64 = environment.writeFileBase64
198 environment.writeFileBase64 = (path, contents) =>
199 writeFileBase64(resolvePath(path), contents)
200​
201 const deleteFile = environment.deleteFile
202 environment.deleteFile = (path) => deleteFile(resolvePath(path))
203​
204 const readFile = environment.readFile
205 environment.readFile = (path) => readFile(resolvePath(path))
206​
207 const exists = environment.exists
208 environment.exists = (path) => exists(resolvePath(path))
209​
210 const isDirectory = environment.isDirectory
211 environment.isDirectory = (path) => isDirectory(resolvePath(path))
212​
213 const readdir = environment.readdir
214 environment.readdir = (path) => readdir(resolvePath(path))
215​
216 const rimraf = environment.rimraf
217 environment.rimraf = (path) => rimraf(resolvePath(path))
218​
219 return { environment, output }