Skip to content

refactor: track bundle size and gzip size in raw bytes #259

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
37 changes: 37 additions & 0 deletions src/__tests__/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,43 @@ describe('CodeSizeAnalyzer', () => {
expect(lastCallArgs[0]).toBe('\x1b[32m%s\x1b[0m');
expect(lastCallArgs[1]).toContain('MB');
});

it('should calculate percentage correctly when units differ', () => {
const originalBundle: BundleList = [
['test.js', { code: 'a'.repeat(500 * 1024) } as any]
];

const obfuscatedBundle: BundleList = [
['test.js', { code: 'a'.repeat(2 * 1024 * 1024) } as any]
];

analyzer.start(originalBundle);
analyzer.end(obfuscatedBundle);
Comment on lines +310 to +311
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Missing test for negative percentage increase (obfuscated smaller than original).

Please add a test where the obfuscated bundle is smaller than the original to ensure negative percentage increases are handled and displayed correctly.


const lastCallArgs = logSpy.mock.lastCall;
expect(lastCallArgs[0]).toBe('\x1b[32m%s\x1b[0m');
const result = lastCallArgs[1];

expect(result).toMatch(/\d+(\.\d+)?KB.*→.*\d+(\.\d+)?MB/);
expect(result).toMatch(/309\.\d+%/);
});
Comment on lines +317 to +319
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Consider adding assertions for gzip percentage increase and output format.

Adding assertions for gzip percentage and its output format will help verify that both raw and gzip metrics are correctly calculated and displayed, aligning with the updated implementation.

Suggested change
expect(result).toMatch(/\d+(\.\d+)?KB.*.*\d+(\.\d+)?MB/);
expect(result).toMatch(/309\.\d+%/);
});
expect(result).toMatch(/\d+(\.\d+)?KB.*.*\d+(\.\d+)?MB/);
expect(result).toMatch(/309\.\d+%/);
// Assert gzip output format (e.g., KB → MB)
expect(result).toMatch(/gzip:\s*\d+(\.\d+)?KB.*.*\d+(\.\d+)?MB/);
// Assert gzip percentage increase (should be similar to raw, but calculated separately)
// The actual percentage may differ depending on gzip implementation, so match a percentage pattern
expect(result).toMatch(/gzip:.*\(\+\d+(\.\d+)?%\)/);
});


it('should handle zero division when calculating percentage', () => {
const emptyOriginalBundle: BundleList = [];

const obfuscatedBundle: BundleList = [
['test.js', { code: 'console.log("test");' } as any]
];

analyzer.start(emptyOriginalBundle);
analyzer.end(obfuscatedBundle);

const lastCallArgs = logSpy.mock.lastCall;
expect(lastCallArgs[0]).toBe('\x1b[32m%s\x1b[0m');
const result = lastCallArgs[1];

expect(result).toContain('0.00%');
});
});

