Skip to content

Commit

Permalink
feat: support logLevel option
Browse files Browse the repository at this point in the history
  • Loading branch information
tjx666 committed Sep 1, 2023
1 parent 4d11c40 commit d38bb05
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 42 deletions.
86 changes: 46 additions & 40 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface Options {
throwErrorWhenDuplicated?: boolean;
whiteList?: Record<string, string[]>;
customErrorMessage?: (issuePackages: Map<string, string[]>) => string;
logLevel?: 'debug' | 'error';
}

const getWorkspaceRootFolder = memoizeAsync(async () => {
Expand All @@ -29,43 +30,6 @@ const getWorkspaceRootFolder = memoizeAsync(async () => {
return workspaceRootFolder;
});

const packagePathRegex = /.*\/node_modules\/(?:@[^/]+\/)?[^/]+/;
const getPackageInfo = memoizeAsync(async (id: string) => {
id = normalizePath(id);
const match = id.match(packagePathRegex);
if (match) {
const packageJsonPath = path.join(match[0], 'package.json');
try {
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
return {
name: packageJson.name,
version: packageJson.version,
};
} catch (error: any) {
consola.warn(`can't read package.json of module id ${id} : ${error.message}`);
}
}
return null;
});

const formatImporter = memoizeAsync(async (importer: string) => {
importer = normalizePath(importer);

let formattedImporter = importer;
if (packagePathRegex.test(importer)) {
const packageInfo = await getPackageInfo(importer);
if (packageInfo) {
formattedImporter = `${packageInfo.name}@${packageInfo.version}`;
}
}

const workspaceRootFolder = await getWorkspaceRootFolder();
if (workspaceRootFolder && formattedImporter.startsWith(workspaceRootFolder)) {
return formattedImporter.slice(workspaceRootFolder.length + 1);
}
return formattedImporter;
});

const getPkgSize = memoizeAsync(_getPkgSize, (name, version) => `${name}@${version}`);

function colorizeSize(kb: number) {
Expand All @@ -90,8 +54,48 @@ export default createUnplugin<Options | undefined>((options) => {
throwErrorWhenDuplicated = false,
whiteList = {},
customErrorMessage,
logLevel = 'debug',
} = options ?? {};

const packagePathRegex = /.*\/node_modules\/(?:@[^/]+\/)?[^/]+/;
const getPackageInfo = memoizeAsync(async (id: string) => {
id = normalizePath(id);
const match = id.match(packagePathRegex);
if (match) {
const packageJsonPath = path.join(match[0], 'package.json');
try {
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
return {
name: packageJson.name,
version: packageJson.version,
};
} catch (error: any) {
if (logLevel === 'debug') {
consola.warn(`can't read package.json of module id ${id} : ${error.message}`);
}
}
}
return null;
});

const formatImporter = memoizeAsync(async (importer: string) => {
importer = normalizePath(importer);

let formattedImporter = importer;
if (packagePathRegex.test(importer)) {
const packageInfo = await getPackageInfo(importer);
if (packageInfo) {
formattedImporter = `${packageInfo.name}@${packageInfo.version}`;
}
}

const workspaceRootFolder = await getWorkspaceRootFolder();
if (workspaceRootFolder && formattedImporter.startsWith(workspaceRootFolder)) {
return formattedImporter.slice(workspaceRootFolder.length + 1);
}
return formattedImporter;
});

/**
* Map(1) {
* 'axios' => Map(2) {
Expand Down Expand Up @@ -194,7 +198,9 @@ export default createUnplugin<Options | undefined>((options) => {
// remove vite output dim colorize
// eslint-disable-next-line unicorn/escape-case, unicorn/no-hex-escape
process.stdout.write(`\x1b[0m${isVitePlugin ? '\n' : ''}`);
consola.warn(warningMessages.join('\n'));
if (logLevel === 'debug') {
consola.warn(warningMessages.join('\n'));
}

if (throwErrorWhenDuplicated) {
const issuePackagesMap = new Map<string, string[]>();
Expand All @@ -212,15 +218,15 @@ export default createUnplugin<Options | undefined>((options) => {
const issueString = [...issuePackagesMap.entries()]
.map(([packageName, _versions]) => {
const versions = _versions.map((version) => `v${version}`).join(', ');
return `${packageName}: ${versions}`;
return ` - ${packageName}: ${versions}`;
})
.join('\n');

if (issuePackagesMap.size > 0) {
throw new Error(
customErrorMessage
? customErrorMessage(issuePackagesMap)
: `[unplugin-detect-duplicated-deps] You can add following duplicated deps to whiteList to pass the check:\n${issueString}`,
: `You can add following duplicated deps to whiteList to pass the check:\n${issueString}`,
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/mono/app/stderr.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[warn] multiple versions of axios is bundled!

axios(49.876000000000005kb):
axios(49.876kb):
- 0.27.2(19.658kb) imported by tests/fixtures/mono/packages/pkg2/index.js
- 1.4.0 (30.218kb) imported by tests/fixtures/mono/packages/pkg1/index.js
9 changes: 8 additions & 1 deletion tests/fixtures/mono/app/vite.config.cts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@ import UnpluginDetectDuplicatedDeps from 'unplugin-detect-duplicated-deps/vite';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [UnpluginDetectDuplicatedDeps()],
plugins: [
UnpluginDetectDuplicatedDeps({
throwErrorWhenDuplicated: true,
whiteList: {
axios: ['0.27.2', '1.4.0'],
},
}),
],
});

0 comments on commit d38bb05

Please sign in to comment.