SvelteRunner/bin/runner.js
2025-01-10 00:46:31 -05:00

61 lines
1.8 KiB
JavaScript

import express from 'express';
import compression from 'compression';
import { join, resolve } from 'path';
import { pathToFileURL } from 'url';
export default class WebServer {
app;
port = process.env.PORT || 3000;
constructor() {
this.app = express();
}
static async create(location) {
const server = new WebServer();
await server.initialize(location);
return server;
}
async initialize(location) {
try {
// Ensure location is absolute
const absolutePath = resolve(location);
console.log('Initializing server with path:', absolutePath);
this.app.use(compression());
// For SvelteKit adapter-node, we need to import the handler first
const handlerUrl = pathToFileURL(join(absolutePath, 'handler.js'));
console.log('Loading SvelteKit handler from:', handlerUrl.href);
try {
// Import the SvelteKit handler
const { handler } = await import(handlerUrl.href);
if (!handler) {
throw new Error('SvelteKit handler not found in the build output');
}
// In adapter-node, the handler includes both static file serving and the app logic
this.app.use(handler);
// Start the server
return new Promise((resolve, reject) => {
const server = this.app.listen(this.port, () => {
console.log(`Server running at http://localhost:${this.port}`);
resolve(server);
}).on('error', (error) => {
console.error('Failed to start server:', error);
reject(error);
});
});
} catch (error) {
console.error('Failed to load SvelteKit handler:', error);
throw error;
}
} catch (error) {
console.error('Server initialization failed:', error);
throw error;
}
}
}