-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathmain.ts
More file actions
305 lines (261 loc) · 8.61 KB
/
main.ts
File metadata and controls
305 lines (261 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import * as p from '@clack/prompts'
import slugify from '@sindresorhus/slugify'
import arg from 'arg'
import chalk from 'chalk'
import figures from 'figures'
import path from 'path'
import type { CliArgs } from './types.js'
import { configurePayloadConfig } from './lib/configure-payload-config.js'
import { createProject } from './lib/create-project.js'
import { parseExample } from './lib/examples.js'
import { generateSecret } from './lib/generate-secret.js'
import { getPackageManager } from './lib/get-package-manager.js'
import { getNextAppDetails, initNext } from './lib/init-next.js'
import { manageEnvFiles } from './lib/manage-env-files.js'
import { parseProjectName } from './lib/parse-project-name.js'
import { parseTemplate } from './lib/parse-template.js'
import { selectAgent } from './lib/select-agent.js'
import { selectDb } from './lib/select-db.js'
import { getValidTemplates, validateTemplate } from './lib/templates.js'
import { updatePayloadInProject } from './lib/update-payload-in-project.js'
import { getLatestPackageVersion } from './utils/getLatestPackageVersion.js'
import { debug, error, info } from './utils/log.js'
import {
feedbackOutro,
helpMessage,
moveMessage,
successfulNextInit,
successMessage,
} from './utils/messages.js'
export class Main {
args: CliArgs
constructor() {
// @ts-expect-error bad typings
this.args = arg(
{
'--agent': String,
'--branch': String,
'--db': String,
'--db-accept-recommended': Boolean,
'--db-connection-string': String,
'--example': String,
'--help': Boolean,
'--local-template': String,
'--name': String,
'--secret': String,
'--template': String,
'--version': String, // Allows overriding the installed Payload version instead of installing the latest
// Next.js
'--init-next': Boolean, // TODO: Is this needed if we detect if inside Next.js project?
// Agent
'--no-agent': Boolean,
// Package manager
'--no-deps': Boolean,
'--use-bun': Boolean,
'--use-npm': Boolean,
'--use-pnpm': Boolean,
'--use-yarn': Boolean,
// Other
'--no-git': Boolean,
// Flags
'--beta': Boolean,
'--debug': Boolean,
'--dry-run': Boolean,
// Aliases
'-a': '--agent',
'-d': '--db',
'-e': '--example',
'-h': '--help',
'-n': '--name',
'-t': '--template',
},
{ permissive: true },
)
}
async init(): Promise<void> {
try {
const debugFlag = this.args['--debug']
// Set DEBUG env var for logger utility
if (debugFlag) {
process.env.DEBUG = 'true'
}
const LATEST_VERSION = await getLatestPackageVersion({
debug: debugFlag,
packageName: 'payload',
})
if (this.args['--help']) {
helpMessage()
process.exit(0)
}
// eslint-disable-next-line no-console
console.log('\n')
p.intro(chalk.bgCyan(chalk.black(' create-payload-app ')))
p.note("Welcome to Payload. Let's create a project!")
// Detect if inside Next.js project
const nextAppDetails = await getNextAppDetails(process.cwd())
const {
hasTopLevelLayout,
isPayloadInstalled,
isSupportedNextVersion,
nextAppDir,
nextConfigPath,
nextVersion,
} = nextAppDetails
if (nextConfigPath && !isSupportedNextVersion) {
p.log.warn(
`Next.js v${nextVersion} is unsupported. Next.js >= 15 is required to use Payload.`,
)
p.outro(feedbackOutro())
process.exit(0)
}
// Upgrade Payload in existing project
if (isPayloadInstalled && nextConfigPath) {
p.log.warn(`Payload installation detected in current project.`)
const shouldUpdate = await p.confirm({
initialValue: false,
message: chalk.bold(`Upgrade Payload in this project?`),
})
if (!p.isCancel(shouldUpdate) && shouldUpdate) {
const { message, success: updateSuccess } = await updatePayloadInProject(nextAppDetails)
if (updateSuccess) {
info(message)
} else {
error(message)
}
}
p.outro(feedbackOutro())
process.exit(0)
}
if (nextConfigPath) {
this.args['--name'] = slugify(path.basename(path.dirname(nextConfigPath)))
}
const projectName = await parseProjectName(this.args)
const projectDir = nextConfigPath
? path.dirname(nextConfigPath)
: path.resolve(process.cwd(), slugify(projectName))
const packageManager = await getPackageManager({ cliArgs: this.args, projectDir })
if (nextConfigPath) {
p.log.step(
chalk.bold(`${chalk.bgBlack(` ${figures.triangleUp} Next.js `)} project detected!`),
)
const proceed = await p.confirm({
initialValue: true,
message: chalk.bold(`Install ${chalk.green('Payload')} in this project?`),
})
if (p.isCancel(proceed) || !proceed) {
p.outro(feedbackOutro())
process.exit(0)
}
// Check for top-level layout.tsx
if (nextAppDir && hasTopLevelLayout) {
p.log.warn(moveMessage({ nextAppDir, projectDir }))
p.outro(feedbackOutro())
process.exit(0)
}
const dbDetails = await selectDb(this.args, projectName)
const result = await initNext({
...this.args,
dbType: dbDetails.type,
nextAppDetails,
packageManager,
projectDir,
})
if (result.success === false) {
p.outro(feedbackOutro())
process.exit(1)
}
await configurePayloadConfig({
dbType: dbDetails?.type,
projectDirOrConfigPath: {
payloadConfigPath: result.payloadConfigPath,
},
})
await manageEnvFiles({
cliArgs: this.args,
databaseType: dbDetails.type,
databaseUri: dbDetails.dbUri,
payloadSecret: generateSecret(),
projectDir,
})
info('Payload project successfully initialized!')
p.note(successfulNextInit(), chalk.bgGreen(chalk.black(' Documentation ')))
p.outro(feedbackOutro())
return
}
const templateArg = this.args['--template']
if (templateArg) {
const valid = validateTemplate({ templateName: templateArg })
if (!valid) {
helpMessage()
process.exit(1)
}
}
const exampleArg = this.args['--example']
if (exampleArg) {
const example = await parseExample({
name: exampleArg,
branch: this.args['--branch'] ?? 'main',
})
if (!example) {
helpMessage()
process.exit(1)
}
const agentType = await selectAgent({ cliArgs: this.args })
await createProject({
agentType,
cliArgs: this.args,
example,
packageManager,
projectDir,
projectName,
})
}
if (debugFlag) {
debug(`Using ${exampleArg ? 'examples' : 'templates'} from git tag: v${LATEST_VERSION}`)
}
if (!exampleArg) {
const validTemplates = getValidTemplates()
const template = await parseTemplate(this.args, validTemplates)
if (!template) {
p.log.error('Invalid template given')
p.outro(feedbackOutro())
process.exit(1)
}
switch (template.type) {
case 'plugin': {
const agentType = await selectAgent({ cliArgs: this.args })
await createProject({
agentType,
cliArgs: this.args,
packageManager,
projectDir,
projectName,
template,
})
break
}
case 'starter': {
const dbDetails = await selectDb(this.args, projectName, template)
const agentType = await selectAgent({ cliArgs: this.args })
await createProject({
agentType,
cliArgs: this.args,
dbDetails,
packageManager,
projectDir,
projectName,
template,
})
break
}
}
}
info('Payload project successfully created!')
p.log.step(chalk.bgGreen(chalk.black(' Next Steps ')))
p.log.message(successMessage(projectDir, packageManager))
p.outro(feedbackOutro())
} catch (err: unknown) {
error(err instanceof Error ? err.message : 'An error occurred')
}
}
}