-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathdev-server.js
More file actions
138 lines (118 loc) · 3.93 KB
/
Copy pathdev-server.js
File metadata and controls
138 lines (118 loc) · 3.93 KB
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
#!/usr/bin/env node
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Configuration
const config = {
httpPort: process.env.HTTP_PORT || 8080,
host: process.env.HOST || 'localhost',
distDir: path.join(__dirname, 'dist')
};
// MIME types
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.webmanifest': 'application/manifest+json'
};
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
return mimeTypes[ext] || 'application/octet-stream';
}
function requestHandler(req, res) {
// Parse URL and remove query parameters
let urlPath = new URL(req.url, `http://${req.headers.host}`).pathname;
// Default to index.html for root requests
if (urlPath === '/') {
urlPath = '/index.html';
}
const filePath = path.join(config.distDir, urlPath);
const mimeType = getMimeType(filePath);
// Security check - ensure file is within dist directory
if (!filePath.startsWith(config.distDir)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
// Set CORS headers for development
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Disable caching for development
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
// Handle OPTIONS requests
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
// Try to serve index.html for SPA routing
const indexPath = path.join(config.distDir, 'index.html');
fs.readFile(indexPath, (indexErr, indexData) => {
if (indexErr) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(indexData);
}
});
} else {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
}
} else {
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
}
});
}
function startServer() {
// Check if dist directory exists
if (!fs.existsSync(config.distDir)) {
console.error(`❌ Dist directory not found: ${config.distDir}`);
console.log('💡 Run "npm run build" first to build the application');
process.exit(1);
}
const server = http.createServer(requestHandler);
server.listen(config.httpPort, config.host, () => {
console.log('🚀 Development server started!');
console.log(`📱 App running at: http://${config.host}:${config.httpPort}`);
console.log('💡 WebHID works here because localhost is a secure context');
console.log('💡 Press Ctrl+C to stop the server');
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`❌ Port ${config.httpPort} is already in use`);
console.log('💡 Try using a different port: HTTP_PORT=8081 npm run serve');
} else {
console.error('❌ Server error:', err.message);
}
process.exit(1);
});
}
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\n👋 Shutting down development server...');
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n👋 Shutting down development server...');
process.exit(0);
});
// Start the server
startServer();