-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
predefinedGeneratorResolvers.ts
231 lines (208 loc) · 6.37 KB
/
predefinedGeneratorResolvers.ts
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
import Debug from '@prisma/debug'
import chalk from 'chalk'
import execa from 'execa'
import fs from 'fs'
import hasYarn from 'has-yarn'
import path from 'path'
import resolvePkg from 'resolve-pkg'
import { logger } from '.'
import { getCommandWithExecutor } from './getCommandWithExecutor'
const debugEnabled = Debug.enabled('generator')
export type GeneratorPaths = {
outputPath: string
generatorPath: string
isNode?: boolean
}
export type GeneratorResolver = (
baseDir: string,
version?: string,
) => Promise<GeneratorPaths>
export type PredefinedGeneratorResolvers = {
[generatorName: string]: GeneratorResolver
}
export const predefinedGeneratorResolvers: PredefinedGeneratorResolvers = {
photonjs: () => {
throw new Error(`Oops! Photon has been renamed to Prisma Client. Please make the following adjustments:
1. Rename ${chalk.red('provider = "photonjs"')} to ${chalk.green(
'provider = "prisma-client-js"',
)} in your ${chalk.bold('schema.prisma')} file.
2. Replace your ${chalk.bold('package.json')}'s ${chalk.red(
'@prisma/photon',
)} dependency to ${chalk.green('@prisma/client')}
3. Replace ${chalk.red(
"import { Photon } from '@prisma/photon'",
)} with ${chalk.green(
"import { PrismaClient } from '@prisma/client'",
)} in your code.
4. Run ${chalk.green(getCommandWithExecutor('prisma generate'))} again.
`)
},
'prisma-client-js': async (baseDir, version) => {
let prismaClientDir = resolvePkg('@prisma/client', { cwd: baseDir })
checkYarnVersion()
checkTypeScriptVersion()
if (debugEnabled) {
console.log({ prismaClientDir })
}
if (!prismaClientDir && !process.env.PRISMA_GENERATE_SKIP_AUTOINSTALL) {
if (
!fs.existsSync(path.join(process.cwd(), 'package.json')) &&
!fs.existsSync(path.join(process.cwd(), '../package.json'))
) {
// Create default package.json
const defaultPackageJson = `{
"name": "my-prisma-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
`
fs.writeFileSync(
path.join(process.cwd(), 'package.json'),
defaultPackageJson,
)
console.info(`✔ Created ${chalk.bold.green('./package.json')}`)
}
await installPackage(baseDir, `-D prisma@${version ?? 'latest'}`)
await installPackage(baseDir, `@prisma/client@${version ?? 'latest'}`)
prismaClientDir = resolvePkg('@prisma/client', { cwd: baseDir })
if (!prismaClientDir) {
throw new Error(
`Could not resolve @prisma/client despite the installation that we just tried.
Please try to install it by hand with ${chalk.bold.greenBright(
'npm install @prisma/client',
)} and rerun ${chalk.bold(
getCommandWithExecutor('prisma generate'),
)} 🙏.`,
)
}
console.info(
`\n✔ Installed the ${chalk.bold.green(
'@prisma/client',
)} and ${chalk.bold.green('prisma')} packages in your project`,
)
}
if (!prismaClientDir) {
throw new Error(
`Could not resolve @prisma/client.
Please try to install it with ${chalk.bold.greenBright(
'npm install @prisma/client',
)} and rerun ${chalk.bold(
getCommandWithExecutor('prisma generate'),
)} 🙏.`,
)
}
return {
outputPath: prismaClientDir,
generatorPath: path.resolve(prismaClientDir, 'generator-build/index.js'),
isNode: true,
}
},
}
async function installPackage(baseDir: string, pkg: string): Promise<void> {
const yarnUsed = hasYarn(baseDir) || hasYarn(path.join(baseDir, '..'))
const cmdName = yarnUsed ? 'yarn add' : 'npm install'
await execa.command(`${cmdName} ${pkg}`, {
cwd: baseDir,
stdio: 'inherit',
env: {
PRISMA_SKIP_POSTINSTALL_GENERATE: 'true',
},
})
}
/**
* Warn, if yarn is older than 1.19.2
*/
function checkYarnVersion() {
if (process.env.npm_config_user_agent) {
const match = parseUserAgentString(process.env.npm_config_user_agent)
if (match) {
const { agent, major, minor, patch } = match
if (agent === 'yarn' && major === 1) {
const currentYarnVersion = `${major}.${minor}.${patch}`
const minYarnVersion = '1.19.2'
if (semverLt(currentYarnVersion, minYarnVersion)) {
logger.warn(
`Your ${chalk.bold(
'yarn',
)} has version ${currentYarnVersion}, which is outdated. Please update it to ${chalk.bold(
minYarnVersion,
)} or ${chalk.bold('newer')} in order to use Prisma.`,
)
}
}
}
}
}
/**
* Warn, if typescript is below `4.1.0` or if it is not install locally or globally
*/
function checkTypeScriptVersion() {
const minVersion = '4.1.0'
try {
const output = execa.sync('tsc', ['-v'], {
preferLocal: true,
})
if (output.stdout) {
const currentVersion = output.stdout.split(' ')[1]
if (semverLt(currentVersion, minVersion)) {
throw new Error(
`Your ${chalk.bold(
'typescript',
)} version is ${currentVersion}, which is outdated. Please update it to ${chalk.bold(
minVersion,
)} or ${chalk.bold('newer')} in order to use Prisma Client.`,
)
}
}
} catch (e) {
// They do not have TS installed, we ignore (example: JS project)
}
}
/**
* Returns true, if semver version `a` is lower than `b`
* Note: This obviously doesn't support the full semver spec.
* @param {string} a
* @param {string} b
*/
function semverLt(a, b) {
const [major1, minor1, patch1] = a.split('.')
const [major2, minor2, patch2] = b.split('.')
if (major1 < major2) {
return true
}
if (major1 > major2) {
return false
}
if (minor1 < minor2) {
return true
}
if (minor1 > minor2) {
return false
}
if (patch1 < patch2) {
return true
}
if (patch1 > patch2) {
return false
}
return false
}
function parseUserAgentString(str) {
const userAgentRegex = /(\w+)\/(\d+)\.(\d+)\.(\d+)/
const match = userAgentRegex.exec(str)
if (match) {
const agent = match[1]
const major = parseInt(match[2])
const minor = parseInt(match[3])
const patch = parseInt(match[4])
return { agent, major, minor, patch }
}
return null
}