File size: 1,391 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { readFile } from "node:fs/promises";
import { gzipSync } from "node:zlib";
import { errorLine, outputLine } from "./io.mjs";

const bundlePath = process.argv[2] || "dist/worker.js";
const defaultLimitBytes = 3 * 1024 * 1024;
const limitBytes = parseLimit(
	process.env.BUNDLE_GZIP_SIZE_LIMIT_BYTES,
	defaultLimitBytes,
);

try {
	const bundle = await readFile(bundlePath);
	if (bundle.length <= 0) {
		fail(`${bundlePath} is missing or empty`);
	}
	const gzipBytes = gzipSync(bundle, { level: 9 }).length;
	if (gzipBytes > limitBytes) {
		fail(
			`${bundlePath} gzip size is ${formatBytes(gzipBytes)}, limit ${formatBytes(limitBytes)}`,
		);
	}
	outputLine(
		`bundle size ok: ${bundlePath} raw ${formatBytes(bundle.length)}, gzip ${formatBytes(gzipBytes)} <= ${formatBytes(limitBytes)}, headroom ${formatBytes(limitBytes - gzipBytes)}`,
	);
} catch (error) {
	if (
		error &&
		typeof error === "object" &&
		"code" in error &&
		error.code === "ENOENT"
	) {
		fail(`${bundlePath} does not exist; run pnpm build first`);
	}
	throw error;
}

function parseLimit(value, fallback) {
	if (value == null || value === "") return fallback;
	const n = Number(value);
	return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
}

function formatBytes(bytes) {
	return `${bytes} bytes`;
}

function fail(message) {
	errorLine(`Bundle size gate failed: ${message}`);
	process.exit(1);
}