Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 5x 29x 29x 29x 29x 29x 29x 29x 9x 9x 9x 9x 9x 9x 9x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 46x 46x 46x 29x 9x 4x 4x | /**
* Runtime Scaffolding Generator
* Generates server setup code for different runtime environments
*/
import { getCLIVersion } from '../utils/version.js';
// Get current CLI version automatically
const cliVersion = getCLIVersion();
/**
* Generate built-in HTTP server setup
*/
export function generateBuiltInServer(options = {}) {
const { port = 3000, hasApi = false, hasDatabase = false, hasAuth = false } = options;
const imports = [
`import http from 'node:http';`,
`import fs from 'node:fs';`,
`import path from 'node:path';`,
`import { render } from '@coherent.js/core';`
];
if (hasApi) imports.push(`import { setupRoutes } from './api/routes.js';`);
if (hasDatabase) imports.push(`import { initDatabase } from './db/index.js';`);
if (hasAuth) imports.push(`import { setupAuthRoutes } from './api/auth.js';`);
const server = `
${imports.join('\n')}
import { HomePage } from './components/HomePage.js';
const PORT = process.env.PORT || ${port};
${hasDatabase ? `// Initialize database
await initDatabase();
` : ''}${hasApi ? `// Setup API routes
const apiRoutes = setupRoutes();
` : ''}${hasAuth ? `// Setup auth routes
const authRoutes = setupAuthRoutes();
` : ''}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, \`http://\${req.headers.host}\`);
${hasApi || hasAuth ? ` // Handle API routes
if (url.pathname.startsWith('/api')) {
const allRoutes = [...${hasApi ? 'apiRoutes' : '[]'}, ...${hasAuth ? 'authRoutes' : '[]'}];
for (const route of allRoutes) {
const match = matchRoute(route.path, url.pathname, req.method, route.method);
if (match) {
req.params = match.params;
return route.handler(req, res);
}
}
}
` : ''} // Serve components for hydration
if (url.pathname.startsWith('/components/')) {
const filePath = path.join(process.cwd(), 'src', url.pathname);
try {
const content = await fs.promises.readFile(filePath);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
return res.end(content);
} catch (err) {
res.writeHead(404);
return res.end('Not Found');
}
}
// Serve static files
if (url.pathname.startsWith('/public')) {
const filePath = path.join(process.cwd(), url.pathname);
try {
const content = await fs.promises.readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
const contentTypes = {
'.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'
};
res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'application/octet-stream' });
return res.end(content);
} catch (err) {
res.writeHead(404);
return res.end('Not Found');
}
}
// Render page
try {
const html = render(HomePage({}));
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(\`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coherent.js App</title>
</head>
<body>
\${html}
</body>
</html>\`);
} catch (error) {
console.error('Render error:', error);
res.writeHead(500);
res.end('Internal Server Error');
}
});
// Route matching helper
function matchRoute(routePattern, urlPath, requestMethod, routeMethod) {
// Check HTTP method
if (requestMethod !== routeMethod) {
return null;
}
// Split paths into segments
const routeSegments = routePattern.split('/').filter(Boolean);
const urlSegments = urlPath.split('/').filter(Boolean);
// Check if lengths match
if (routeSegments.length !== urlSegments.length) {
return null;
}
const params = {};
// Match each segment
for (let i = 0; i < routeSegments.length; i++) {
const routeSegment = routeSegments[i];
const urlSegment = urlSegments[i];
// Check for parameter (e.g., :id)
if (routeSegment.startsWith(':')) {
const paramName = routeSegment.substring(1);
params[paramName] = urlSegment;
} else if (routeSegment !== urlSegment) {
// Literal segment doesn't match
return null;
}
}
return { params };
}
server.listen(PORT, () => {
console.log(\`Server running at http://localhost:\${PORT}\`);
});
`;
return server;
}
/**
* Generate Express server setup
*/
export function generateExpressServer(options = {}) {
const { port = 3000, hasApi = false, hasDatabase = false, hasAuth = false } = options;
const imports = [
`import express from 'express';`,
`import { render } from '@coherent.js/core';`
];
if (hasApi) imports.push(`import apiRoutes from './api/routes.js';`);
if (hasDatabase) imports.push(`import { initDatabase } from './db/index.js';`);
if (hasAuth) imports.push(`import { authMiddleware } from './middleware/auth.js';`);
const server = `
${imports.join('\n')}
import { HomePage } from './components/HomePage.js';
const app = express();
const PORT = process.env.PORT || ${port};
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
${hasDatabase ? `// Initialize database
await initDatabase();
` : ''}${hasAuth ? `// Setup authentication
app.use(authMiddleware);
` : ''}
${hasApi ? `// API routes - convert Coherent.js router to Express middleware
app.use('/api', apiRoutes.toExpressRouter(express));
` : ''}
// Main route - render Coherent.js component to HTML
app.get('/', (req, res) => {
const content = render(HomePage({}));
const html = \`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coherent.js App</title>
</head>
<body>
\${content}
</body>
</html>\`;
res.type('html').send(html);
});
// Error handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(PORT, () => {
console.log(\`Server running at http://localhost:\${PORT}\`);
});
`;
return server;
}
/**
* Generate Fastify server setup
*/
export function generateFastifyServer(options = {}) {
const { port = 3000, hasApi = false, hasDatabase = false, hasAuth = false } = options;
const imports = [
`import Fastify from 'fastify';`,
`import { setupCoherent } from '@coherent.js/fastify';`
];
if (hasApi) imports.push(`import apiRoutes from './api/routes.js';`);
if (hasDatabase) imports.push(`import { initDatabase } from './db/index.js';`);
if (hasAuth) imports.push(`import { authPlugin } from './plugins/auth.js';`);
const server = `
${imports.join('\n')}
import { HomePage } from './components/HomePage.js';
const fastify = Fastify({
logger: true
});
${hasDatabase ? `// Initialize database
await initDatabase();
` : ''}${hasAuth ? `// Register auth plugin
await fastify.register(authPlugin);
` : ''}
// Setup Coherent.js
await fastify.register(setupCoherent);
// Serve static files
await fastify.register(import('@fastify/static'), {
root: new URL('./public', import.meta.url).pathname,
prefix: '/public/'
});
${hasApi ? `// API routes
await fastify.register(apiRoutes, { prefix: '/api' });
` : ''}
// Main route - return Coherent.js component (auto-rendered by plugin)
fastify.get('/', async (request, reply) => {
return HomePage({});
});
// Start server
try {
await fastify.listen({ port: process.env.PORT || ${port} });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
`;
return server;
}
/**
* Generate Koa server setup
*/
export function generateKoaServer(options = {}) {
const { port = 3000, hasApi = false, hasDatabase = false, hasAuth = false } = options;
const imports = [
`import Koa from 'koa';`,
`import Router from '@koa/router';`,
`import { koaBody } from 'koa-body';`,
`import serve from 'koa-static';`,
`import { setupCoherent } from '@coherent.js/koa';`
];
if (hasApi) imports.push(`import apiRoutes from './api/routes.js';`);
if (hasDatabase) imports.push(`import { initDatabase } from './db/index.js';`);
if (hasAuth) imports.push(`import { authMiddleware } from './middleware/auth.js';`);
const server = `
${imports.join('\n')}
import { HomePage } from './components/HomePage.js';
const app = new Koa();
const router = new Router();
const PORT = process.env.PORT || ${port};
${hasDatabase ? `// Initialize database
await initDatabase();
` : ''}
// Middleware
app.use(koaBody());
app.use(serve('./public'));
${hasAuth ? `app.use(authMiddleware);
` : ''}
// Setup Coherent.js
setupCoherent(app);
${hasApi ? `// API routes
apiRoutes(router);
` : ''}
// Main route - set body to Coherent.js component (auto-rendered by middleware)
router.get('/', async (ctx) => {
ctx.body = HomePage({});
});
app.use(router.routes());
app.use(router.allowedMethods());
// Error handling
app.on('error', (err, ctx) => {
console.error('Server error:', err, ctx);
});
app.listen(PORT, () => {
console.log(\`Server running at http://localhost:\${PORT}\`);
});
`;
return server;
}
/**
* Get runtime-specific dependencies
*/
export function getRuntimeDependencies(runtime) {
const deps = {
'built-in': {},
express: {
express: '^4.19.2',
'@coherent.js/express': `^${cliVersion}`
},
fastify: {
fastify: '^4.28.1',
'@fastify/static': '^7.0.4',
'@coherent.js/fastify': `^${cliVersion}`
},
koa: {
koa: '^2.15.3',
'@koa/router': '^13.0.1',
'koa-body': '^6.0.1',
'koa-static': '^5.0.0',
'@coherent.js/koa': `^${cliVersion}`
}
};
return deps[runtime] || {};
}
/**
* Generate server file based on runtime
*/
export function generateServerFile(runtime, options = {}) {
switch (runtime) {
case 'built-in':
return generateBuiltInServer(options);
case 'express':
return generateExpressServer(options);
case 'fastify':
return generateFastifyServer(options);
case 'koa':
return generateKoaServer(options);
default:
throw new Error(`Unknown runtime: ${runtime}`);
}
}
|