-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
getClientVersion.ts
74 lines (61 loc) · 1.83 KB
/
getClientVersion.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
import fs from 'fs'
import Module from 'module'
import pkgUp from 'pkg-up'
/**
* Try reading the installed Prisma Client version
*/
export async function getInstalledPrismaClientVersion(cwd: string = process.cwd()): Promise<string | null> {
return (await getPrismaClientVersionFromNodeModules(cwd)) ?? (await getPrismaClientVersionFromLocalPackageJson(cwd))
}
/**
* Try reading the Prisma Client version from its package.json
*/
async function getPrismaClientVersionFromNodeModules(cwd: string = process.cwd()): Promise<string | null> {
try {
const pkgJsonPath = requireResolveFrom('@prisma/client/package.json', cwd)
if (!pkgJsonPath) {
return null
}
const pkgJsonString = await fs.promises.readFile(pkgJsonPath, 'utf-8')
const pkgJson = JSON.parse(pkgJsonString)
if (!pkgJson.version) {
return null
}
return pkgJson.version
} catch {
return null
}
}
/**
* Try reading the Prisma Client version from the local package.json
*/
async function getPrismaClientVersionFromLocalPackageJson(cwd: string = process.cwd()): Promise<string | null> {
try {
const pkgJsonPath = await pkgUp({ cwd })
if (!pkgJsonPath) {
return null
}
const pkgJsonString = await fs.promises.readFile(pkgJsonPath, 'utf-8')
const pkgJson = JSON.parse(pkgJsonString)
const clientVersion = pkgJson.dependencies?.['@prisma/client'] ?? pkgJson.devDependencies?.['@prisma/client']
if (!clientVersion) {
return null
}
return clientVersion
} catch {
return null
}
}
/**
* Run require resolve from a given path
*/
function requireResolveFrom(moduleId: string, fromDir: string): string | null {
try {
const resolvedPath = require.resolve(moduleId, {
paths: (Module as any)._nodeModulePaths(fromDir),
})
return resolvedPath
} catch {
return null
}
}