create-fluxstack 1.7.5 → 1.8.1

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.
Files changed (39) hide show
  1. package/.dockerignore +82 -0
  2. package/Dockerfile +70 -0
  3. package/app/server/app.ts +20 -5
  4. package/app/server/backend-only.ts +15 -12
  5. package/app/server/index.ts +83 -96
  6. package/app/server/live/FluxStackConfig.ts +5 -5
  7. package/app/server/routes/env-test.ts +59 -0
  8. package/config/app.config.ts +2 -54
  9. package/config/client.config.ts +95 -0
  10. package/config/index.ts +57 -22
  11. package/config/monitoring.config.ts +114 -0
  12. package/config/plugins.config.ts +59 -0
  13. package/config/runtime.config.ts +0 -17
  14. package/config/server.config.ts +50 -30
  15. package/core/build/bundler.ts +17 -16
  16. package/core/build/flux-plugins-generator.ts +29 -18
  17. package/core/build/index.ts +32 -31
  18. package/core/build/live-components-generator.ts +29 -18
  19. package/core/build/optimizer.ts +37 -17
  20. package/core/cli/index.ts +6 -2
  21. package/core/config/env.ts +4 -0
  22. package/core/config/runtime-config.ts +10 -8
  23. package/core/config/schema.ts +24 -2
  24. package/core/framework/server.ts +1 -0
  25. package/core/index.ts +31 -23
  26. package/core/plugins/built-in/static/index.ts +73 -246
  27. package/core/plugins/built-in/vite/index.ts +377 -377
  28. package/core/plugins/registry.ts +22 -18
  29. package/core/server/backend-entry.ts +51 -0
  30. package/core/types/plugin.ts +6 -0
  31. package/core/utils/build-logger.ts +324 -0
  32. package/core/utils/config-schema.ts +2 -6
  33. package/core/utils/helpers.ts +14 -9
  34. package/core/utils/regenerate-files.ts +69 -0
  35. package/core/utils/version.ts +1 -1
  36. package/fluxstack.config.ts +138 -252
  37. package/package.json +2 -17
  38. package/vitest.config.ts +8 -26
  39. package/config/build.config.ts +0 -24
