Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add code size analyzer #109

Merged
merged 2 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { IndexHtmlTransformHook, PluginOption, Rollup } from 'vite';
import { Config, ViteConfigFn } from './type';
import {
CodeSizeAnalyzer,
createWorkerTask,
formatTime,
getChunkName,
getManualChunks,
getThreadPoolSize,
Expand Down Expand Up @@ -70,9 +70,10 @@ export default function viteBundleObfuscator(config?: Partial<Config>): PluginOp
const transformIndexHtmlHandler: IndexHtmlTransformHook = async (html, { bundle }) => {
if (!finalConfig.enable || !bundle) return html;

_log.forceLog('starting obfuscation process...');
const now = performance.now();
_log.forceLog(LOG_COLOR.info + '\nstarting obfuscation process...');
const analyzer = new CodeSizeAnalyzer(_log);
const bundleList = getValidBundleList(finalConfig, bundle);
analyzer.start(bundleList);

if (isEnableThreadPool(finalConfig)) {
const poolSize = Math.min(getThreadPoolSize(finalConfig), bundleList.length);
Expand All @@ -91,8 +92,7 @@ export default function viteBundleObfuscator(config?: Partial<Config>): PluginOp
});
}

const consume = formatTime(performance.now() - now);
_log.forceLog(LOG_COLOR.info + '%s\x1b[0m %s', '✓', `obfuscation process completed in ${consume}.`);
analyzer.end(bundleList);

return html;
};
Expand Down
8 changes: 8 additions & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ObfuscatorOptions } from 'javascript-obfuscator';
import type { Plugin, Rollup } from 'vite';
import { SizeUnit } from './utils/constants';

export type ViteConfigFn = Plugin['config'];

Expand All @@ -10,6 +11,13 @@ export interface WorkerMessage {
chunk: BundleList;
}

export type SizeResult = { original: FormatSizeResult; gzip: FormatSizeResult };

export interface FormatSizeResult {
value: number;
unit: SizeUnit;
}

export interface ObfuscationResult {
fileName: string;
obfuscatedCode: string;
Expand Down
7 changes: 7 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,14 @@ export const VENDOR_MODULES = 'vendor-modules';

export const CHUNK_PREFIX = 'vendor-';

export enum SizeUnit {
B = 'B',
KB = 'KB',
MB = 'MB',
}

export const LOG_COLOR = Object.freeze({
info: '\x1b[36m', // Cyan
warn: '\x1b[33m', // Yellow
success: '\x1b[32m', // Green
});
98 changes: 94 additions & 4 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as vite from 'vite';
import { Rollup } from 'vite';
import { BundleList, Config, ObfuscationResult } from '../type';
import os from 'node:os';
import { isBoolean, isFileNameExcluded, isObject } from './is';
import { Worker } from 'node:worker_threads';
import path from 'node:path';
import os from 'node:os';
import { gzipSync } from 'node:zlib';
import javascriptObfuscator from 'javascript-obfuscator';
import { CHUNK_PREFIX, VENDOR_MODULES } from './constants';

import type { BundleList, Config, FormatSizeResult, ObfuscationResult, SizeResult } from '../type';
import { isBoolean, isFileNameExcluded, isObject } from './is';
import { CHUNK_PREFIX, LOG_COLOR, SizeUnit, VENDOR_MODULES } from './constants';

export class Log {
private readonly _log: (msg: string) => void;
Expand Down Expand Up @@ -133,3 +135,91 @@ export function createWorkerTask(finalConfig: Config, chunk: BundleList) {
});
});
}

export function formatSize(bytes: number): FormatSizeResult {
const units = Object.values(SizeUnit);
let i = 0;
while (bytes >= 1024 && i < units.length - 1) {
bytes /= 1024;
i++;
}
return {
value: Number(bytes.toFixed(2)),
unit: units[i],
};
}

export class CodeSizeAnalyzer {
private _log;
private originalSize: SizeResult;
private obfuscatedSize: SizeResult;
private startTime: number;
private endTime: number;

constructor(log: Log) {
this._log = log;
this.originalSize = this.createEmptySizeResult();
this.obfuscatedSize = this.createEmptySizeResult();
this.startTime = 0;
this.endTime = 0;
}

private createEmptySizeResult(): SizeResult {
return {
original: { value: 0, unit: SizeUnit.B },
gzip: { value: 0, unit: SizeUnit.B },
};
}

start(originalBundleList: BundleList): void {
this.startTime = performance.now();
this.originalSize = this.calculateBundleSize(originalBundleList);
}

end(obfuscatedBundleList: BundleList): void {
this.obfuscatedSize = this.calculateBundleSize(obfuscatedBundleList);
this.endTime = performance.now();
this.logResult();
}

private calculateBundleSize(bundleList: BundleList): { original: FormatSizeResult; gzip: FormatSizeResult } {
const { totalSize, gzipSize } = bundleList.reduce(
(acc, [, bundleItem]) => {
if (bundleItem.code) {
const { code } = bundleItem;
acc.totalSize += Buffer.byteLength(code, 'utf-8');
acc.gzipSize += gzipSync(code, { level: 9 }).byteLength;
}
return acc;
},
{ totalSize: 0, gzipSize: 0 },
);

return {
original: formatSize(totalSize),
gzip: formatSize(gzipSize),
};
}

private analyze(): string {
const { originalSize, obfuscatedSize } = this;

const consume = formatTime(this.endTime - this.startTime);

const percentageIncrease = (
((obfuscatedSize.original.value - originalSize.original.value) / originalSize.original.value)
* 100
).toFixed(2);
Comment on lines +209 to +212
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Handle edge cases where original sizes are 0 to prevent NaN or Infinity results

Add checks before division to handle cases where originalSize values are 0. Consider returning '0%' or 'N/A' in such cases.


const gzipPercentageIncrease = (
((obfuscatedSize.gzip.value - originalSize.gzip.value) / originalSize.gzip.value)
* 100
).toFixed(2);

return `✓ obfuscated in ${consume} | 📦 ${originalSize.original.value}${originalSize.original.unit} (gzip: ${originalSize.gzip.value}${originalSize.gzip.unit}) → 🔒 ${obfuscatedSize.original.value}${obfuscatedSize.original.unit} (gzip: ${obfuscatedSize.gzip.value}${obfuscatedSize.gzip.unit}) | 📈 ${percentageIncrease}% (gzip: ${gzipPercentageIncrease}%)`;
}

private logResult(): void {
this._log.forceLog(LOG_COLOR.success + '%s\x1b[0m', this.analyze());
}
}
Loading