This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
package_json.ts
60 lines (49 loc) · 1.62 KB
/
package_json.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
import { promises as fs } from 'fs'
import pkgDir from 'pkg-dir'
interface PackageJson {
name?: string
version?: string
dependencies?: Record<string, string>
peerDependencies?: Record<string, string>
peerDependenciesMeta?: Record<string, { optional?: boolean }>
optionalDependencies?: Record<string, string>
devDependencies?: Record<string, string>
files?: string[]
gypfile?: boolean
binary?: boolean
type?: string
}
const sanitiseFiles = (files: unknown): string[] | undefined => {
if (!Array.isArray(files)) {
return undefined
}
return files.filter((file) => typeof file === 'string')
}
const sanitisePackageJson = (packageJson: Record<string, unknown>): PackageJson => ({
...packageJson,
files: sanitiseFiles(packageJson.files),
})
// Retrieve the `package.json` of a specific project or module
const getPackageJson = async function (srcDir: string): Promise<PackageJson> {
const packageRoot = await pkgDir(srcDir)
if (packageRoot === undefined) {
return {}
}
const packageJsonPath = `${packageRoot}/package.json`
try {
// The path depends on the user's build, i.e. must be dynamic
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'))
return sanitisePackageJson(packageJson)
} catch (error) {
throw new Error(`${packageJsonPath} is invalid JSON: ${error.message}`)
}
}
const getPackageJsonIfAvailable = async (srcDir: string): Promise<PackageJson> => {
try {
const packageJson = await getPackageJson(srcDir)
return packageJson
} catch {
return {}
}
}
export { getPackageJson, getPackageJsonIfAvailable, PackageJson, sanitisePackageJson }