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

edge-template-file.ts

214 lines5.6 KB

1import { renderForOptions } from './edge-render.js'
2import { relativePath } from './edge-file-helpers.js'
3import { joinPaths } from './edge-path.js'
4import { formatCommand } from './utils.js'
5import {
6 getPackageManagerExecuteCommand,
7 getPackageManagerInstallCommand,
8 getPackageManagerScriptCommand,
9} from './package-manager.js'
10​
11import type {
12 AddOn,
13 Environment,
14 Integration,
15 IntegrationWithSource,
16 Options,
17} from './types.js'
18​
19function convertDotFilesAndPaths(path: string) {
20 return path
21 .split('/')
22 .map((segment) => segment.replace(/^_dot_/, '.'))
23 .join('/')
25​
26function normalizeSourceExtension(target: string, typescript: boolean) {
27 if (!typescript) {
28 return target
29 }
30​
31 const normalizedTarget = target.replace(/\\/g, '/')
32​
33 if (!normalizedTarget.startsWith('src/')) {
34 return target
35 }
36​
37 if (normalizedTarget.endsWith('.js')) {
38 return `${target.slice(0, -3)}.ts`
39 }
40​
41 if (normalizedTarget.endsWith('.jsx')) {
42 return `${target.slice(0, -4)}.tsx`
43 }
44​
45 return target
47​
48export function createTemplateFile(environment: Environment, options: Options) {
49 function getPackageManagerAddScript(
50 packageName: string,
51 isDev: boolean = false,
52 ) {
53 return formatCommand(
54 getPackageManagerInstallCommand(
55 options.packageManager,
56 packageName,
57 isDev,
58 ),
59 )
60 }
61 function getPackageManagerRunScript(
62 scriptName: string,
63 args: Array<string> = [],
64 ) {
65 return formatCommand(
66 getPackageManagerScriptCommand(options.packageManager, [
67 scriptName,
68 ...args,
69 ]),
70 )
71 }
72 function getPackageManagerExecuteScript(
73 pkg: string,
74 args: Array<string> = [],
75 ) {
76 return formatCommand(
77 getPackageManagerExecuteCommand(options.packageManager, pkg, args),
78 )
79 }
80​
81 class IgnoreFileError extends Error {
82 constructor() {
83 super('ignoreFile')
84 this.name = 'IgnoreFileError'
85 }
86 }
87​
88 const integrations: Array<IntegrationWithSource> = []
89 for (const addOn of options.chosenAddOns) {
90 if (addOn.integrations) {
91 for (const integration of addOn.integrations) {
92 integrations.push({
93 ...integration,
94 _sourceId: addOn.id,
95 _sourceName: addOn.name,
96 })
97 }
98 }
99 }
100​
101 const routes: Array<Required<AddOn>['routes'][number]> = []
102 for (const addOn of options.chosenAddOns) {
103 if (addOn.routes) {
104 routes.push(...addOn.routes)
105 }
106 }
107​
108 const addOnEnabled = options.chosenAddOns.reduce<Record<string, boolean>>(
109 (acc, addOn) => {
110 acc[addOn.id] = true
111 return acc
112 },
113 {},
114 )
115​
116 return async function templateFile(file: string, content: string) {
117 const localRelativePath = (path: string, stripExtension: boolean = false) =>
118 relativePath(file, path, stripExtension)
119​
120 const integrationImportContent = (integration: Integration) =>
121 integration.import ||
122 `import ${integration.jsName} from '${localRelativePath(integration.path || '')}'`
123​
124 const integrationImportCode = (integration: Integration) =>
125 integration.code || integration.jsName
126​
127 const templateValues = {
128 packageManager: options.packageManager,
129 projectName: options.projectName,
130 bundler: options.bundler ?? 'vite',
131 typescript: true,
132 tailwind: options.tailwind,
133 blank: options.projectPreset === 'blank',
134 js: 'ts',
135 jsx: 'tsx',
136 fileRouter: options.mode === 'file-router',
137 codeRouter: options.mode === 'code-router',
138 routerOnly: options.routerOnly === true,
139 includeExamples:
140 options.projectPreset !== 'blank' && options.includeExamples !== false,
141 addOnEnabled,
142 addOnOption: options.addOnOptions,
143 addOns: options.chosenAddOns,
144 integrations,
145 routes,
146​
147 getPackageManagerAddScript,
148 getPackageManagerRunScript,
149 getPackageManagerExecuteScript,
150​
151 relativePath: (path: string, stripExtension: boolean = false) =>
152 relativePath(file, path, stripExtension),
153​
154 integrationImportContent,
155 integrationImportCode,
156​
157 renderTemplate: (templateContent: string) => {
158 return renderForOptions(options, templateContent, templateValues)
159 },
160​
161 ignoreFile: () => {
162 throw new IgnoreFileError()
163 },
164 }
165​
166 let ignoreFile = false
167​
168 if (file.endsWith('.ejs')) {
169 try {
170 content = renderForOptions(options, content, templateValues)
171 } catch (error) {
172 if (error instanceof IgnoreFileError) {
173 ignoreFile = true
174 } else {
175 const message = error instanceof Error ? error.message : String(error)
176 environment.error(`EJS error in file ${file}`, message)
177 throw error
178 }
179 }
180 }
181​
182 if (ignoreFile) {
183 return
184 }
185​
186 let target = convertDotFilesAndPaths(file.replace('.ejs', ''))
187 target = normalizeSourceExtension(target, options.typescript)
188​
189 const prefixMatch = target.match(/^(.+\/)?__([^_]+)__(.+)$/)
190 if (prefixMatch) {
191 const [, directory, , filename] = prefixMatch
192 target = (directory || '') + filename
193 }
194​
195 let append = false
196 if (target.endsWith('.append')) {
197 append = true
198 target = target.replace('.append', '')
199 }
200​
201 if (append) {
202 const targetPath = joinPaths(options.targetDir, target)
203 if (content && !/^[\r\n]/.test(content) && environment.exists(targetPath)) {
204 const existing = await environment.readFile(targetPath)
205 if (existing && !/[\r\n]$/.test(existing)) {
206 content = `\n${content}`
207 }
208 }
209 await environment.appendFile(targetPath, content)
210 } else {
211 await environment.writeFile(joinPaths(options.targetDir, target), content)
212 }
213 }