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 getPackageManagerInstallCommand,
8 getPackageManagerScriptCommand,
9} from './package-manager.js'
10import { relativePath } from './file-helpers.js'
11
12import type {
13 AddOn,
14 Environment,
15 Integration,
16 IntegrationWithSource,
17 Options,
18} from './types.js'
19
20function convertDotFilesAndPaths(path: string) {
21 return path
22 .split(sep)
23 .map((segment) => segment.replace(/^_dot_/, '.'))
24 .join(sep)
25}
26
27export function createTemplateFile(environment: Environment, options: Options) {
28 function getPackageManagerAddScript(
29 packageName: string,
30 isDev: boolean = false,
31 ) {
32 return formatCommand(
33 getPackageManagerInstallCommand(
34 options.packageManager,
35 packageName,
36 isDev,
37 ),
38 )
39 }
40 function getPackageManagerRunScript(
41 scriptName: string,
42 args: Array<string> = [],
43 ) {
44 return formatCommand(
45 getPackageManagerScriptCommand(options.packageManager, [
46 scriptName,
47 ...args,
48 ]),
49 )
50 }
51
52 class IgnoreFileError extends Error {
53 constructor() {
54 super('ignoreFile')
55 this.name = 'IgnoreFileError'
56 }
57 }
58
59 // Collect integrations and tag them with source add-on for attribution
60 const integrations: Array<IntegrationWithSource> = []
61 for (const addOn of options.chosenAddOns) {
62 if (addOn.integrations) {
63 for (const integration of addOn.integrations) {
64 integrations.push({
65 ...integration,
66 _sourceId: addOn.id,
67 _sourceName: addOn.name,
68 })
69 }
70 }
71 }
72
73 const routes: Array<Required<AddOn>['routes'][number]> = []
74 for (const addOn of options.chosenAddOns) {
75 if (addOn.routes) {
76 routes.push(...addOn.routes)
77 }
78 }
79
80 const addOnEnabled = options.chosenAddOns.reduce<Record<string, boolean>>(
81 (acc, addOn) => {
82 acc[addOn.id] = true
83 return acc
84 },
85 {},
86 )
87
88 return async function templateFile(file: string, content: string) {
89 const localRelativePath = (path: string, stripExtension: boolean = false) =>
90 relativePath(file, path, stripExtension)
91
92 const integrationImportContent = (integration: Integration) =>
93 integration.import ||
94 `import ${integration.jsName} from '${localRelativePath(integration.path || '')}'`
95
96 const integrationImportCode = (integration: Integration) =>
97 integration.code || integration.jsName
98
99 const templateValues = {
100 packageManager: options.packageManager,
101 projectName: options.projectName,
102 typescript: true,
103 tailwind: true,
104 js: 'ts',
105 jsx: 'tsx',
106 fileRouter: options.mode === 'file-router',
107 codeRouter: options.mode === 'code-router',
108 addOnEnabled,
109 addOnOption: options.addOnOptions,
110 addOns: options.chosenAddOns,
111 integrations,
112 routes,
113
114 getPackageManagerAddScript,
115 getPackageManagerRunScript,
116
117 relativePath: (path: string, stripExtension: boolean = false) =>
118 relativePath(file, path, stripExtension),
119
120 integrationImportContent,
121 integrationImportCode,
122
123 ignoreFile: () => {
124 throw new IgnoreFileError()
125 },
126 }
127
128 let ignoreFile = false
129
130 if (file.endsWith('.ejs')) {
131 try {
132 content = render(content, templateValues)
133 } catch (error) {
134 if (error instanceof IgnoreFileError) {
135 ignoreFile = true
136 } else {
137 console.error(file, error)
138 environment.error(`EJS error in file ${file}`, error?.toString())
139 process.exit(1)
140 }
141 }
142 }
143
144 if (ignoreFile) {
145 return
146 }
147
148 let target = convertDotFilesAndPaths(file.replace('.ejs', ''))
149
150 // Strip option prefixes from filename (e.g., __postgres__schema.prisma -> schema.prisma)
151 const prefixMatch = target.match(/^(.+\/)?__([^_]+)__(.+)$/)
152 if (prefixMatch) {
153 const [, directory, , filename] = prefixMatch
154 target = (directory || '') + filename
155 }
156
157 let append = false
158 if (target.endsWith('.append')) {
159 append = true
160 target = target.replace('.append', '')
161 }
162
163 if (target.endsWith('.ts') || target.endsWith('.tsx')) {
164 content = await format(content, {
165 semi: false,
166 singleQuote: true,
167 trailingComma: 'all',
168 parser: 'typescript',
169 })
170 }
171
172 if (append) {
173 await environment.appendFile(resolve(options.targetDir, target), content)
174 } else {
175 await environment.writeFile(resolve(options.targetDir, target), content)
176 }
177 }
178}