@@ -1,378 +1,378 @@
1
- import type { FluxStack, PluginContext, RequestContext } from "../../types"
2
- import { createServer, type ViteDevServer } from 'vite'
3
- import { FLUXSTACK_VERSION } from "../../../utils/version"
4
-
5
- type Plugin = FluxStack.Plugin
6
-
7
- let viteServer: ViteDevServer | null = null
8
-
9
- export const vitePlugin: Plugin = {
10
- name: "vite",
11
- version: FLUXSTACK_VERSION,
12
- description: "Enhanced Vite integration plugin for FluxStack with improved error handling and monitoring",
13
- author: "FluxStack Team",
14
- priority: 800, // Should run early to setup proxying
15
- category: "development",
16
- tags: ["vite", "development", "hot-reload"],
17
- dependencies: [], // No dependencies
18
-
19
- configSchema: {
20
- type: "object",
21
- properties: {
22
- enabled: {
23
- type: "boolean",
24
- description: "Enable Vite integration"
25
- },
26
- port: {
27
- type: "number",
28
- minimum: 1,
29
- maximum: 65535,
30
- description: "Vite development server port"
31
- },
32
- host: {
33
- type: "string",
34
- description: "Vite development server host"
35
- },
36
- checkInterval: {
37
- type: "number",
38
- minimum: 100,
39
- description: "Interval to check if Vite is running (ms)"
40
- },
41
- maxRetries: {
42
- type: "number",
43
- minimum: 1,
44
- description: "Maximum retries to connect to Vite"
45
- },
46
- timeout: {
47
- type: "number",
48
- minimum: 100,
49
- description: "Timeout for Vite requests (ms)"
50
- },
51
- proxyPaths: {
52
- type: "array",
53
- items: { type: "string" },
54
- description: "Paths to proxy to Vite (defaults to all non-API paths)"
55
- },
56
- excludePaths: {
57
- type: "array",
58
- items: { type: "string" },
59
- description: "Paths to exclude from Vite proxying"
60
- }
61
- },
62
- additionalProperties: false
63
- },
64
-
65
- defaultConfig: {
66
- enabled: true,
67
- port: 5173,
68
- host: "localhost",
69
- checkInterval: 2000,
70
- maxRetries: 10,
71
- timeout: 5000,
72
- proxyPaths: [],
73
- excludePaths: []
74
- },
75
-
76
- setup: async (context: PluginContext) => {
77
- const config = getPluginConfig(context)
78
-
79
- if (!config.enabled || !context.config.client) {
80
- context.logger.debug('Vite plugin disabled or no client configuration found')
81
- return
82
- }
83
-
84
- const vitePort = config.port || context.config.client.port || 5173
85
- const viteHost = config.host || "localhost"
86
-
87
- try {
88
- const { startGroup, endGroup, logInGroup } = await import('../../../utils/logger/group-logger')
89
-
90
- startGroup({
91
- title: 'Vite Development Server',
92
- icon: '🎨',
93
- color: 'magenta',
94
- collapsed: true
95
- })
96
-
97
- logInGroup(`Starting on ${viteHost}:${vitePort}`, '📍')
98
-
99
- // Start Vite dev server programmatically
100
- viteServer = await createServer({
101
- configFile: './vite.config.ts',
102
- // Don't override root - let vite.config.ts handle it
103
- server: {
104
- port: vitePort,
105
- host: viteHost,
106
- strictPort: true
107
- },
108
- logLevel: 'warn' // Suppress Vite's verbose logs
109
- })
110
-
111
- await viteServer.listen()
112
-
113
- // Custom URL display instead of viteServer.printUrls()
114
- logInGroup(`Local: http://${viteHost}:${vitePort}/`, '✅')
115
- logInGroup('Hot reload coordination active', '🔄')
116
-
117
- endGroup()
118
- console.log('') // Separator line
119
-
120
- // Store Vite config in context for later use
121
- ; (context as any).viteConfig = {
122
- port: vitePort,
123
- host: viteHost,
124
- ...config,
125
- server: viteServer
126
- }
127
-
128
- // Setup cleanup on process exit
129
- const cleanup = async () => {
130
- if (viteServer) {
131
- context.logger.debug('🛑 Stopping Vite server...')
132
- await viteServer.close()
133
- viteServer = null
134
- }
135
- }
136
-
137
- process.on('SIGINT', cleanup)
138
- process.on('SIGTERM', cleanup)
139
- process.on('exit', cleanup)
140
-
141
- } catch (error) {
142
- context.logger.error('❌ Failed to start Vite server programmatically:', error)
143
- context.logger.debug('⚠️ Falling back to monitoring mode...')
144
-
145
- // Fallback to monitoring if programmatic start fails
146
- ; (context as any).viteConfig = {
147
- port: vitePort,
148
- host: viteHost,
149
- ...config
150
- }
151
- monitorVite(context, viteHost, vitePort, config)
152
- }
153
- },
154
-
155
- onServerStart: async (context: PluginContext) => {
156
- const config = getPluginConfig(context)
157
- const viteConfig = (context as any).viteConfig
158
-
159
- if (config.enabled && viteConfig) {
160
- context.logger.debug(`Vite integration active - monitoring ${viteConfig.host}:${viteConfig.port}`)
161
- }
162
- },
163
-
164
- onBeforeRoute: async (requestContext: RequestContext) => {
165
- // Skip API routes and swagger - let them be handled by backend
166
- if (requestContext.path.startsWith("/api") || requestContext.path.startsWith("/swagger")) {
167
- return
168
- }
169
-
170
- // For Vite internal routes, proxy directly to Vite server
171
- if (requestContext.path.startsWith("/@") || // All Vite internal routes (/@vite/, /@fs/, /@react-refresh, etc.)
172
- requestContext.path.startsWith("/__vite") || // Vite HMR and dev routes
173
- requestContext.path.startsWith("/node_modules") || // Direct node_modules access
174
- requestContext.path.includes("/.vite/") || // Vite cache and deps
175
- requestContext.path.endsWith(".js.map") || // Source maps
176
- requestContext.path.endsWith(".css.map")) { // CSS source maps
177
-
178
- // Use fixed configuration for Vite proxy
179
- const viteHost = "localhost"
180
- const vitePort = 5173
181
-
182
- try {
183
- const url = new URL(requestContext.request.url)
184
- const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
185
-
186
- // Forward request to Vite
187
- const response = await fetch(viteUrl, {
188
- method: requestContext.method,
189
- headers: requestContext.headers,
190
- body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
191
- })
192
-
193
- // Return the Vite response
194
- const body = await response.arrayBuffer()
195
-
196
- requestContext.handled = true
197
- requestContext.response = new Response(body, {
198
- status: response.status,
199
- statusText: response.statusText,
200
- headers: response.headers
201
- })
202
-
203
- } catch (viteError) {
204
- // If Vite fails, let the request continue to normal routing (will become 404)
205
- // Only log if explicitly enabled for debugging
206
- const { serverConfig } = await import('@/config/server.config')
207
- if (serverConfig.enableViteProxyLogs) {
208
- console.warn(`Vite proxy error: ${viteError}`)
209
- }
210
- }
211
- return
212
- }
213
-
214
- // Use fixed configuration for simplicity - Vite should be running on port 5173
215
- const viteHost = "localhost"
216
- const vitePort = 5173
217
-
218
- try {
219
- const url = new URL(requestContext.request.url)
220
- const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
221
-
222
- // Forward request to Vite
223
- const response = await fetch(viteUrl, {
224
- method: requestContext.method,
225
- headers: requestContext.headers,
226
- body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
227
- })
228
-
229
- // If Vite responds successfully, handle the request
230
- if (response.ok || response.status < 500) {
231
- // Return a proper Response object with all headers and status
232
- const body = await response.arrayBuffer()
233
-
234
- requestContext.handled = true
235
- requestContext.response = new Response(body, {
236
- status: response.status,
237
- statusText: response.statusText,
238
- headers: response.headers
239
- })
240
- }
241
-
242
- } catch (viteError) {
243
- // If Vite fails, let the request continue to normal routing (will become 404)
244
- // Only log if explicitly enabled for debugging
245
- const { serverConfig } = await import('@/config/server.config')
246
- if (serverConfig.enableViteProxyLogs) {
247
- console.warn(`Vite proxy error: ${viteError}`)
248
- }
249
- }
250
- }
251
- }
252
-
253
- // Helper function to get plugin config
254
- function getPluginConfig(context: PluginContext) {
255
- const pluginConfig = context.config.plugins.config?.vite || {}
256
- return { ...vitePlugin.defaultConfig, ...pluginConfig }
257
- }
258
-
259
- // Monitor Vite server status with automatic port detection
260
- async function monitorVite(
261
- context: PluginContext,
262
- host: string,
263
- initialPort: number,
264
- config: any
265
- ) {
266
- let retries = 0
267
- let isConnected = false
268
- let actualPort = initialPort
269
- let portDetected = false
270
-
271
- const checkVite = async () => {
272
- try {
273
- // If we haven't found the correct port yet, try to detect it
274
- if (!portDetected) {
275
- const detectedPort = await detectVitePort(host, initialPort)
276
- if (detectedPort !== null) {
277
- actualPort = detectedPort
278
- portDetected = true
279
- // Update the context with the detected port
280
- if ((context as any).viteConfig) {
281
- ; (context as any).viteConfig.port = actualPort
282
- }
283
- }
284
- }
285
-
286
- const isRunning = await checkViteRunning(host, actualPort, config.timeout)
287
-
288
- if (isRunning && !isConnected) {
289
- isConnected = true
290
- retries = 0
291
- if (actualPort !== initialPort) {
292
- context.logger.debug(`✓ Vite server detected on ${host}:${actualPort} (auto-detected from port ${initialPort})`)
293
- } else {
294
- context.logger.debug(`✓ Vite server detected on ${host}:${actualPort}`)
295
- }
296
- context.logger.debug("Hot reload coordination active")
297
- } else if (!isRunning && isConnected) {
298
- isConnected = false
299
- context.logger.warn(`✗ Vite server disconnected from ${host}:${actualPort}`)
300
- // Reset port detection when disconnected
301
- portDetected = false
302
- actualPort = initialPort
303
- } else if (!isRunning) {
304
- retries++
305
- if (retries <= config.maxRetries) {
306
- if (portDetected) {
307
- context.logger.debug(`Waiting for Vite server on ${host}:${actualPort}... (${retries}/${config.maxRetries})`)
308
- } else {
309
- context.logger.debug(`Detecting Vite server port... (${retries}/${config.maxRetries})`)
310
- }
311
- } else if (retries === config.maxRetries + 1) {
312
- context.logger.warn(`Vite server not found after ${config.maxRetries} attempts. Development features may be limited.`)
313
- }
314
- }
315
- } catch (error) {
316
- if (isConnected) {
317
- context.logger.error('Error checking Vite server status', { error })
318
- }
319
- }
320
-
321
- // Continue monitoring
322
- setTimeout(checkVite, config.checkInterval)
323
- }
324
-
325
- // Start monitoring after a brief delay
326
- setTimeout(checkVite, 1000)
327
- }
328
-
329
- // Auto-detect Vite port by trying common ports
330
- async function detectVitePort(host: string, startPort: number): Promise<number | null> {
331
- // Try the initial port first, then common alternatives
332
- const portsToTry = [
333
- startPort,
334
- startPort + 1,
335
- startPort + 2,
336
- startPort + 3,
337
- 5174, // Common Vite alternative
338
- 5175,
339
- 5176,
340
- 3000, // Sometimes Vite might use this
341
- 4173 // Another common alternative
342
- ]
343
-
344
- for (const port of portsToTry) {
345
- try {
346
- const isRunning = await checkViteRunning(host, port, 1000)
347
- if (isRunning) {
348
- return port
349
- }
350
- } catch (error) {
351
- // Continue trying other ports
352
- }
353
- }
354
-
355
- return null
356
- }
357
-
358
- // Check if Vite is running
359
- async function checkViteRunning(host: string, port: number, timeout: number = 1000): Promise<boolean> {
360
- try {
361
- const controller = new AbortController()
362
- const timeoutId = setTimeout(() => controller.abort(), timeout)
363
-
364
- const response = await fetch(`http://${host}:${port}`, {
365
- signal: controller.signal,
366
- method: 'HEAD' // Use HEAD to minimize data transfer
367
- })
368
-
369
- clearTimeout(timeoutId)
370
- return response.status >= 200 && response.status < 500
371
- } catch (error) {
372
- return false
373
- }
374
- }
375
-
376
- // Note: Proxy logic is now handled directly in the onBeforeRoute hook above
377
-
1
+ import type { FluxStack, PluginContext, RequestContext } from "../../types"
2
+ import { createServer, type ViteDevServer } from 'vite'
3
+ import { FLUXSTACK_VERSION } from "../../../utils/version"
4
+
5
+ type Plugin = FluxStack.Plugin
6
+
7
+ let viteServer: ViteDevServer | null = null
8
+
9
+ export const vitePlugin: Plugin = {
10
+ name: "vite",
11
+ version: FLUXSTACK_VERSION,
12
+ description: "Enhanced Vite integration plugin for FluxStack with improved error handling and monitoring",
13
+ author: "FluxStack Team",
14
+ priority: 800, // Should run early to setup proxying
15
+ category: "development",
16
+ tags: ["vite", "development", "hot-reload"],
17
+ dependencies: [], // No dependencies
18
+
19
+ configSchema: {
20
+ type: "object",
21
+ properties: {
22
+ enabled: {
23
+ type: "boolean",
24
+ description: "Enable Vite integration"
25
+ },
26
+ port: {
27
+ type: "number",
28
+ minimum: 1,
29
+ maximum: 65535,
30
+ description: "Vite development server port"
31
+ },
32
+ host: {
33
+ type: "string",
34
+ description: "Vite development server host"
35
+ },
36
+ checkInterval: {
37
+ type: "number",
38
+ minimum: 100,
39
+ description: "Interval to check if Vite is running (ms)"
40
+ },
41
+ maxRetries: {
42
+ type: "number",
43
+ minimum: 1,
44
+ description: "Maximum retries to connect to Vite"
45
+ },
46
+ timeout: {
47
+ type: "number",
48
+ minimum: 100,
49
+ description: "Timeout for Vite requests (ms)"
50
+ },
51
+ proxyPaths: {
52
+ type: "array",
53
+ items: { type: "string" },
54
+ description: "Paths to proxy to Vite (defaults to all non-API paths)"
55
+ },
56
+ excludePaths: {
57
+ type: "array",
58
+ items: { type: "string" },
59
+ description: "Paths to exclude from Vite proxying"
60
+ }
61
+ },
62
+ additionalProperties: false
63
+ },
64
+
65
+ defaultConfig: {
66
+ enabled: true,
67
+ port: 5173,
68
+ host: "localhost",
69
+ checkInterval: 2000,
70
+ maxRetries: 10,
71
+ timeout: 5000,
72
+ proxyPaths: [],
73
+ excludePaths: []
74
+ },
75
+
76
+ setup: async (context: PluginContext) => {
77
+ const config = getPluginConfig(context)
78
+
79
+ if (!config.enabled || !context.config.client) {
80
+ context.logger.debug('Vite plugin disabled or no client configuration found')
81
+ return
82
+ }
83
+
84
+ const vitePort = config.port || context.config.client.port || 5173
85
+ const viteHost = config.host || "localhost"
86
+
87
+ try {
88
+ const { startGroup, endGroup, logInGroup } = await import('../../../utils/logger/group-logger')
89
+
90
+ startGroup({
91
+ title: 'Vite Development Server',
92
+ icon: '🎨',
93
+ color: 'magenta',
94
+ collapsed: true
95
+ })
96
+
97
+ logInGroup(`Starting on ${viteHost}:${vitePort}`, '📍')
98
+
99
+ // Start Vite dev server programmatically
100
+ viteServer = await createServer({
101
+ configFile: './vite.config.ts',
102
+ // Don't override root - let vite.config.ts handle it
103
+ server: {
104
+ port: vitePort,
105
+ host: viteHost,
106
+ strictPort: true
107
+ },
108
+ logLevel: 'warn' // Suppress Vite's verbose logs
109
+ })
110
+
111
+ await viteServer.listen()
112
+
113
+ // Custom URL display instead of viteServer.printUrls()
114
+ logInGroup(`Local: http://${viteHost}:${vitePort}/`, '✅')
115
+ logInGroup('Hot reload coordination active', '🔄')
116
+
117
+ endGroup()
118
+ console.log('') // Separator line
119
+
120
+ // Store Vite config in context for later use
121
+ ; (context as any).viteConfig = {
122
+ port: vitePort,
123
+ host: viteHost,
124
+ ...config,
125
+ server: viteServer
126
+ }
127
+
128
+ // Setup cleanup on process exit
129
+ const cleanup = async () => {
130
+ if (viteServer) {
131
+ context.logger.debug('🛑 Stopping Vite server...')
132
+ await viteServer.close()
133
+ viteServer = null
134
+ }
135
+ }
136
+
137
+ process.on('SIGINT', cleanup)
138
+ process.on('SIGTERM', cleanup)
139
+ process.on('exit', cleanup)
140
+
141
+ } catch (error) {
142
+ context.logger.error('❌ Failed to start Vite server programmatically:', error)
143
+ context.logger.debug('⚠️ Falling back to monitoring mode...')
144
+
145
+ // Fallback to monitoring if programmatic start fails
146
+ ; (context as any).viteConfig = {
147
+ port: vitePort,
148
+ host: viteHost,
149
+ ...config
150
+ }
151
+ monitorVite(context, viteHost, vitePort, config)
152
+ }
153
+ },
154
+
155
+ onServerStart: async (context: PluginContext) => {
156
+ const config = getPluginConfig(context)
157
+ const viteConfig = (context as any).viteConfig
158
+
159
+ if (config.enabled && viteConfig) {
160
+ context.logger.debug(`Vite integration active - monitoring ${viteConfig.host}:${viteConfig.port}`)
161
+ }
162
+ },
163
+
164
+ onBeforeRoute: async (requestContext: RequestContext) => {
165
+ // Skip API routes and swagger - let them be handled by backend
166
+ if (requestContext.path.startsWith("/api") || requestContext.path.startsWith("/swagger")) {
167
+ return
168
+ }
169
+
170
+ // For Vite internal routes, proxy directly to Vite server
171
+ if (requestContext.path.startsWith("/@") || // All Vite internal routes (/@vite/, /@fs/, /@react-refresh, etc.)
172
+ requestContext.path.startsWith("/__vite") || // Vite HMR and dev routes
173
+ requestContext.path.startsWith("/node_modules") || // Direct node_modules access
174
+ requestContext.path.includes("/.vite/") || // Vite cache and deps
175
+ requestContext.path.endsWith(".js.map") || // Source maps
176
+ requestContext.path.endsWith(".css.map")) { // CSS source maps
177
+
178
+ // Use fixed configuration for Vite proxy
179
+ const viteHost = "localhost"
180
+ const vitePort = 5173
181
+
182
+ try {
183
+ const url = new URL(requestContext.request.url)
184
+ const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
185
+
186
+ // Forward request to Vite
187
+ const response = await fetch(viteUrl, {
188
+ method: requestContext.method,
189
+ headers: requestContext.headers,
190
+ body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
191
+ })
192
+
193
+ // Return the Vite response
194
+ const body = await response.arrayBuffer()
195
+
196
+ requestContext.handled = true
197
+ requestContext.response = new Response(body, {
198
+ status: response.status,
199
+ statusText: response.statusText,
200
+ headers: response.headers
201
+ })
202
+
203
+ } catch (viteError) {
204
+ // If Vite fails, let the request continue to normal routing (will become 404)
205
+ // Only log if explicitly enabled for debugging
206
+ const { clientConfig } = await import('@/config/client.config')
207
+ if (clientConfig.vite.enableLogging) {
208
+ console.warn(`Vite proxy error: ${viteError}`)
209
+ }
210
+ }
211
+ return
212
+ }
213
+
214
+ // Use fixed configuration for simplicity - Vite should be running on port 5173
215
+ const viteHost = "localhost"
216
+ const vitePort = 5173
217
+
218
+ try {
219
+ const url = new URL(requestContext.request.url)
220
+ const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
221
+
222
+ // Forward request to Vite
223
+ const response = await fetch(viteUrl, {
224
+ method: requestContext.method,
225
+ headers: requestContext.headers,
226
+ body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
227
+ })
228
+
229
+ // If Vite responds successfully, handle the request
230
+ if (response.ok || response.status < 500) {
231
+ // Return a proper Response object with all headers and status
232
+ const body = await response.arrayBuffer()
233
+
234
+ requestContext.handled = true
235
+ requestContext.response = new Response(body, {
236
+ status: response.status,
237
+ statusText: response.statusText,
238
+ headers: response.headers
239
+ })
240
+ }
241
+
242
+ } catch (viteError) {
243
+ // If Vite fails, let the request continue to normal routing (will become 404)
244
+ // Only log if explicitly enabled for debugging
245
+ const { clientConfig } = await import('@/config/client.config')
246
+ if (clientConfig.vite.enableLogging) {
247
+ console.warn(`Vite proxy error: ${viteError}`)
248
+ }
249
+ }
250
+ }
251
+ }
252
+
253
+ // Helper function to get plugin config
254
+ function getPluginConfig(context: PluginContext) {
255
+ const pluginConfig = context.config.plugins.config?.vite || {}
256
+ return { ...vitePlugin.defaultConfig, ...pluginConfig }
257
+ }
258
+
259
+ // Monitor Vite server status with automatic port detection
260
+ async function monitorVite(
261
+ context: PluginContext,
262
+ host: string,
263
+ initialPort: number,
264
+ config: any
265
+ ) {
266
+ let retries = 0
267
+ let isConnected = false
268
+ let actualPort = initialPort
269
+ let portDetected = false
270
+
271
+ const checkVite = async () => {
272
+ try {
273
+ // If we haven't found the correct port yet, try to detect it
274
+ if (!portDetected) {
275
+ const detectedPort = await detectVitePort(host, initialPort)
276
+ if (detectedPort !== null) {
277
+ actualPort = detectedPort
278
+ portDetected = true
279
+ // Update the context with the detected port
280
+ if ((context as any).viteConfig) {
281
+ ; (context as any).viteConfig.port = actualPort
282
+ }
283
+ }
284
+ }
285
+
286
+ const isRunning = await checkViteRunning(host, actualPort, config.timeout)
287
+
288
+ if (isRunning && !isConnected) {
289
+ isConnected = true
290
+ retries = 0
291
+ if (actualPort !== initialPort) {
292
+ context.logger.debug(`✓ Vite server detected on ${host}:${actualPort} (auto-detected from port ${initialPort})`)
293
+ } else {
294
+ context.logger.debug(`✓ Vite server detected on ${host}:${actualPort}`)
295
+ }
296
+ context.logger.debug("Hot reload coordination active")
297
+ } else if (!isRunning && isConnected) {
298
+ isConnected = false
299
+ context.logger.warn(`✗ Vite server disconnected from ${host}:${actualPort}`)
300
+ // Reset port detection when disconnected
301
+ portDetected = false
302
+ actualPort = initialPort
303
+ } else if (!isRunning) {
304
+ retries++
305
+ if (retries <= config.maxRetries) {
306
+ if (portDetected) {
307
+ context.logger.debug(`Waiting for Vite server on ${host}:${actualPort}... (${retries}/${config.maxRetries})`)
308
+ } else {
309
+ context.logger.debug(`Detecting Vite server port... (${retries}/${config.maxRetries})`)
310
+ }
311
+ } else if (retries === config.maxRetries + 1) {
312
+ context.logger.warn(`Vite server not found after ${config.maxRetries} attempts. Development features may be limited.`)
313
+ }
314
+ }
315
+ } catch (error) {
316
+ if (isConnected) {
317
+ context.logger.error('Error checking Vite server status', { error })
318
+ }
319
+ }
320
+
321
+ // Continue monitoring
322
+ setTimeout(checkVite, config.checkInterval)
323
+ }
324
+
325
+ // Start monitoring after a brief delay
326
+ setTimeout(checkVite, 1000)
327
+ }
328
+
329
+ // Auto-detect Vite port by trying common ports
330
+ async function detectVitePort(host: string, startPort: number): Promise<number | null> {
331
+ // Try the initial port first, then common alternatives
332
+ const portsToTry = [
333
+ startPort,
334
+ startPort + 1,
335
+ startPort + 2,
336
+ startPort + 3,
337
+ 5174, // Common Vite alternative
338
+ 5175,
339
+ 5176,
340
+ 3000, // Sometimes Vite might use this
341
+ 4173 // Another common alternative
342
+ ]
343
+
344
+ for (const port of portsToTry) {
345
+ try {
346
+ const isRunning = await checkViteRunning(host, port, 1000)
347
+ if (isRunning) {
348
+ return port
349
+ }
350
+ } catch (error) {
351
+ // Continue trying other ports
352
+ }
353
+ }
354
+
355
+ return null
356
+ }
357
+
358
+ // Check if Vite is running
359
+ async function checkViteRunning(host: string, port: number, timeout: number = 1000): Promise<boolean> {
360
+ try {
361
+ const controller = new AbortController()
362
+ const timeoutId = setTimeout(() => controller.abort(), timeout)
363
+
364
+ const response = await fetch(`http://${host}:${port}`, {
365
+ signal: controller.signal,
366
+ method: 'HEAD' // Use HEAD to minimize data transfer
367
+ })
368
+
369
+ clearTimeout(timeoutId)
370
+ return response.status >= 200 && response.status < 500
371
+ } catch (error) {
372
+ return false
373
+ }
374
+ }
375
+
376
+ // Note: Proxy logic is now handled directly in the onBeforeRoute hook above
377
+
378
378
  export default vitePlugin