UNPKG

1.35 kBJavaScriptView Raw
1import fs from 'node:fs';
2import fsPromises from 'node:fs/promises';
3import path from 'node:path';
4import parseJson from 'parse-json';
5import normalizePackageData from 'normalize-package-data';
6import {toPath} from 'unicorn-magic';
7
8const getPackagePath = cwd => path.resolve(toPath(cwd) ?? '.', 'package.json');
9
10const _readPackage = (file, normalize) => {
11 const json = typeof file === 'string'
12 ? parseJson(file)
13 : file;
14
15 if (normalize) {
16 normalizePackageData(json);
17 }
18
19 return json;
20};
21
22export async function readPackage({cwd, normalize = true} = {}) {
23 const packageFile = await fsPromises.readFile(getPackagePath(cwd), 'utf8');
24 return _readPackage(packageFile, normalize);
25}
26
27export function readPackageSync({cwd, normalize = true} = {}) {
28 const packageFile = fs.readFileSync(getPackagePath(cwd), 'utf8');
29 return _readPackage(packageFile, normalize);
30}
31
32export function parsePackage(packageFile, {normalize = true} = {}) {
33 const isObject = packageFile !== null && typeof packageFile === 'object' && !Array.isArray(packageFile);
34 const isString = typeof packageFile === 'string';
35
36 if (!isObject && !isString) {
37 throw new TypeError('`packageFile` should be either an `object` or a `string`.');
38 }
39
40 const clonedPackageFile = isObject ? structuredClone(packageFile) : packageFile;
41
42 return _readPackage(clonedPackageFile, normalize);
43}