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 typescript: true,
134 tailwind: true,
135 js: 'ts',
136 jsx: 'tsx',
137 fileRouter: options.mode === 'file-router',
138 codeRouter: options.mode === 'code-router',
139 routerOnly: options.routerOnly === true,
140 includeExamples: 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: (content: string) => {
158 return render(content, 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 = render(content, templateValues)
171 } catch (error) {
172 if (error instanceof IgnoreFileError) {
173 ignoreFile = true
174 } else {
175 console.error(file, error)
176 environment.error(`EJS error in file ${file}`, error?.toString())
177 process.exit(1)
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 // Strip option prefixes from filename (e.g., __postgres__schema.prisma -> schema.prisma)
190 const prefixMatch = target.match(/^(.+\/)?__([^_]+)__(.+)$/)
191 if (prefixMatch) {
192 const [, directory, , filename] = prefixMatch
193 target = (directory || '') + filename
194 }
195
196 let append = false
197 if (target.endsWith('.append')) {
198 append = true
199 target = target.replace('.append', '')
200 }
201
202 if (target.endsWith('.ts') || target.endsWith('.tsx')) {
203 content = await format(content, {
204 semi: false,
205 singleQuote: true,
206 trailingComma: 'all',
207 parser: 'typescript',
208 })
209 }
210
211 if (append) {
212 await environment.appendFile(resolve(options.targetDir, target), content)
213 } else {
214 await environment.writeFile(resolve(options.targetDir, target), content)
215 }
216 }
217}