Spaces:
Runtime error
Runtime error
File size: 17,959 Bytes
fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 d0ea8bd fe3c808 d0ea8bd fe3c808 d0ea8bd fe3c808 fa54e05 e0a756c fa54e05 d0ea8bd 63f0830 e0a756c fe3c808 fa54e05 fe3c808 e0a756c fe3c808 e0a756c fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 fa54e05 fe3c808 63f0830 fa54e05 | 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | #!/usr/bin/env node
const express = require('express');
const path = require('path');
const cors = require('cors');
const fs = require('fs').promises;
const DemoStreamingService = require('./demo-streaming');
const SpacesStorageManager = require('./storage-manager');
const app = express();
const PORT = process.env.PORT || 3000;
const IS_SPACES = process.env.IS_SPACES === 'true';
const WORKSPACE_DIR = process.env.WORKSPACE_DIR || './demo-sessions';
// Initialize services
const streamingService = new DemoStreamingService();
const storageManager = new SpacesStorageManager(WORKSPACE_DIR);
// Hugging Face Spaces optimized middleware
if (IS_SPACES) {
// Trust proxy for Spaces environment
app.set('trust proxy', true);
// Add Spaces-specific headers and force HTTPS
app.use((req, res, next) => {
// Force HTTPS redirect in Spaces
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`);
return;
}
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Powered-By', 'Doc-less API Agent on Spaces');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
}
// Enhanced CORS configuration for Spaces
const corsOptions = {
origin: IS_SPACES ? true : (process.env.CORS_ORIGIN || '*'),
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
credentials: false
};
app.use(cors(corsOptions));
// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Serve static files with proper headers
app.use(express.static('.', {
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
} else if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
} else if (path.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css; charset=utf-8');
} else if (path.endsWith('.json')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
} else if (path.endsWith('.md')) {
res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
} else if (path.endsWith('.yaml') || path.endsWith('.yml')) {
res.setHeader('Content-Type', 'text/yaml; charset=utf-8');
}
// Cache static assets appropriately
if (path.includes('demo-output') || path.includes('deliverables')) {
res.setHeader('Cache-Control', 'public, max-age=300'); // 5 minutes
} else {
res.setHeader('Cache-Control', 'no-cache');
}
}
}));
// Main route - serve the demo interface
app.get('/', (req, res) => {
try {
console.log(`π± Serving demo interface to ${req.ip} - User Agent: ${req.get('User-Agent')?.substring(0, 50)}...`);
// Add headers for better compatibility
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
// Send the file with error handling
res.sendFile(path.join(__dirname, 'demo-interface.html'), (err) => {
if (err) {
console.error('β Error serving demo interface:', err);
res.status(500).send(`
<!DOCTYPE html>
<html>
<head><title>Doc-less API Agent</title></head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h1>π€ Doc-less API Agent</h1>
<p>Demo interface is loading...</p>
<p>Server Status: β
Running</p>
<p>Environment: ${IS_SPACES ? 'Hugging Face Spaces' : 'Local'}</p>
<p>Port: ${PORT}</p>
<p>Time: ${new Date().toISOString()}</p>
<a href="/health">Health Check</a> |
<a href="/test">Test Endpoint</a> |
<a href="/api/status">API Status</a>
</body>
</html>
`);
}
});
} catch (error) {
console.error('β Fatal error in main route:', error);
res.status(500).json({
error: 'Internal Server Error',
message: 'Unable to serve demo interface',
timestamp: new Date().toISOString()
});
}
});
app.get('/favicon.ico', (req, res) => {
res.status(204).end();
});
// Simple test route for debugging
app.get('/test', (req, res) => {
console.log(`π§ͺ Test endpoint accessed from ${req.ip}`);
res.json({
status: 'success',
message: 'Doc-less API Agent is working!',
timestamp: new Date().toISOString(),
environment: IS_SPACES ? 'Hugging Face Spaces' : 'Local',
port: PORT,
uptime: process.uptime()
});
});
// Debug page for troubleshooting
app.get('/debug', (req, res) => {
console.log(`π§ Debug page accessed from ${req.ip}`);
res.sendFile(path.join(__dirname, 'debug.html'));
});
// Health check endpoint with detailed information
app.get('/health', async (req, res) => {
const health = {
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: IS_SPACES ? 'spaces' : 'local',
port: PORT,
version: process.env.npm_package_version || '1.0.0',
memory: process.memoryUsage(),
workspace: WORKSPACE_DIR,
request_info: {
ip: req.ip,
user_agent: req.get('User-Agent'),
headers: req.headers
},
services: {
streaming: {
active_sessions: streamingService.getActiveSessionsCount(),
active_streams: streamingService.getActiveStreamsCount()
},
storage: await storageManager.getStorageStats()
}
};
// Check workspace directory
try {
await fs.access(WORKSPACE_DIR);
health.workspace_accessible = true;
} catch (error) {
health.workspace_accessible = false;
health.workspace_error = error.message;
}
// Add CORS headers for health check
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET');
res.setHeader('Cache-Control', 'no-cache');
console.log(`π₯ Health check from ${req.ip} - Status: ${health.status}`);
res.json(health);
});
// Spaces-specific metadata endpoint
app.get('/spaces/info', (req, res) => {
res.json({
title: 'π€ Doc-less API Agent',
description: 'Interactive API documentation and SDK generator demo',
version: '1.0.0',
features: [
'Live API Discovery',
'OpenAPI Generation',
'TypeScript SDK Creation',
'Postman Collections',
'Mock Lab Environment',
'Evidence Reports',
'Real-time Demo Streaming'
],
demo_paths: [
'/ - Interactive Demo Interface',
'/api/status - Service Status',
'/api/demo/stream - Live Demo Stream',
'/deliverables - Generated Files',
'/spaces/info - This Information'
],
github: 'https://github.com/ysrastogi/apiWitness',
is_spaces: IS_SPACES,
uptime: process.uptime()
});
});
// Server-Sent Events endpoint for real-time demo streaming
app.get('/api/demo/stream', streamingService.createSSEEndpoint());
// API endpoints for demo integration
app.get('/api/status', async (req, res) => {
const status = {
services: {
main_server: `http://localhost:${PORT}`,
demo_interface: `http://localhost:${PORT}/`,
deliverables: `http://localhost:${PORT}/deliverables`,
demo_stream: `http://localhost:${PORT}/api/demo/stream`
},
environment: {
is_spaces: IS_SPACES,
workspace: WORKSPACE_DIR,
node_env: process.env.NODE_ENV || 'development'
},
demo: {
interface_url: `http://localhost:${PORT}`,
deliverables_url: `http://localhost:${PORT}/deliverables`,
health_check: `http://localhost:${PORT}/health`,
streaming_url: `http://localhost:${PORT}/api/demo/stream`
},
streaming: {
active_sessions: streamingService.getActiveSessionsCount(),
active_streams: streamingService.getActiveStreamsCount()
},
timestamp: new Date().toISOString()
};
// Check if demo assets exist
try {
const demoOutputs = await fs.readdir('.', { withFileTypes: true });
const demoFolders = demoOutputs
.filter(dirent => dirent.isDirectory() && dirent.name.startsWith('demo-output-'))
.map(dirent => dirent.name);
status.available_demos = demoFolders;
} catch (error) {
status.demo_scan_error = error.message;
}
res.json(status);
});
// Demo session management for Spaces
app.post('/api/demo/start', async (req, res) => {
try {
const { sessionId, config = {} } = req.body;
const finalSessionId = sessionId || `demo-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
// Create storage session
const session = await storageManager.createSession(finalSessionId);
// Start streaming demo
const demoConfig = streamingService.startDemoSession(finalSessionId, {
delays: config.delays !== false, // Default to true
realExecution: config.realExecution || false,
...config
});
console.log(`π¬ Demo started: ${finalSessionId}`);
res.json({
sessionId: finalSessionId,
session,
demoConfig,
streamUrl: `/api/demo/stream?sessionId=${finalSessionId}`
});
} catch (error) {
console.error('β Error starting demo:', error);
res.status(500).json({ error: error.message });
}
});
// Get demo session status
app.get('/api/demo/:sessionId/status', (req, res) => {
const { sessionId } = req.params;
const status = streamingService.getSessionStatus(sessionId);
if (status) {
res.json(status);
} else {
res.status(404).json({ error: 'Session not found' });
}
});
// Save demo result file
app.post('/api/demo/:sessionId/save', async (req, res) => {
try {
const { sessionId } = req.params;
const { fileName, content, metadata } = req.body;
if (!fileName || content === undefined) {
return res.status(400).json({ error: 'fileName and content are required' });
}
const filePath = await storageManager.saveFile(sessionId, fileName, content, metadata);
res.json({
success: true,
fileName,
path: filePath,
sessionId
});
} catch (error) {
console.error('β Error saving file:', error);
res.status(500).json({ error: error.message });
}
});
// Get demo session files
app.get('/api/demo/:sessionId/files', async (req, res) => {
try {
const { sessionId } = req.params;
const session = await storageManager.getSession(sessionId);
if (!session) {
return res.status(404).json({ error: 'Session not found' });
}
res.json({
sessionId,
files: session.files || []
});
} catch (error) {
console.error('β Error getting session files:', error);
res.status(500).json({ error: error.message });
}
});
// Get specific file from session
app.get('/api/demo/:sessionId/files/:fileName', async (req, res) => {
try {
const { sessionId, fileName } = req.params;
const content = await storageManager.getFile(sessionId, fileName);
if (content === null) {
return res.status(404).json({ error: 'File not found' });
}
// Set appropriate content type
if (fileName.endsWith('.json')) {
res.setHeader('Content-Type', 'application/json');
} else if (fileName.endsWith('.md')) {
res.setHeader('Content-Type', 'text/markdown');
} else if (fileName.endsWith('.yaml') || fileName.endsWith('.yml')) {
res.setHeader('Content-Type', 'text/yaml');
} else if (fileName.endsWith('.ts')) {
res.setHeader('Content-Type', 'text/typescript');
}
res.send(content);
} catch (error) {
console.error('β Error getting file:', error);
res.status(500).json({ error: error.message });
}
});
// Serve deliverables directory with better error handling
app.use('/deliverables', express.static('demo-output-*', {
setHeaders: (res, path) => {
res.setHeader('Access-Control-Allow-Origin', '*');
if (path.endsWith('.json')) {
res.setHeader('Content-Type', 'application/json');
} else if (path.endsWith('.md')) {
res.setHeader('Content-Type', 'text/markdown');
} else if (path.endsWith('.yaml') || path.endsWith('.yml')) {
res.setHeader('Content-Type', 'text/yaml');
}
}
}));
// Serve static demo outputs if available
app.get('/demo-assets/:asset', async (req, res) => {
const asset = req.params.asset;
try {
// Look for the asset in any demo-output directory
const dirs = await fs.readdir('.');
const demoDir = dirs.find(dir => dir.startsWith('demo-output-'));
if (demoDir) {
const assetPath = path.join(demoDir, asset);
await fs.access(assetPath);
res.sendFile(path.resolve(assetPath));
} else {
res.status(404).json({ error: 'Demo assets not found' });
}
} catch (error) {
console.error(`β Error serving asset ${asset}:`, error);
res.status(404).json({ error: 'Asset not found' });
}
});
// Analytics endpoint (privacy-compliant)
app.post('/api/analytics', (req, res) => {
const { event, category, label, value } = req.body;
// Log analytics data (can be enhanced to send to analytics service)
console.log(`π Analytics: ${category}/${event}`, {
label,
value,
timestamp: new Date().toISOString(),
ip: req.ip,
userAgent: req.get('User-Agent')
});
res.json({ status: 'logged' });
});
// Storage management endpoints
app.get('/api/storage/stats', async (req, res) => {
try {
const stats = await storageManager.getStorageStats();
res.json(stats);
} catch (error) {
console.error('β Error getting storage stats:', error);
res.status(500).json({ error: error.message });
}
});
app.post('/api/storage/cleanup', async (req, res) => {
try {
const deletedCount = await storageManager.cleanup();
res.json({ success: true, deleted: deletedCount });
} catch (error) {
console.error('β Error during cleanup:', error);
res.status(500).json({ error: error.message });
}
});
// 404 handler - redirect to demo interface for SPA behavior
app.use((req, res) => {
console.log(`π 404 for ${req.path}, redirecting to demo interface`);
res.status(404).sendFile(path.join(__dirname, 'demo-interface.html'));
});
// Enhanced error handler
app.use((error, req, res, next) => {
console.error('β Server Error:', {
message: error.message,
stack: error.stack,
url: req.url,
method: req.method,
timestamp: new Date().toISOString()
});
res.status(error.status || 500).json({
error: IS_SPACES ? 'Internal Server Error' : error.message,
timestamp: new Date().toISOString(),
path: req.path
});
});
// Graceful shutdown handling
process.on('SIGTERM', () => {
console.log('π SIGTERM received, shutting down gracefully');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('π SIGINT received, shutting down gracefully');
process.exit(0);
});
// Start server
app.listen(PORT, '0.0.0.0', () => {
console.log(`π Doc-less API Agent ${IS_SPACES ? '(Spaces)' : '(Local)'} running on:`);
console.log(` Local: http://localhost:${PORT}`);
console.log(` Network: http://0.0.0.0:${PORT}`);
console.log(` Health: http://localhost:${PORT}/health`);
console.log(` API: http://localhost:${PORT}/api/status`);
console.log(` Stream: http://localhost:${PORT}/api/demo/stream`);
console.log(` Info: http://localhost:${PORT}/spaces/info`);
console.log('');
console.log('π Serving files from:', __dirname);
console.log('πΎ Workspace directory:', WORKSPACE_DIR);
console.log('π― Environment:', IS_SPACES ? 'Hugging Face Spaces' : 'Local Development');
console.log(`π₯ Streaming service: ${streamingService.getActiveSessionsCount()} active sessions`);
// Initialize storage manager after server starts
console.log('πΎ Storage manager initialized:', WORKSPACE_DIR);
console.log('β° Cleanup timer started (every 60 minutes)');
});
module.exports = app;
|