slicejs-cli 2.8.5 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,270 +1,260 @@
1
- // commands/startServer/startServer.js - MEJORADO CON VALIDACIÓN Y FEEDBACK
2
-
3
- import bundle from '../bundle/bundle.js';
4
- import fs from 'fs-extra';
5
- import path from 'path';
6
- import { fileURLToPath } from 'url';
7
- import { spawn } from 'child_process';
8
- import { createServer } from 'net';
9
- import setupWatcher, { stopWatcher } from './watchServer.js';
10
- import Print from '../Print.js';
11
- import { getConfigPath, getApiPath, getSrcPath, getDistPath } from '../utils/PathHelper.js';
12
-
13
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
-
15
- /**
16
- * Carga la configuración desde sliceConfig.json
17
- */
18
- const loadConfig = () => {
19
- try {
20
- const configPath = getConfigPath(import.meta.url);
21
- const rawData = fs.readFileSync(configPath, 'utf-8');
22
- return JSON.parse(rawData);
23
- } catch (error) {
24
- Print.error(`Loading configuration: ${error.message}`);
25
- return null;
26
- }
27
- };
28
-
29
- /**
30
- * Verifica si un puerto está disponible
31
- */
32
- async function isPortAvailable(port) {
33
- return new Promise((resolve) => {
34
- const server = createServer();
35
-
36
- server.once('error', (err) => {
37
- if (err.code === 'EADDRINUSE') {
38
- resolve(false);
39
- } else {
40
- resolve(false);
41
- }
42
- });
43
-
44
- server.once('listening', () => {
45
- server.close();
46
- resolve(true);
47
- });
48
-
49
- server.listen(port);
50
- });
51
- }
52
-
53
- /**
54
- * Verifica si existe un build de producción
55
- */
56
- async function checkProductionBuild() {
57
- const distDir = getDistPath(import.meta.url);
58
- return await fs.pathExists(distDir);
59
- }
60
-
61
- /**
62
- * Verifica si existe la estructura de desarrollo
63
- */
64
- async function checkDevelopmentStructure() {
65
- const srcDir = getSrcPath(import.meta.url);
66
- const apiDir = getApiPath(import.meta.url);
67
-
68
- return (await fs.pathExists(srcDir)) && (await fs.pathExists(apiDir));
69
- }
70
-
71
- /**
72
- * Inicia el servidor Node.js con argumentos y mejor feedback
73
- */
74
- function startNodeServer(port, mode) {
75
- return new Promise((resolve, reject) => {
76
- const apiIndexPath = getApiPath(import.meta.url, 'index.js');
77
-
78
- // Verificar que el archivo existe
79
- if (!fs.existsSync(apiIndexPath)) {
80
- reject(new Error(`Server file not found: ${apiIndexPath}`));
81
- return;
82
- }
83
-
84
- Print.serverStatus('starting', 'Starting server...');
85
-
86
- // Construir argumentos basados en el modo
87
- const args = [apiIndexPath];
88
- if (mode === 'production') {
89
- args.push('--production');
90
- } else if (mode === 'bundled') {
91
- args.push('--bundled');
92
- } else {
93
- args.push('--development');
94
- }
95
-
96
- const serverProcess = spawn('node', args, {
97
- stdio: ['inherit', 'pipe', 'pipe'],
98
- env: {
99
- ...process.env,
100
- PORT: port
101
- }
102
- });
103
-
104
- let serverStarted = false;
105
- let outputBuffer = '';
106
-
107
- // Capturar la salida para detectar cuando el servidor está listo
108
- serverProcess.stdout.on('data', (data) => {
109
- const output = data.toString();
110
- outputBuffer += output;
111
-
112
- // Detectar mensajes comunes que indican que el servidor ha iniciado
113
- if (!serverStarted && (
114
- output.includes('Server running') ||
115
- output.includes('listening on') ||
116
- output.includes('Started on') ||
117
- output.includes(`port ${port}`)
118
- )) {
119
- serverStarted = true;
120
- Print.serverReady(port);
121
- }
122
-
123
- // Mostrar la salida del servidor
124
- process.stdout.write(output);
125
- });
126
-
127
- serverProcess.stderr.on('data', (data) => {
128
- const output = data.toString();
129
- process.stderr.write(output);
130
- });
131
-
132
- serverProcess.on('error', (error) => {
133
- if (!serverStarted) {
134
- Print.serverStatus('error', `Failed to start server: ${error.message}`);
135
- reject(error);
136
- }
137
- });
138
-
139
- serverProcess.on('exit', (code, signal) => {
140
- if (code !== null && code !== 0 && !serverStarted) {
141
- reject(new Error(`Server exited with code ${code}`));
142
- }
143
- });
144
-
145
- // Manejar Ctrl+C
146
- process.on('SIGINT', () => {
147
- Print.newLine();
148
- Print.info('Shutting down server...');
149
- serverProcess.kill('SIGINT');
150
- setTimeout(() => {
151
- process.exit(0);
152
- }, 100);
153
- });
154
-
155
- process.on('SIGTERM', () => {
156
- serverProcess.kill('SIGTERM');
157
- });
158
-
159
- // Si después de 3 segundos no detectamos inicio, asumimos que está listo
160
- setTimeout(() => {
161
- if (!serverStarted) {
162
- serverStarted = true;
163
- Print.serverReady(port);
164
- }
165
- resolve(serverProcess);
166
- }, 3000);
167
- });
168
- }
169
-
170
- /**
171
- * Función principal para iniciar servidor
172
- */
173
- export default async function startServer(options = {}) {
174
- const config = loadConfig();
175
- const defaultPort = config?.server?.port || 3000;
176
-
177
- const { mode = 'development', port = defaultPort, watch = false, bundled = false } = options;
178
-
179
- try {
180
- Print.title(`🚀 Starting Slice.js ${mode} server...`);
181
- Print.newLine();
182
-
183
- // Verificar estructura del proyecto
184
- if (!await checkDevelopmentStructure()) {
185
- throw new Error('Project structure not found. Run "slice init" first.');
186
- }
187
-
188
- let actualPort = await isPortAvailable(port) ? port : port + 1; // Try one more port
189
- if(actualPort !== port) {
190
- // Check if the fallback is available
191
- const fallbackAvailable = await isPortAvailable(actualPort);
192
- if(!fallbackAvailable) {
193
- throw new Error(`Ports ${port} and ${actualPort} are in use.`);
194
- }
195
- Print.info(`ℹ️ Port ${port} in use, using ${actualPort} instead.`);
196
- }
197
-
198
- Print.serverStatus('checking', `Port ${actualPort} available ✓`);
199
- Print.newLine();
200
-
201
- if (mode === 'production') {
202
- // Verificar que existe build de producción
203
- if (!await checkProductionBuild()) {
204
- throw new Error('No production build found. Run "slice build" first.');
205
- }
206
- Print.info('Production mode: serving optimized files from /dist');
207
- } else if (mode === 'bundled') {
208
- Print.info('Bundled mode: serving with generated bundles for optimized loading');
209
- } else {
210
- Print.info('Development mode: serving files from /src with hot reload');
211
- }
212
-
213
- Print.newLine();
214
-
215
- // Iniciar el servidor con argumentos
216
- let serverProcess = await startNodeServer(actualPort, mode);
217
-
218
- // Configurar watch mode si está habilitado
219
- if (watch) {
220
- Print.newLine();
221
- const watcher = setupWatcher(serverProcess, async (changedPath) => {
222
- if (serverProcess) {
223
- serverProcess.kill();
224
- }
225
-
226
- // Short delay to ensure port is freed
227
- await new Promise(r => setTimeout(r, 500));
228
-
229
- try {
230
- // If we are in bundled mode, regenerate bundles before restarting
231
- if (mode === 'bundled') {
232
- Print.info('🔄 File changed. Regenerating bundles...');
233
- try {
234
- await bundle({ verbose: false });
235
- } catch (err) {
236
- Print.error('Bundle generation failed during watch restart');
237
- console.error(err);
238
- // We continue restarting anyway to show error in browser if possible,
239
- // or maybe just to keep process alive.
240
- }
241
- } else {
242
- Print.info('🔄 File changed. Restarting server...');
243
- }
244
-
245
- serverProcess = await startNodeServer(actualPort, mode);
246
- } catch (e) {
247
- Print.error(`Failed to restart server: ${e.message}`);
248
- }
249
- });
250
-
251
- // Cleanup en exit
252
- const cleanup = () => {
253
- stopWatcher(watcher);
254
- };
255
-
256
- process.on('SIGINT', cleanup);
257
- process.on('SIGTERM', cleanup);
258
- }
259
-
260
- } catch (error) {
261
- Print.newLine();
262
- Print.error(error.message);
263
- throw error;
264
- }
265
- }
266
-
267
- /**
268
- * Funciones de utilidad exportadas
269
- */
270
- export { checkProductionBuild, checkDevelopmentStructure, isPortAvailable };
1
+ // commands/startServer/startServer.js - MEJORADO CON VALIDACIÓN Y FEEDBACK
2
+
3
+ import fs from 'fs-extra';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { spawn } from 'child_process';
7
+ import { createServer } from 'net';
8
+ import setupWatcher, { stopWatcher } from './watchServer.js';
9
+ import Print from '../Print.js';
10
+ import { getConfigPath, getApiPath, getSrcPath, getDistPath } from '../utils/PathHelper.js';
11
+ import build from '../build/build.js';
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+
15
+ /**
16
+ * Carga la configuración desde sliceConfig.json
17
+ */
18
+ const loadConfig = () => {
19
+ try {
20
+ const configPath = getConfigPath(import.meta.url);
21
+ const rawData = fs.readFileSync(configPath, 'utf-8');
22
+ return JSON.parse(rawData);
23
+ } catch (error) {
24
+ Print.error(`Loading configuration: ${error.message}`);
25
+ return null;
26
+ }
27
+ };
28
+
29
+ /**
30
+ * Verifica si un puerto está disponible
31
+ */
32
+ async function isPortAvailable(port) {
33
+ return new Promise((resolve) => {
34
+ const server = createServer();
35
+
36
+ server.once('error', (err) => {
37
+ if (err.code === 'EADDRINUSE') {
38
+ resolve(false);
39
+ } else {
40
+ resolve(false);
41
+ }
42
+ });
43
+
44
+ server.once('listening', () => {
45
+ server.close();
46
+ resolve(true);
47
+ });
48
+
49
+ server.listen(port);
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Verifica si existe un build de producción
55
+ */
56
+ async function checkProductionBuild() {
57
+ const distDir = getDistPath(import.meta.url);
58
+ const bundleConfigPath = path.join(distDir, 'bundles', 'bundle.config.json');
59
+ return (await fs.pathExists(distDir)) && (await fs.pathExists(bundleConfigPath));
60
+ }
61
+
62
+ /**
63
+ * Verifica si existe la estructura de desarrollo
64
+ */
65
+ async function checkDevelopmentStructure() {
66
+ const srcDir = getSrcPath(import.meta.url);
67
+ const apiDir = getApiPath(import.meta.url);
68
+
69
+ return (await fs.pathExists(srcDir)) && (await fs.pathExists(apiDir));
70
+ }
71
+
72
+ /**
73
+ * Inicia el servidor Node.js con argumentos y mejor feedback
74
+ */
75
+ function startNodeServer(port, mode) {
76
+ return new Promise((resolve, reject) => {
77
+ const apiIndexPath = getApiPath(import.meta.url, 'index.js');
78
+
79
+ // Verificar que el archivo existe
80
+ if (!fs.existsSync(apiIndexPath)) {
81
+ reject(new Error(`Server file not found: ${apiIndexPath}`));
82
+ return;
83
+ }
84
+
85
+ Print.serverStatus('starting', 'Starting server...');
86
+
87
+ // Construir argumentos basados en el modo
88
+ const args = [apiIndexPath];
89
+ if (mode === 'production') {
90
+ args.push('--production');
91
+ } else if (mode === 'bundled') {
92
+ args.push('--bundled');
93
+ } else {
94
+ args.push('--development');
95
+ }
96
+
97
+ const serverProcess = spawn('node', args, {
98
+ stdio: ['inherit', 'pipe', 'pipe'],
99
+ env: {
100
+ ...process.env,
101
+ PORT: port
102
+ }
103
+ });
104
+
105
+ let serverStarted = false;
106
+ let outputBuffer = '';
107
+
108
+ // Capturar la salida para detectar cuando el servidor está listo
109
+ serverProcess.stdout.on('data', (data) => {
110
+ const output = data.toString();
111
+ outputBuffer += output;
112
+
113
+ // Detectar mensajes comunes que indican que el servidor ha iniciado
114
+ if (!serverStarted && (
115
+ output.includes('Server running') ||
116
+ output.includes('listening on') ||
117
+ output.includes('Started on') ||
118
+ output.includes(`port ${port}`)
119
+ )) {
120
+ serverStarted = true;
121
+ Print.serverReady(port);
122
+ }
123
+
124
+ // Mostrar la salida del servidor
125
+ process.stdout.write(output);
126
+ });
127
+
128
+ serverProcess.stderr.on('data', (data) => {
129
+ const output = data.toString();
130
+ process.stderr.write(output);
131
+ });
132
+
133
+ serverProcess.on('error', (error) => {
134
+ if (!serverStarted) {
135
+ Print.serverStatus('error', `Failed to start server: ${error.message}`);
136
+ reject(error);
137
+ }
138
+ });
139
+
140
+ serverProcess.on('exit', (code, signal) => {
141
+ if (code !== null && code !== 0 && !serverStarted) {
142
+ reject(new Error(`Server exited with code ${code}`));
143
+ }
144
+ });
145
+
146
+ // Manejar Ctrl+C
147
+ process.on('SIGINT', () => {
148
+ Print.newLine();
149
+ Print.info('Shutting down server...');
150
+ serverProcess.kill('SIGINT');
151
+ setTimeout(() => {
152
+ process.exit(0);
153
+ }, 100);
154
+ });
155
+
156
+ process.on('SIGTERM', () => {
157
+ serverProcess.kill('SIGTERM');
158
+ });
159
+
160
+ // Si después de 3 segundos no detectamos inicio, asumimos que está listo
161
+ setTimeout(() => {
162
+ if (!serverStarted) {
163
+ serverStarted = true;
164
+ Print.serverReady(port);
165
+ }
166
+ resolve(serverProcess);
167
+ }, 3000);
168
+ });
169
+ }
170
+
171
+ /**
172
+ * Función principal para iniciar servidor
173
+ */
174
+ export default async function startServer(options = {}) {
175
+ const config = loadConfig();
176
+ const defaultPort = config?.server?.port || 3000;
177
+
178
+ const { mode = 'development', port = defaultPort, watch = false } = options;
179
+
180
+ try {
181
+ Print.title(`🚀 Starting Slice.js ${mode} server...`);
182
+ Print.newLine();
183
+
184
+ // Verificar estructura del proyecto
185
+ if (!await checkDevelopmentStructure()) {
186
+ throw new Error('Project structure not found. Run "slice init" first.');
187
+ }
188
+
189
+ let actualPort = await isPortAvailable(port) ? port : port + 1; // Try one more port
190
+ if(actualPort !== port) {
191
+ // Check if the fallback is available
192
+ const fallbackAvailable = await isPortAvailable(actualPort);
193
+ if(!fallbackAvailable) {
194
+ throw new Error(`Ports ${port} and ${actualPort} are in use.`);
195
+ }
196
+ Print.info(`ℹ️ Port ${port} in use, using ${actualPort} instead.`);
197
+ }
198
+
199
+ Print.serverStatus('checking', `Port ${actualPort} available ✓`);
200
+ Print.newLine();
201
+
202
+ if (mode === 'production') {
203
+ // Verificar que existe build de producción
204
+ if (!await checkProductionBuild()) {
205
+ Print.info('No production build found. Running "slice build"...');
206
+ const success = await build({});
207
+ if (!success) {
208
+ throw new Error('Build failed. Cannot start production server.');
209
+ }
210
+ }
211
+ Print.info('Production mode: serving optimized files from /dist');
212
+ } else {
213
+ Print.info('Development mode: serving files from /src with hot reload');
214
+ }
215
+
216
+ Print.newLine();
217
+
218
+ // Iniciar el servidor con argumentos
219
+ let serverProcess = await startNodeServer(actualPort, mode);
220
+
221
+ // Configurar watch mode si está habilitado
222
+ if (watch) {
223
+ Print.newLine();
224
+ const watcher = setupWatcher(serverProcess, async (changedPath) => {
225
+ if (serverProcess) {
226
+ serverProcess.kill();
227
+ }
228
+
229
+ // Short delay to ensure port is freed
230
+ await new Promise(r => setTimeout(r, 500));
231
+
232
+ try {
233
+ Print.info('🔄 File changed. Restarting server...');
234
+
235
+ serverProcess = await startNodeServer(actualPort, mode);
236
+ } catch (e) {
237
+ Print.error(`Failed to restart server: ${e.message}`);
238
+ }
239
+ });
240
+
241
+ // Cleanup en exit
242
+ const cleanup = () => {
243
+ stopWatcher(watcher);
244
+ };
245
+
246
+ process.on('SIGINT', cleanup);
247
+ process.on('SIGTERM', cleanup);
248
+ }
249
+
250
+ } catch (error) {
251
+ Print.newLine();
252
+ Print.error(error.message);
253
+ throw error;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Funciones de utilidad exportadas
259
+ */
260
+ export { checkProductionBuild, checkDevelopmentStructure, isPortAvailable };