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