const { WasmAnalyzerBuilder } = require('../pkg/webpage_quality_analyzer.js');
async function loadFromJson() {
console.log('\n=== Method 1: Load from JSON String ===\n');
const configJson = JSON.stringify({
active_profile: "news",
presets: {
news: {
metadata: {
name: "News Article",
description: "Optimized for news content"
},
category_weights: {
content: 1.5,
seo: 1.8,
technical: 1.2,
authority: 2.0
},
content_expectations: {
min_word_count: 500,
max_word_count: 2000,
min_heading_count: 3,
min_image_count: 1
}
}
}
});
try {
const analyzer = WasmAnalyzerBuilder.fromConfigJson(configJson);
console.log('✅ Analyzer created from JSON config');
const html = `
<!DOCTYPE html>
<html>
<head><title>Breaking News</title></head>
<body>
<h1>Major Event Happens</h1>
<p>This is a news article with some content...</p>
</body>
</html>
`;
const report = await analyzer.analyze(html);
console.log(`Score: ${report.score}`);
console.log(`Verdict: ${report.verdict}`);
} catch (error) {
console.error('❌ Error:', error);
}
}
async function loadFromYaml() {
console.log('\n=== Method 2: Load from YAML String ===\n');
const configYaml = `
active_profile: content_article
presets:
content_article:
metadata:
name: "Content Article"
description: "Optimized for blog posts and articles"
category_weights:
content: 2.0
seo: 1.5
technical: 1.0
readability: 1.8
content_expectations:
min_word_count: 800
max_word_count: 3000
min_heading_count: 4
min_paragraph_count: 5
`;
try {
const analyzer = WasmAnalyzerBuilder.fromConfigYaml(configYaml);
console.log('✅ Analyzer created from YAML config');
const html = `
<!DOCTYPE html>
<html>
<head>
<title>How to Use WASM Configuration</title>
<meta name="description" content="A comprehensive guide">
</head>
<body>
<h1>Guide to Configuration</h1>
<h2>Introduction</h2>
<p>First paragraph of content...</p>
<h2>Setup</h2>
<p>Second paragraph with more details...</p>
<h2>Usage</h2>
<p>Third paragraph explaining usage...</p>
<h2>Conclusion</h2>
<p>Final thoughts and summary...</p>
</body>
</html>
`;
const report = await analyzer.analyze(html);
console.log(`Score: ${report.score}`);
console.log(`Word Count: ${report.metrics.content_metrics.word_count}`);
} catch (error) {
console.error('❌ Error:', error);
}
}
async function loadFromToml() {
console.log('\n=== Method 3: Load from TOML String ===\n');
const configToml = `
active_profile = "product"
[presets.product]
[presets.product.metadata]
name = "Product Page"
description = "E-commerce product pages"
[presets.product.category_weights]
content = 1.5
seo = 1.5
technical = 1.2
business = 2.5
media = 2.0
[presets.product.content_expectations]
min_word_count = 200
max_word_count = 1000
min_image_count = 3
`;
try {
const analyzer = WasmAnalyzerBuilder.fromConfigToml(configToml);
console.log('✅ Analyzer created from TOML config');
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Premium Widget - $49.99</title>
<meta name="description" content="Buy our amazing widget">
</head>
<body>
<h1>Premium Widget</h1>
<img src="product1.jpg" alt="Widget front view">
<img src="product2.jpg" alt="Widget side view">
<img src="product3.jpg" alt="Widget in use">
<p>Product description and features...</p>
<button>Add to Cart</button>
</body>
</html>
`;
const report = await analyzer.analyze(html);
console.log(`Score: ${report.score}`);
console.log(`Image Count: ${report.metrics.media_metrics.image_count}`);
} catch (error) {
console.error('❌ Error:', error);
}
}
async function loadFromServer() {
console.log('\n=== Method 4: Fetch Config from Server ===\n');
const serverConfig = JSON.stringify({
active_profile: "blog",
presets: {
blog: {
metadata: {
name: "Blog Post",
description: "Personal blog content"
},
category_weights: {
content: 2.0,
readability: 1.8,
seo: 1.3
}
}
}
});
try {
await new Promise(resolve => setTimeout(resolve, 100));
const analyzer = WasmAnalyzerBuilder.fromConfigJson(serverConfig);
console.log('✅ Analyzer created from server config');
console.log(' (Simulated fetch from server)');
} catch (error) {
console.error('❌ Error:', error);
}
}
async function loadFromEmbeddedConfig() {
console.log('\n=== Method 5: Embedded Config in JavaScript ===\n');
const config = {
active_profile: "homepage",
presets: {
homepage: {
metadata: {
name: "Homepage",
description: "Website landing page"
},
category_weights: {
content: 1.2,
seo: 1.5,
technical: 1.5,
user_experience: 2.0,
performance: 1.8
},
content_expectations: {
min_word_count: 300,
max_word_count: 1500,
min_heading_count: 2,
min_link_count: 5
}
}
}
};
try {
const configJson = JSON.stringify(config);
const analyzer = WasmAnalyzerBuilder.fromConfigJson(configJson);
console.log('✅ Analyzer created from embedded config');
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Our Site</title>
<meta name="description" content="Your trusted partner">
</head>
<body>
<h1>Welcome</h1>
<p>We provide excellent services...</p>
<nav>
<a href="/about">About</a>
<a href="/services">Services</a>
<a href="/contact">Contact</a>
</nav>
</body>
</html>
`;
const report = await analyzer.analyze(html);
console.log(`Score: ${report.score}`);
} catch (error) {
console.error('❌ Error:', error);
}
}
async function typescriptExample() {
console.log('\n=== Method 6: TypeScript Usage Example ===\n');
console.log('TypeScript code example:');
console.log(`
import { WasmAnalyzerBuilder, PageQualityReport } from 'webpage-quality-analyzer';
interface AnalyzerConfig {
active_profile: string;
presets: Record<string, any>;
}
async function analyzeWithConfig(html: string, config: AnalyzerConfig): Promise<PageQualityReport> {
const configJson = JSON.stringify(config);
const analyzer = WasmAnalyzerBuilder.fromConfigJson(configJson);
return await analyzer.analyze(html);
}
// Usage
const config: AnalyzerConfig = {
active_profile: "news",
presets: { news: { category_weights: { content: 2.0 } } }
};
const report = await analyzeWithConfig(htmlContent, config);
console.log(\`Score: \${report.score}\`);
`);
}
async function errorHandlingExamples() {
console.log('\n=== Error Handling Examples ===\n');
try {
const analyzer = WasmAnalyzerBuilder.fromConfigJson('{ invalid json }');
} catch (error) {
console.log('✅ Caught invalid JSON error:', error.toString().substring(0, 60) + '...');
}
try {
const config = JSON.stringify({
active_profile: "nonexistent_profile",
presets: {}
});
const analyzer = WasmAnalyzerBuilder.fromConfigJson(config);
} catch (error) {
console.log('✅ Caught invalid profile error:', error.toString().substring(0, 60) + '...');
}
try {
const analyzer = WasmAnalyzerBuilder.fromConfigYaml('invalid: : yaml:');
} catch (error) {
console.log('✅ Caught invalid YAML error:', error.toString().substring(0, 60) + '...');
}
}
async function main() {
console.log('╔════════════════════════════════════════════════════════════╗');
console.log('║ WASM Configuration Loading Demo ║');
console.log('║ Alternative to from_config_file() for browsers ║');
console.log('╚════════════════════════════════════════════════════════════╝');
await loadFromJson();
await loadFromYaml();
await loadFromToml();
await loadFromServer();
await loadFromEmbeddedConfig();
await typescriptExample();
await errorHandlingExamples();
console.log('\n✅ All examples completed!\n');
console.log('📚 Key Takeaways:');
console.log(' 1. Use fromConfigJson() for JSON configurations');
console.log(' 2. Use fromConfigYaml() for YAML configurations');
console.log(' 3. Use fromConfigToml() for TOML configurations');
console.log(' 4. Fetch configs from server using fetch API');
console.log(' 5. Embed configs directly in JavaScript/TypeScript');
console.log(' 6. All methods return configured WasmAnalyzer instances');
console.log(' 7. No file system access needed - works in all WASM environments');
}
if (require.main === module) {
main().catch(console.error);
}
module.exports = {
loadFromJson,
loadFromYaml,
loadFromToml,
loadFromServer,
loadFromEmbeddedConfig
};