forked from prisma/prisma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateClient.ts
450 lines (411 loc) · 11.9 KB
/
generateClient.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import { BinaryType } from '@prisma/fetch-engine'
import {
BinaryPaths,
DataSource,
DMMF,
GeneratorConfig,
} from '@prisma/generator-helper'
import { getVersion } from '@prisma/sdk/dist/engine-commands/getVersion'
import copy from '@timsuchanek/copy'
import chalk from 'chalk'
import fs from 'fs'
import makeDir from 'make-dir'
import path from 'path'
import pkgUp from 'pkg-up'
import { promisify } from 'util'
import { DMMF as PrismaClientDMMF } from '../runtime/dmmf-types'
import { Dictionary } from '../runtime/utils/common'
import { getPrismaClientDMMF } from './getDMMF'
import { JS, TS, TSClient } from './TSClient'
import { BrowserJS } from './TSClient/Generatable'
const remove = promisify(fs.unlink)
const writeFile = promisify(fs.writeFile)
const exists = promisify(fs.exists)
const copyFile = promisify(fs.copyFile)
const stat = promisify(fs.stat)
export class DenylistError extends Error {
constructor(message: string) {
super(message)
this.name = 'DenylistError'
this.stack = undefined
}
}
export interface GenerateClientOptions {
projectRoot?: string
datamodel: string
datamodelPath: string
browser?: boolean
schemaDir?: string
transpile?: boolean
runtimePath?: string
outputDir: string
generator?: GeneratorConfig
dmmf: DMMF.Document
datasources: DataSource[]
binaryPaths: BinaryPaths
testMode?: boolean
copyRuntime?: boolean
engineVersion: string
clientVersion: string
activeProvider: string
}
export interface BuildClientResult {
fileMap: Dictionary<string>
prismaClientDmmf: PrismaClientDMMF.Document
}
// eslint-disable-next-line @typescript-eslint/require-await
export async function buildClient({
datamodel,
schemaDir = process.cwd(),
runtimePath = '@prisma/client/runtime',
browser = false,
binaryPaths,
outputDir,
generator,
dmmf,
datasources,
engineVersion,
clientVersion,
projectRoot,
activeProvider,
}: GenerateClientOptions): Promise<BuildClientResult> {
const document = getPrismaClientDMMF(dmmf)
const useNodeAPI =
generator?.previewFeatures?.includes('nApi') ||
process.env.PRISMA_FORCE_NAPI === 'true'
const client = new TSClient({
document,
runtimePath,
browser,
datasources: datasources,
generator,
platforms: useNodeAPI
? Object.keys(binaryPaths.libqueryEngine!)
: Object.keys(binaryPaths.queryEngine!),
schemaDir,
outputDir,
clientVersion,
engineVersion,
projectRoot: projectRoot!,
activeProvider,
})
const fileMap = {
'index.d.ts': TS(client),
'index.js': JS(client),
'index-browser.js': BrowserJS(client),
}
return {
fileMap,
prismaClientDmmf: document,
}
}
async function getDotPrismaDir(outputDir: string): Promise<string> {
if (outputDir.endsWith('node_modules/@prisma/client')) {
return path.join(outputDir, '../../.prisma/client')
}
if (
process.env.INIT_CWD &&
process.env.npm_lifecycle_event === 'postinstall' &&
!process.env.PWD?.includes('.pnpm')
) {
// INIT_CWD is the dir, in which "npm install" has been invoked. That can e.g. be in ./src
// If we're in ./ - there'll also be a package.json, so we can directly go for it
// otherwise, we'll go up in the filesystem and look for the first package.json
if (fs.existsSync(path.join(process.env.INIT_CWD, 'package.json'))) {
return path.join(process.env.INIT_CWD, 'node_modules/.prisma/client')
}
const packagePath = await pkgUp({ cwd: process.env.INIT_CWD })
if (packagePath) {
return path.join(path.dirname(packagePath), 'node_modules/.prisma/client')
}
}
return path.join(outputDir, '../../.prisma/client')
}
export async function generateClient({
datamodel,
datamodelPath,
schemaDir = datamodelPath ? path.dirname(datamodelPath) : process.cwd(),
outputDir,
transpile,
runtimePath,
browser,
generator,
dmmf,
datasources,
binaryPaths,
testMode,
copyRuntime,
clientVersion,
engineVersion,
activeProvider,
}: GenerateClientOptions): Promise<BuildClientResult | undefined> {
const useDotPrisma = testMode ? !runtimePath : !generator?.isCustomOutput
const useNodeAPI =
generator?.previewFeatures?.includes('nApi') ||
process.env.PRISMA_FORCE_NAPI === 'true'
runtimePath =
runtimePath || (useDotPrisma ? '@prisma/client/runtime' : './runtime')
const finalOutputDir = useDotPrisma
? await getDotPrismaDir(outputDir)
: outputDir
const packageRoot = await pkgUp({ cwd: path.dirname(finalOutputDir) })
const projectRoot = packageRoot ? path.dirname(packageRoot) : process.cwd()
const { prismaClientDmmf, fileMap } = await buildClient({
datamodel,
datamodelPath,
schemaDir,
transpile,
runtimePath,
browser,
outputDir: finalOutputDir,
generator,
dmmf,
datasources,
binaryPaths,
clientVersion,
engineVersion,
projectRoot,
activeProvider,
})
const denylistsErrors = validateDmmfAgainstDenylists(prismaClientDmmf)
if (denylistsErrors) {
let message = `${chalk.redBright.bold(
'Error: ',
)}The schema at "${datamodelPath}" contains reserved keywords.\n Rename the following items:`
for (const error of denylistsErrors) {
message += '\n - ' + error.message
}
message += `\nTo learn more about how to rename models, check out https://pris.ly/d/naming-models`
throw new DenylistError(message)
}
await makeDir(finalOutputDir)
await makeDir(path.join(outputDir, 'runtime'))
await Promise.all(
Object.entries(fileMap).map(async ([fileName, file]) => {
const filePath = path.join(finalOutputDir, fileName)
// The deletion of the file is necessary, so VSCode
// picks up the changes.
if (await exists(filePath)) {
await remove(filePath)
}
await writeFile(filePath, file)
}),
)
const runtimeSourceDir = testMode
? eval(`require('path').join(__dirname, '../../runtime')`) // tslint:disable-line
: eval(`require('path').join(__dirname, '../runtime')`) // tslint:disable-line
// if users use a custom output dir
if (
copyRuntime ||
!path.resolve(outputDir).endsWith(`@prisma${path.sep}client`)
) {
// TODO: Windows, / is not working here...
const copyTarget = path.join(outputDir, 'runtime')
await makeDir(copyTarget)
if (runtimeSourceDir !== copyTarget) {
await copy({
from: runtimeSourceDir,
to: copyTarget,
recursive: true,
parallelJobs: process.platform === 'win32' ? 1 : 20,
overwrite: true,
})
}
}
const enginePath = useNodeAPI
? binaryPaths.libqueryEngine
: binaryPaths.queryEngine
if (!enginePath) {
throw new Error(
`Prisma Client needs \`${
useNodeAPI ? 'libqueryEngine' : 'queryEngine'
}\` in the \`binaryPaths\` object.`,
)
}
if (transpile) {
if (process.env.NETLIFY) {
await makeDir('/tmp/prisma-engines')
}
for (const [binaryTarget, filePath] of Object.entries(enginePath)) {
const fileName = path.basename(filePath)
const target =
process.env.NETLIFY && binaryTarget !== 'rhel-openssl-1.0.x'
? path.join('/tmp/prisma-engines', fileName)
: path.join(finalOutputDir, fileName)
const [sourceFileSize, targetFileSize] = await Promise.all([
fileSize(filePath),
fileSize(target),
])
// If the target doesn't exist yet, copy it
if (!targetFileSize) {
if (fs.existsSync(filePath)) {
await copyFile(filePath, target)
continue
} else {
throw new Error(`File at ${filePath} is required but was not present`)
}
}
// If target !== source size, they're definitely different, copy it
if (
targetFileSize &&
sourceFileSize &&
targetFileSize !== sourceFileSize
) {
await copyFile(filePath, target)
continue
}
const binaryName = useNodeAPI
? BinaryType.libqueryEngine
: BinaryType.queryEngine
// They must have an equal size now, let's check for the hash
const [sourceVersion, targetVersion] = await Promise.all([
getVersion(filePath, binaryName).catch(() => null),
getVersion(target, binaryName).catch(() => null),
])
if (sourceVersion && targetVersion && sourceVersion === targetVersion) {
// skip
} else {
await copyFile(filePath, target)
}
}
}
const datamodelTargetPath = path.join(finalOutputDir, 'schema.prisma')
if (datamodelPath !== datamodelTargetPath) {
await copyFile(datamodelPath, datamodelTargetPath)
}
if (!generator?.isCustomOutput) {
const packageJsonTargetPath = path.join(finalOutputDir, 'package.json')
const pkgJson = JSON.stringify(
{
name: '.prisma/client',
main: 'index.js',
types: 'index.d.ts',
browser: 'index-browser.js',
},
null,
2,
)
await writeFile(packageJsonTargetPath, pkgJson)
}
if (!testMode && process.env.INIT_CWD) {
const backupPath = path.join(
process.env.INIT_CWD,
'node_modules/.prisma/client',
)
if (finalOutputDir !== backupPath && !generator?.isCustomOutput) {
await copy({
from: finalOutputDir,
to: backupPath,
recursive: true,
parallelJobs: process.platform === 'win32' ? 1 : 20,
overwrite: true,
})
}
}
const proxyIndexJsPath = path.join(outputDir, 'index.js')
const proxyIndexBrowserJsPath = path.join(outputDir, 'index-browser.js')
const proxyIndexDTSPath = path.join(outputDir, 'index.d.ts')
if (!fs.existsSync(proxyIndexJsPath)) {
await copyFile(path.join(__dirname, '../../index.js'), proxyIndexJsPath)
}
if (!fs.existsSync(proxyIndexDTSPath)) {
await copyFile(path.join(__dirname, '../../index.d.ts'), proxyIndexDTSPath)
}
if (!fs.existsSync(proxyIndexBrowserJsPath)) {
await copyFile(
path.join(__dirname, '../../index-browser.js'),
proxyIndexBrowserJsPath,
)
}
return { prismaClientDmmf, fileMap }
}
async function fileSize(name: string): Promise<number | null> {
try {
const statResult = await stat(name)
return statResult.size
} catch (e) {
return null
}
}
function validateDmmfAgainstDenylists(
prismaClientDmmf: PrismaClientDMMF.Document,
): Error[] | null {
const errorArray = [] as Error[]
const denylists = {
// A copy of this list is also in prisma-engines. Any edit should be done in both places.
// https://github.com/prisma/prisma-engines/blob/master/libs/datamodel/core/src/transform/ast_to_dml/reserved_model_names.rs
models: [
// Reserved Prisma keywords
'PrismaClient',
'Prisma',
// JavaScript keywords
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
],
fields: ['AND', 'OR', 'NOT'],
dynamic: [],
}
if (prismaClientDmmf.datamodel.enums) {
for (const it of prismaClientDmmf.datamodel.enums) {
if (
denylists.models.includes(it.name) ||
denylists.fields.includes(it.name)
) {
errorArray.push(Error(`"enum ${it.name}"`))
}
}
}
if (prismaClientDmmf.datamodel.models) {
for (const it of prismaClientDmmf.datamodel.models) {
if (
denylists.models.includes(it.name) ||
denylists.fields.includes(it.name)
) {
errorArray.push(Error(`"model ${it.name}"`))
}
}
}
return errorArray.length > 0 ? errorArray : null
}