@pierrad/web-carbon-analyzer
Version:
A tool to measure the carbon footprint of websites using CO2.js
232 lines • 9.21 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Carbon Footprint Analyzer CLI
* Command-line interface for analyzing website carbon footprints
*/
const commander_1 = require("commander");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const lib_1 = require("../lib");
const logger_1 = __importDefault(require("../lib/utils/logger"));
// Get package.json for version information
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf8'));
// Setup CLI
commander_1.program
.name('carbon-analyzer')
.description('Analyze the carbon footprint of websites using CO2.js')
.version(packageJson.version)
.option('-u, --url <url>', 'URL to analyze')
.option('-o, --output <file>', 'Output file path')
.option('-f, --format <format>', 'Output format (json)', 'json')
.option('-t, --timeout <ms>', 'Page load timeout in milliseconds', parseInt)
.option('-w, --wait <ms>', 'Wait time for network idle in milliseconds', parseInt)
.option('-m, --model <model>', 'CO2 calculation model (swd, 1byte)', 'swd')
.option('-s, --scroll-depth <number>', 'Number of page heights to scroll', parseInt)
.option('-v, --verbose', 'Enable verbose logging')
.option('-q, --quiet', 'Suppress console output')
.option('--detailed', 'Include detailed resource breakdown in output')
.option('--no-headless', 'Run browser in non-headless mode')
.option('--viewport <size>', 'Viewport size (e.g., 1920x1080)')
.option('--user-agent <string>', 'Custom user agent string')
.option('--cookies <file>', 'Path to JSON file containing cookies')
.option('--htaccess-username <username>', 'Username for htaccess authentication')
.option('--htaccess-password <password>', 'Password for htaccess authentication')
.option('--no-green-hosting-check', 'Disable green hosting checks')
// Lighthouse options
.option('--lighthouse', 'Enable Lighthouse audit')
.option('--lighthouse-port <port>', 'Port for Lighthouse to use for Chrome remote debugging', parseInt)
.option('--lighthouse-performance-threshold <threshold>', 'Minimum acceptable Lighthouse performance score (0-100)', parseInt)
.option('--lighthouse-accessibility-threshold <threshold>', 'Minimum acceptable Lighthouse accessibility score (0-100)', parseInt)
.option('--lighthouse-best-practices-threshold <threshold>', 'Minimum acceptable Lighthouse best practices score (0-100)', parseInt)
.option('--lighthouse-seo-threshold <threshold>', 'Minimum acceptable Lighthouse SEO score (0-100)', parseInt);
commander_1.program.parse();
const options = commander_1.program.opts();
// Validate required options
if (!options.url) {
console.error('Error: URL is required');
commander_1.program.help();
process.exit(1);
}
// Configure logging based on options
if (options.verbose) {
logger_1.default.level = 'debug';
}
else if (options.quiet) {
logger_1.default.level = 'error';
}
/**
* Convert CLI options to analyzer configuration
* @param options CLI options
* @returns Analyzer configuration
*/
function createConfigFromOptions(options) {
// Create browser config with required fields
const browserConfig = {
type: 'chromium', // Default browser type
headless: options.headless !== false,
timeout: options.timeout || 30000,
networkIdleTimeout: options.wait || 5000,
waitForNetworkIdle: true,
viewport: { width: 1920, height: 1080 } // Default viewport
};
// Set user agent if provided
if (options.userAgent) {
browserConfig.userAgent = options.userAgent;
}
// Set htaccess authentication if provided
if (options.htaccessUsername && options.htaccessPassword) {
browserConfig.httpCredentials = {
username: options.htaccessUsername,
password: options.htaccessPassword
};
}
// Parse viewport if provided
if (options.viewport) {
const [width, height] = options.viewport.split('x').map(Number);
if (width && height) {
browserConfig.viewport = { width, height };
}
}
// Create user behavior config
const userBehaviorConfig = {
scrollDepth: options.scrollDepth || 3,
scrollDelay: 500, // Default scroll delay
maxScrollTime: 10000 // Default max scroll time
};
// Create CO2 config
const co2Config = {
model: options.model || 'swd',
includeGreenHostingCheck: options.greenHostingCheck !== false
};
// Create output config
const outputConfig = {
format: options.format || 'json',
includeResourceDetails: options.detailed || true,
includeComparisons: true
};
// Create logging config
const loggingConfig = {
level: options.verbose ? 'debug' : (options.quiet ? 'error' : 'info'),
console: true,
file: false,
filePath: ''
};
// Create the complete config object with all required fields
const config = {
browser: browserConfig,
userBehavior: userBehaviorConfig,
co2: co2Config,
output: outputConfig,
logging: loggingConfig
};
// Add lighthouse configuration if enabled
if (options.lighthouse) {
// Create lighthouse config
config.lighthouse = {
enabled: true,
port: options.lighthousePort || 9222,
thresholds: {
performance: options.lighthousePerformanceThreshold || 0,
accessibility: options.lighthouseAccessibilityThreshold || 0,
'best-practices': options.lighthouseBestPracticesThreshold || 0,
seo: options.lighthouseSeoThreshold || 0
}
};
// If we're using lighthouse, make sure we're using chromium with remote debugging port
if (config.browser) {
config.browser.type = 'chromium';
config.browser.remoteDebuggingPort = options.lighthousePort || 9222;
}
}
return config;
}
/**
* Run the analyzer with CLI options
* @param url URL to analyze
* @param options CLI options
*/
async function runCLI(url, options) {
try {
// Create configuration from CLI options
const config = createConfigFromOptions(options);
// Create the analyzer
const analyzer = new lib_1.CarbonFootprintAnalyzer(config);
// Load cookies if provided
if (options.cookies) {
try {
await analyzer.loadCookies(options.cookies);
}
catch (error) {
logger_1.default.error(`Failed to load cookies: ${error.message}`);
}
}
// Run analysis
const results = await analyzer.analyze(url);
// Format results based on output option
const output = JSON.stringify(results, null, 2);
// Output results
if (options.output) {
const outputDir = path.dirname(options.output);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
fs.writeFileSync(options.output, output);
logger_1.default.info(`Results written to ${options.output}`);
}
else {
console.log(output);
}
return results;
}
catch (error) {
logger_1.default.error(`Analysis failed: ${error.message}`);
throw error;
}
}
// Execute main function
runCLI(options.url, options)
.then(() => {
process.exit(0);
})
.catch((error) => {
process.exit(1);
});
//# sourceMappingURL=index.js.map