describe('is utils', () => {
Expand Down
43 changes: 29 additions & 14 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,17 @@ export class CodeSizeAnalyzer {
private _log;
private originalSize: SizeResult;
private obfuscatedSize: SizeResult;
private originalBytes: { total: number; gzip: number };
private obfuscatedBytes: { total: number; gzip: number };
Comment on lines +267 to +268
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider using a type alias for byte size objects.

Defining a type alias for the shared structure will make future updates easier and the code more readable.

Suggested implementation:

type ByteSize = { total: number; gzip: number };

  private _log;
  private originalSize: SizeResult;
  private obfuscatedSize: SizeResult;
  private originalBytes: ByteSize;
  private obfuscatedBytes: ByteSize;
  private startTime: number;
  private endTime: number;
    this._log = log;
    this.originalSize = this.createEmptySizeResult();
    this.obfuscatedSize = this.createEmptySizeResult();
    this.originalBytes = { total: 0, gzip: 0 };
    this.obfuscatedBytes = { total: 0, gzip: 0 };
    this.startTime = 0;
    this.endTime = 0;
  }

private startTime: number;
private endTime: number;

constructor(log: Log) {
this._log = log;
this.originalSize = this.createEmptySizeResult();
this.obfuscatedSize = this.createEmptySizeResult();
this.originalBytes = { total: 0, gzip: 0 };
this.obfuscatedBytes = { total: 0, gzip: 0 };
this.startTime = 0;
this.endTime = 0;
}
Expand All @@ -284,16 +288,23 @@ export class CodeSizeAnalyzer {

start(originalBundleList: BundleList): void {
this.startTime = performance.now();
this.originalSize = this.calculateBundleSize(originalBundleList);
const { size, bytes } = this.calculateBundleSize(originalBundleList);
this.originalSize = size;
this.originalBytes = bytes;
}

end(obfuscatedBundleList: BundleList): void {
this.obfuscatedSize = this.calculateBundleSize(obfuscatedBundleList);
const { size, bytes } = this.calculateBundleSize(obfuscatedBundleList);
this.obfuscatedSize = size;
this.obfuscatedBytes = bytes;
this.endTime = performance.now();
this.logResult();
}

private calculateBundleSize(bundleList: BundleList): { original: FormatSizeResult; gzip: FormatSizeResult } {
private calculateBundleSize(bundleList: BundleList): {
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider simplifying the code by returning and storing only raw byte sizes, and formatting sizes on-the-fly in the logging method.

Suggested change
private calculateBundleSize(bundleList: BundleList): {
// 1. Simplify calculateBundleSize to return raw bytes only
private calculateBundleSize(bundleList: BundleList): { total: number; gzip: number } {
const { totalSize, gzipSize } = bundleList.reduce(
(acc, [, bundleItem]) => {
if (bundleItem.code) {
const code = bundleItem.code;
acc.totalSize += Buffer.byteLength(code, 'utf-8');
acc.gzipSize += gzipSync(code, { level: 9 }).byteLength;
}
return acc;
},
{ totalSize: 0, gzipSize: 0 },
);
return { total: totalSize, gzip: gzipSize };
}
// 2. Drop originalSize/obfuscatedSize fields and only keep raw bytes
private originalBytes = { total: 0, gzip: 0 };
private obfuscatedBytes = { total: 0, gzip: 0 };
start(originalBundleList: BundleList): void {
this.startTime = performance.now();
this.originalBytes = this.calculateBundleSize(originalBundleList);
}
end(obfuscatedBundleList: BundleList): void {
this.obfuscatedBytes = this.calculateBundleSize(obfuscatedBundleList);
this.endTime = performance.now();
this.logResult();
}
// 3. Format sizes on-the-fly in analyze(), removing nested destructuring and guard logic
private analyze(): string {
const { total: oT, gzip: oG } = this.originalBytes;
const { total: fT, gzip: fG } = this.obfuscatedBytes;
const origSize = formatSize(oT);
const origGzip = formatSize(oG);
const newSize = formatSize(fT);
const newGzip = formatSize(fG);
const pct = oT > 0 ? (((fT - oT) / oT) * 100).toFixed(2) : '0.00';
const gzipPct = oG > 0 ? (((fG - oG) / oG) * 100).toFixed(2) : '0.00';
const timeTaken = formatTime(this.endTime - this.startTime);
return `✓ obfuscated in ${timeTaken} | `
+ `📦 ${origSize.value}${origSize.unit} (gzip: ${origGzip.value}${origGzip.unit}) → `
+ `🔒 ${newSize.value}${newSize.unit} (gzip: ${newGzip.value}${newGzip.unit}) | `
+ `📈 ${pct}% (gzip: ${gzipPct}%)`;
}

This keeps all functionality but removes the extra size object, nested destructuring, and boilerplate guard logic, by formatting sizes right before logging.

size: { original: FormatSizeResult; gzip: FormatSizeResult };
bytes: { total: number; gzip: number };
} {
const { totalSize, gzipSize } = bundleList.reduce(
(acc, [, bundleItem]) => {
if (bundleItem.code) {
Expand All @@ -307,25 +318,29 @@ export class CodeSizeAnalyzer {
);

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

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

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

const percentageIncrease = (
((obfuscatedSize.original.value - originalSize.original.value) / originalSize.original.value)
* 100
).toFixed(2);
const percentageIncrease = originalBytes.total > 0
? (((obfuscatedBytes.total - originalBytes.total) / originalBytes.total) * 100).toFixed(2)
: '0.00';

const gzipPercentageIncrease = (
((obfuscatedSize.gzip.value - originalSize.gzip.value) / originalSize.gzip.value)
* 100
).toFixed(2);
const gzipPercentageIncrease = originalBytes.gzip > 0
? (((obfuscatedBytes.gzip - originalBytes.gzip) / originalBytes.gzip) * 100).toFixed(2)
: '0.00';

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}%)`;
}
Expand Down