juxscript 1.1.2 → 1.1.3

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.
@@ -23,12 +23,12 @@ export const defaultConfig = {
23
23
  // Load user configuration
24
24
  export async function loadConfig(projectRoot) {
25
25
  const configPath = path.join(projectRoot, 'juxconfig.js');
26
-
26
+
27
27
  if (fs.existsSync(configPath)) {
28
28
  try {
29
29
  const configModule = await import(`file://${configPath}`);
30
30
  const userConfig = configModule.default || configModule;
31
-
31
+
32
32
  return {
33
33
  ...defaultConfig,
34
34
  ...userConfig,
@@ -41,7 +41,7 @@ export async function loadConfig(projectRoot) {
41
41
  return defaultConfig;
42
42
  }
43
43
  }
44
-
44
+
45
45
  console.log('ℹ️ No juxconfig.js found, using defaults');
46
46
  return defaultConfig;
47
47
  }
@@ -51,9 +51,9 @@ export async function runBootstrap(bootstrapFunctions = []) {
51
51
  if (!Array.isArray(bootstrapFunctions) || bootstrapFunctions.length === 0) {
52
52
  return;
53
53
  }
54
-
54
+
55
55
  console.log('🚀 Running bootstrap functions...\n');
56
-
56
+
57
57
  for (const fn of bootstrapFunctions) {
58
58
  if (typeof fn === 'function') {
59
59
  try {
@@ -63,6 +63,93 @@ export async function runBootstrap(bootstrapFunctions = []) {
63
63
  }
64
64
  }
65
65
  }
66
-
66
+
67
67
  console.log('✅ Bootstrap complete\n');
68
+ }
69
+
70
+ /**
71
+ * Type helper for JUX Configuration (Identity function for Autocomplete)
72
+ * Used in juxconfig.js to provide Intellisense.
73
+ * @param {Object} config
74
+ * @returns {Object}
75
+ */
76
+ export function defineConfig(config) {
77
+ return config;
78
+ }
79
+
80
+ /**
81
+ * Normalizes user configuration into the strict format used by the compiler/server.
82
+ * Handles "DX Sugar" like:
83
+ * - Inferring file extensions (.jux, .css)
84
+ * - Mapping 'dist' -> 'distribution'
85
+ * - Resolving shortcuts (e.g. layouts)
86
+ * - Defaulting ports
87
+ */
88
+ export function resolveConfig(userConfig, projectRoot = process.cwd()) {
89
+ const root = userConfig.root || projectRoot;
90
+
91
+ // 1. Directories (Map 'dist' alias to 'distribution')
92
+ const dirs = userConfig.directories || {};
93
+ const directories = {
94
+ source: dirs.source || 'jux',
95
+ distribution: dirs.dist || dirs.distribution || '.jux-dist',
96
+ themes: dirs.themes || 'themes',
97
+ layouts: dirs.layouts || 'themes/layouts',
98
+ assets: dirs.assets || 'themes/assets'
99
+ };
100
+
101
+ // 2. Defaults (Infer extensions)
102
+ const defs = userConfig.defaults || {};
103
+ const httpPort = defs.port || defs.httpPort || 3000;
104
+
105
+ const defaults = {
106
+ httpPort,
107
+ wsPort: defs.wsPort || (httpPort + 1),
108
+ autoRoute: defs.autoRoute !== false, // default true
109
+ layout: ensureExt(defs.layout, '.jux') || 'base.jux',
110
+ theme: ensureExt(defs.theme, '.css') || 'base.css'
111
+ };
112
+
113
+ // 3. Pages Normalization (Recursively fix route paths)
114
+ const pages = normalizePages(userConfig.pages || {});
115
+
116
+ // 4. Return Normalized Config
117
+ return {
118
+ root,
119
+ directories,
120
+ defaults,
121
+ pages,
122
+ hooks: userConfig.hooks || {}
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Helper: Appends extension if missing
128
+ */
129
+ function ensureExt(file, ext) {
130
+ if (!file) return file;
131
+ return file.endsWith(ext) ? file : `${file}${ext}`;
132
+ }
133
+
134
+ /**
135
+ * Helper: Recursively normalizes page routes
136
+ */
137
+ function normalizePages(pages) {
138
+ const normalized = {};
139
+ for (const [key, value] of Object.entries(pages)) {
140
+ if (typeof value === 'string') {
141
+ // Direct route: '/' -> 'experiments/index'
142
+ // Becomes: '/' -> 'experiments/index.jux'
143
+ normalized[key] = ensureExt(value, '.jux');
144
+ } else if (typeof value === 'object') {
145
+ // Route Group
146
+ normalized[key] = {
147
+ ...value,
148
+ layout: value.layout ? ensureExt(value.layout, '.jux') : undefined,
149
+ theme: value.theme ? ensureExt(value.theme, '.css') : undefined,
150
+ routes: normalizePages(value.routes || {})
151
+ };
152
+ }
153
+ }
154
+ return normalized;
68
155
  }
@@ -0,0 +1,255 @@
1
+ import express from 'express';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import http from 'http';
5
+ import { fileURLToPath } from 'url';
6
+ import { WebSocketServer } from 'ws';
7
+ import { createWatcher } from './watcher.js';
8
+ import { JuxCompiler } from './compiler3.js';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+
13
+ // ═══════════════════════════════════════════════════════════════
14
+ // CONFIGURATION
15
+ // ═══════════════════════════════════════════════════════════════
16
+ const args = process.argv.slice(2);
17
+ const HOT_RELOAD = args.includes('--hot') || args.includes('-h') || args.includes('--watch');
18
+
19
+ // Extract port from args (e.g., --port=3000 or -p 3000)
20
+ function getArgValue(flag, shortFlag, defaultValue) {
21
+ for (let i = 0; i < args.length; i++) {
22
+ if (args[i].startsWith(`${flag}=`)) return args[i].split('=')[1];
23
+ if (args[i].startsWith(`${shortFlag}=`)) return args[i].split('=')[1];
24
+ if ((args[i] === flag || args[i] === shortFlag) && args[i + 1]) return args[i + 1];
25
+ }
26
+ return defaultValue;
27
+ }
28
+
29
+ const PORT = parseInt(getArgValue('--port', '-p', process.env.PORT || '3000'));
30
+ const WS_PORT = parseInt(getArgValue('--ws-port', '-w', process.env.WS_PORT || String(PORT + 1)));
31
+
32
+ // Resolve paths relative to CWD (user's project)
33
+ const PROJECT_ROOT = process.cwd();
34
+ const DIST_DIR = path.resolve(PROJECT_ROOT, '.jux-dist');
35
+ const SRC_DIR = path.resolve(PROJECT_ROOT, 'jux');
36
+
37
+ const app = express();
38
+ let lastBuildResult = { success: true, errors: [] };
39
+
40
+ // Check if dist directory exists - if not, try to build first
41
+ if (!fs.existsSync(DIST_DIR) || !fs.existsSync(path.join(DIST_DIR, 'index.html'))) {
42
+ console.log('⚠️ Dist directory not found. Running initial build...');
43
+
44
+ const compiler = new JuxCompiler({
45
+ srcDir: SRC_DIR,
46
+ distDir: DIST_DIR
47
+ });
48
+
49
+ try {
50
+ const result = await compiler.build();
51
+ lastBuildResult = result;
52
+
53
+ if (!result.success) {
54
+ console.log('\n❌ Initial build failed. Starting server to show error overlay.\n');
55
+ }
56
+ } catch (err) {
57
+ console.error('❌ Initial build failed:', err.message);
58
+ lastBuildResult = { success: false, errors: [{ message: err.message }] };
59
+ }
60
+ }
61
+
62
+ if (!fs.existsSync(DIST_DIR)) {
63
+ fs.mkdirSync(DIST_DIR, { recursive: true });
64
+ }
65
+
66
+ app.use((req, res, next) => {
67
+ res.setHeader('Cache-Control', 'no-store');
68
+ next();
69
+ });
70
+
71
+ app.use((req, res, next) => {
72
+ if (req.path.endsWith('.js')) {
73
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
74
+ }
75
+ next();
76
+ });
77
+
78
+ app.get('/favicon.ico', (req, res) => res.status(204).end());
79
+ app.get('/favicon.png', (req, res) => res.status(204).end());
80
+
81
+ app.get('/__jux_sources.json', (req, res) => {
82
+ const snapshotPath = path.join(DIST_DIR, '__jux_sources.json');
83
+ if (fs.existsSync(snapshotPath)) {
84
+ res.setHeader('Content-Type', 'application/json');
85
+ res.sendFile(snapshotPath);
86
+ } else {
87
+ res.json({});
88
+ }
89
+ });
90
+
91
+ const hotReloadScript = `
92
+ <script>
93
+ (function() {
94
+ var ws = new WebSocket('ws://localhost:${WS_PORT}');
95
+ ws.onopen = function() { console.log('🔥 Hot reload connected'); };
96
+ ws.onmessage = function(e) {
97
+ var data = JSON.parse(e.data);
98
+ if (data.type === 'reload') location.reload();
99
+ else if (data.type === 'build-error') console.error('❌ Build error:', data.errors);
100
+ };
101
+ ws.onclose = function() { setTimeout(function() { location.reload(); }, 2000); };
102
+ })();
103
+ </script>
104
+ `;
105
+
106
+ function getErrorPageHtml(errors) {
107
+ return `<!DOCTYPE html>
108
+ <html lang="en">
109
+ <head>
110
+ <meta charset="UTF-8">
111
+ <title>JUX Build Error</title>
112
+ <style>
113
+ * { margin: 0; padding: 0; box-sizing: border-box; }
114
+ body { font-family: monospace; background: #1a1a2e; color: #eee; min-height: 100vh; padding: 40px; }
115
+ .container { max-width: 800px; margin: 0 auto; }
116
+ h1 { color: #ff6b6b; margin-bottom: 8px; }
117
+ .subtitle { color: #888; margin-bottom: 30px; }
118
+ .error-card { background: #16213e; padding: 16px 20px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #ff6b6b; }
119
+ .error-header { color: #ff6b6b; font-weight: bold; margin-bottom: 8px; }
120
+ .error-code { background: #0f0f23; padding: 12px; border-radius: 4px; font-size: 13px; color: #888; }
121
+ </style>
122
+ </head>
123
+ <body>
124
+ <div class="container">
125
+ <h1>🛑 Build Failed</h1>
126
+ <p class="subtitle">Fix the errors below and save to rebuild.</p>
127
+ ${errors.map(err => `
128
+ <div class="error-card">
129
+ <div class="error-header">${err.view ? `[${err.view}] ` : ''}${err.message}</div>
130
+ ${err.code ? `<pre class="error-code">${err.code}</pre>` : ''}
131
+ </div>
132
+ `).join('')}
133
+ </div>
134
+ ${HOT_RELOAD ? `<script>
135
+ var ws = new WebSocket('ws://localhost:${WS_PORT}');
136
+ ws.onmessage = function(e) { if (JSON.parse(e.data).type === 'reload') location.reload(); };
137
+ </script>` : ''}
138
+ </body>
139
+ </html>`;
140
+ }
141
+
142
+ if (HOT_RELOAD) {
143
+ app.get(['/', '/index.html'], (req, res) => {
144
+ const indexPath = path.join(DIST_DIR, 'index.html');
145
+
146
+ if (!fs.existsSync(indexPath) || !lastBuildResult.success) {
147
+ return res.send(getErrorPageHtml(lastBuildResult.errors));
148
+ }
149
+
150
+ let html = fs.readFileSync(indexPath, 'utf8');
151
+ html = html.replace('</body>', hotReloadScript + '</body>');
152
+ res.setHeader('Content-Type', 'text/html');
153
+ res.send(html);
154
+ });
155
+ }
156
+
157
+ app.use(express.static(DIST_DIR));
158
+
159
+ app.get('*', (req, res) => {
160
+ if (path.extname(req.path) && req.path !== '/') {
161
+ return res.status(404).send('Not found');
162
+ }
163
+
164
+ const indexPath = path.join(DIST_DIR, 'index.html');
165
+
166
+ if (!fs.existsSync(indexPath) || !lastBuildResult.success) {
167
+ return res.send(getErrorPageHtml(lastBuildResult.errors));
168
+ }
169
+
170
+ if (HOT_RELOAD) {
171
+ let html = fs.readFileSync(indexPath, 'utf8');
172
+ html = html.replace('</body>', hotReloadScript + '</body>');
173
+ res.setHeader('Content-Type', 'text/html');
174
+ res.send(html);
175
+ } else {
176
+ res.sendFile(indexPath);
177
+ }
178
+ });
179
+
180
+ const server = http.createServer(app);
181
+ let wss = null;
182
+ let watcher = null;
183
+
184
+ if (HOT_RELOAD) {
185
+ wss = new WebSocketServer({ port: WS_PORT });
186
+ const clients = new Set();
187
+
188
+ wss.on('connection', (ws) => {
189
+ clients.add(ws);
190
+ ws.on('close', () => clients.delete(ws));
191
+ });
192
+
193
+ const broadcast = (message) => {
194
+ const data = JSON.stringify(message);
195
+ clients.forEach(client => {
196
+ if (client.readyState === 1) client.send(data);
197
+ });
198
+ };
199
+
200
+ const compiler = new JuxCompiler({
201
+ srcDir: SRC_DIR,
202
+ distDir: DIST_DIR
203
+ });
204
+
205
+ watcher = createWatcher(SRC_DIR, {
206
+ onChange: async (changedFiles) => {
207
+ console.log('🔄 Rebuilding...');
208
+
209
+ try {
210
+ const result = await compiler.build();
211
+ lastBuildResult = result;
212
+
213
+ if (!result.success) {
214
+ console.error('❌ Rebuild failed');
215
+ broadcast({ type: 'build-error', errors: result.errors });
216
+ return;
217
+ }
218
+
219
+ console.log('✅ Rebuild complete');
220
+ broadcast({ type: 'reload', files: changedFiles });
221
+ } catch (err) {
222
+ console.error('❌ Rebuild failed:', err.message);
223
+ lastBuildResult = { success: false, errors: [{ message: err.message }] };
224
+ broadcast({ type: 'build-error', errors: [{ message: err.message }] });
225
+ }
226
+ },
227
+ onReady: () => {
228
+ console.log(`👀 Watching: ${SRC_DIR}`);
229
+ }
230
+ });
231
+ }
232
+
233
+ server.listen(PORT, () => {
234
+ console.log(`\n🚀 JUX Server running at http://localhost:${PORT}`);
235
+ if (HOT_RELOAD) {
236
+ console.log(`🔥 Hot reload: ws://localhost:${WS_PORT}`);
237
+ }
238
+ if (!lastBuildResult.success) {
239
+ console.log(`⚠️ Build has errors - fix them and save\n`);
240
+ }
241
+ });
242
+
243
+ const shutdown = () => {
244
+ console.log('\n👋 Shutting down...');
245
+ if (watcher) watcher.close();
246
+ if (wss) {
247
+ wss.clients.forEach(client => client.terminate());
248
+ wss.close();
249
+ }
250
+ server.close(() => process.exit(0));
251
+ setTimeout(() => process.exit(0), 2000);
252
+ };
253
+
254
+ process.on('SIGINT', shutdown);
255
+ process.on('SIGTERM', shutdown);
@@ -1,171 +1,59 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import {
4
- copyLibToOutput,
5
- bundleJuxFilesToRouter,
6
- generateIndexHtml
7
- } from './compiler.js';
8
-
9
- let isRebuilding = false;
10
- let rebuildQueued = false;
11
3
 
12
4
  /**
13
- * Find all .jux files in a directory
5
+ * Watch a directory for changes and trigger callbacks
14
6
  */
15
- function findJuxFiles(dir, fileList = []) {
16
- if (!fs.existsSync(dir)) return fileList;
17
-
18
- const files = fs.readdirSync(dir);
19
-
20
- files.forEach(file => {
21
- const filePath = path.join(dir, file);
22
- const stat = fs.statSync(filePath);
23
-
24
- if (stat.isDirectory()) {
25
- if (file !== 'node_modules' && file !== 'jux-dist' && file !== '.git' && file !== 'server') {
26
- findJuxFiles(filePath, fileList);
27
- }
28
- } else if (file.endsWith('.jux')) {
29
- fileList.push(filePath);
30
- }
7
+ export function createWatcher(srcDir, options = {}) {
8
+ const {
9
+ onChange = () => { },
10
+ onReady = () => { },
11
+ debounceMs = 100,
12
+ extensions = ['.jux', '.js', '.css']
13
+ } = options;
14
+
15
+ const absoluteSrcDir = path.resolve(srcDir);
16
+ let debounceTimer = null;
17
+ let pendingChanges = new Set();
18
+
19
+ console.log(`👀 Watching: ${absoluteSrcDir}`);
20
+
21
+ // Debounced change handler
22
+ const handleChange = (eventType, filename) => {
23
+ if (!filename) return;
24
+
25
+ // Filter by extension
26
+ const ext = path.extname(filename);
27
+ if (!extensions.includes(ext)) return;
28
+
29
+ pendingChanges.add(filename);
30
+
31
+ // Debounce rapid changes
32
+ if (debounceTimer) clearTimeout(debounceTimer);
33
+ debounceTimer = setTimeout(() => {
34
+ const changes = [...pendingChanges];
35
+ pendingChanges.clear();
36
+
37
+ console.log(`📝 Changed: ${changes.join(', ')}`);
38
+ onChange(changes);
39
+ }, debounceMs);
40
+ };
41
+
42
+ // Start watching
43
+ const watcher = fs.watch(absoluteSrcDir, { recursive: true }, handleChange);
44
+
45
+ watcher.on('error', (err) => {
46
+ console.error('❌ Watcher error:', err);
31
47
  });
32
48
 
33
- return fileList;
34
- }
35
-
36
- /**
37
- * Full rebuild of the entire bundle
38
- */
39
- async function fullRebuild(juxSource, distDir) {
40
- const startTime = performance.now(); // ✅ Start timing
41
- console.log('\n🔄 Rebuilding bundle...');
42
-
43
- try {
44
- // Find all .jux files
45
- const projectJuxFiles = findJuxFiles(juxSource);
46
- console.log(` Found ${projectJuxFiles.length} .jux file(s)`);
47
-
48
- // ✅ Time the bundling step
49
- const bundleStartTime = performance.now();
50
-
51
- // Bundle all files
52
- const mainJsFilename = await bundleJuxFilesToRouter(juxSource, distDir, {
53
- routePrefix: ''
54
- });
55
-
56
- const bundleTime = performance.now() - bundleStartTime;
57
-
58
- // ✅ Time the route generation step
59
- const routeStartTime = performance.now();
60
-
61
- // Generate routes for index.html
62
- const routes = projectJuxFiles.map(juxFile => {
63
- const relativePath = path.relative(juxSource, juxFile);
64
- const parsedPath = path.parse(relativePath);
65
-
66
- const rawFunctionName = parsedPath.dir
67
- ? `${parsedPath.dir.replace(/\//g, '_')}_${parsedPath.name}`
68
- : parsedPath.name;
69
-
70
- const functionName = rawFunctionName
71
- .replace(/[-_]/g, ' ')
72
- .split(' ')
73
- .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
74
- .join('');
75
-
76
- const routePath = '/' + (parsedPath.dir ? `${parsedPath.dir}/` : '') + parsedPath.name;
77
-
78
- return {
79
- path: routePath.replace(/\/+/g, '/'),
80
- functionName
81
- };
82
- });
83
-
84
- // Generate index.html
85
- generateIndexHtml(distDir, routes, mainJsFilename);
86
-
87
- const routeTime = performance.now() - routeStartTime;
88
- const totalTime = performance.now() - startTime;
49
+ onReady();
89
50
 
90
- // Pretty-print timing breakdown
91
- console.log(`\n⏱️ Rebuild Performance:`);
92
- console.log(` Bundle generation: ${bundleTime.toFixed(0)}ms`);
93
- console.log(` Route/index.html: ${routeTime.toFixed(0)}ms`);
94
- console.log(` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
95
- console.log(` Total rebuild: ${totalTime.toFixed(0)}ms`);
96
-
97
- // ✅ Color-coded performance indicator
98
- if (totalTime < 100) {
99
- console.log(` ✅ Lightning fast! ⚡`);
100
- } else if (totalTime < 500) {
101
- console.log(` ✅ Fast rebuild`);
102
- } else if (totalTime < 1000) {
103
- console.log(` ⚠️ Moderate speed`);
104
- } else {
105
- console.log(` 🐌 Slow rebuild (consider optimizing)`);
106
- }
107
-
108
- console.log(`✅ Bundle rebuilt: ${mainJsFilename}\n`);
109
- return true;
110
-
111
- } catch (err) {
112
- const failTime = performance.now() - startTime;
113
- console.error(`❌ Rebuild failed after ${failTime.toFixed(0)}ms:`, err.message);
114
- return false;
115
- }
116
- }
117
-
118
- /**
119
- * Start watching for file changes and rebuild on change
120
- */
121
- export function startWatcher(juxSource, distDir, wsClients) {
122
- console.log(`👀 Watching: ${juxSource}`);
123
-
124
- const watcher = fs.watch(juxSource, { recursive: true }, async (eventType, filename) => {
125
- // Ignore non-.jux files and certain patterns
126
- if (!filename ||
127
- !filename.endsWith('.jux') ||
128
- filename.includes('node_modules') ||
129
- filename.includes('jux-dist') ||
130
- filename.startsWith('.')) {
131
- return;
132
- }
133
-
134
- // Debounce: If already rebuilding, queue another rebuild
135
- if (isRebuilding) {
136
- rebuildQueued = true;
137
- return;
51
+ // Return control object
52
+ return {
53
+ close: () => {
54
+ if (debounceTimer) clearTimeout(debounceTimer);
55
+ watcher.close();
56
+ console.log('👋 Watcher closed');
138
57
  }
139
-
140
- isRebuilding = true;
141
- console.log(`\n📝 File changed: ${filename}`);
142
-
143
- // Rebuild the entire bundle
144
- const success = await fullRebuild(juxSource, distDir);
145
-
146
- isRebuilding = false;
147
-
148
- // Notify all WebSocket clients to reload
149
- if (success && wsClients && wsClients.length > 0) {
150
- console.log(`🔌 Notifying ${wsClients.length} client(s) to reload`);
151
-
152
- // ✅ Add small delay to ensure file is fully written
153
- setTimeout(() => {
154
- wsClients.forEach(client => {
155
- if (client.readyState === 1) { // OPEN
156
- client.send(JSON.stringify({ type: 'reload' }));
157
- }
158
- });
159
- }, 100);
160
- }
161
-
162
- // Process queued rebuild if needed
163
- if (rebuildQueued) {
164
- rebuildQueued = false;
165
- console.log('🔄 Processing queued rebuild...');
166
- setTimeout(() => watcher.emit('change', 'change', filename), 500);
167
- }
168
- });
169
-
170
- return watcher;
58
+ };
171
59
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "juxscript",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "type": "module",
5
5
  "description": "A JavaScript UX authorship platform",
6
6
  "main": "index.js",
@@ -1,166 +0,0 @@
1
- import express from 'express';
2
- import http from 'http';
3
- import path from 'path';
4
- import fs from 'fs';
5
- import { fileURLToPath } from 'url';
6
- import { startWatcher } from './watcher.js';
7
- import { WebSocketServer } from 'ws';
8
-
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = path.dirname(__filename);
11
-
12
- /**
13
- * Try to start a server on a port, with fallback to next port if busy
14
- * Returns the actual port that was successfully allocated
15
- */
16
- async function tryPort(startPort, maxAttempts = 5, reservedPorts = []) {
17
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
18
- const port = startPort + attempt;
19
-
20
- // Skip if this port is already reserved
21
- if (reservedPorts.includes(port)) {
22
- continue;
23
- }
24
-
25
- try {
26
- // Test if port is available
27
- await new Promise((resolve, reject) => {
28
- const testServer = http.createServer();
29
- testServer.once('error', reject);
30
- testServer.once('listening', () => {
31
- testServer.close();
32
- resolve(port);
33
- });
34
- testServer.listen(port);
35
- });
36
- return port;
37
- } catch (err) {
38
- if (err.code === 'EADDRINUSE') {
39
- if (attempt < maxAttempts - 1) {
40
- console.log(` Port ${port} in use, trying ${port + 1}...`);
41
- }
42
- continue;
43
- }
44
- throw err;
45
- }
46
- }
47
- throw new Error(`Could not find available port after ${maxAttempts} attempts starting from ${startPort}`);
48
- }
49
-
50
- async function serve(httpPort = 3000, wsPort = 3001, distDir = './.jux-dist') {
51
- const app = express();
52
- const absoluteDistDir = path.resolve(distDir);
53
- const projectRoot = path.resolve('.');
54
-
55
- app.use(express.json());
56
-
57
- if (!fs.existsSync(absoluteDistDir)) {
58
- console.error(`❌ Error: ${path.basename(distDir)}/ directory not found at ${absoluteDistDir}`);
59
- console.error(' Run: npx jux build\n');
60
- process.exit(1);
61
- }
62
-
63
- // Strong cache prevention
64
- app.use((req, res, next) => {
65
- res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
66
- res.setHeader('Pragma', 'no-cache');
67
- res.setHeader('Expires', '0');
68
- res.setHeader('ETag', 'W/"' + Date.now() + '"');
69
- next();
70
- });
71
-
72
- // ✅ ADD: Explicit MIME type for JavaScript files
73
- app.use((req, res, next) => {
74
- if (req.path.endsWith('.js')) {
75
- res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
76
- }
77
- next();
78
- });
79
-
80
- // Serve static files
81
- app.use(express.static(absoluteDistDir));
82
-
83
- // ✅ FIX: Only apply SPA fallback to routes, not static files
84
- app.use((req, res, next) => {
85
- // Skip SPA fallback for file extensions (static assets)
86
- if (/\.[a-zA-Z0-9]+$/.test(req.path)) {
87
- return res.status(404).send('File not found');
88
- }
89
-
90
- // SPA fallback for routes only
91
- if (req.accepts('html')) {
92
- const indexPath = path.join(absoluteDistDir, 'index.html');
93
- if (fs.existsSync(indexPath)) {
94
- res.sendFile(indexPath);
95
- } else {
96
- res.status(404).send('index.html not found. Run `npx jux build` first.');
97
- }
98
- } else {
99
- res.status(404).send('Not found');
100
- }
101
- });
102
-
103
- // Find available ports sequentially to avoid collision
104
- console.log('🔍 Finding available ports...');
105
-
106
- // First, find HTTP port
107
- const availableHttpPort = await tryPort(httpPort);
108
-
109
- // Then find WS port, excluding the HTTP port we just allocated
110
- const availableWsPort = await tryPort(wsPort, 5, [availableHttpPort]);
111
-
112
- // Create HTTP server
113
- const server = http.createServer(app);
114
-
115
- // WebSocket server for hot reload
116
- const wss = new WebSocketServer({ port: availableWsPort });
117
- const clients = [];
118
-
119
- wss.on('connection', (ws) => {
120
- clients.push(ws);
121
- console.log('🔌 WebSocket client connected');
122
-
123
- ws.on('close', () => {
124
- console.log('🔌 WebSocket client disconnected');
125
- const index = clients.indexOf(ws);
126
- if (index > -1) clients.splice(index, 1);
127
- });
128
-
129
- ws.on('error', (error) => {
130
- console.error('WebSocket error:', error);
131
- });
132
- });
133
-
134
- console.log(`🔌 WebSocket server running at ws://localhost:${availableWsPort}`);
135
-
136
- // Start HTTP server
137
- server.listen(availableHttpPort, () => {
138
- console.log(`🚀 JUX dev server running at http://localhost:${availableHttpPort}`);
139
- console.log(` Serving: ${absoluteDistDir}`);
140
- console.log(` Press Ctrl+C to stop\n`);
141
- });
142
-
143
- // Start file watcher
144
- const juxSource = path.join(projectRoot, 'jux');
145
- if (fs.existsSync(juxSource)) {
146
- console.log(`👀 Watching: ${juxSource}\n`);
147
- startWatcher(juxSource, absoluteDistDir, clients);
148
- }
149
-
150
- // Graceful shutdown
151
- const shutdown = async () => {
152
- console.log('\n\n👋 Shutting down server...');
153
- wss.close();
154
- server.close();
155
- process.exit(0);
156
- };
157
-
158
- process.on('SIGINT', shutdown);
159
- process.on('SIGTERM', shutdown);
160
-
161
- return { server, httpPort: availableHttpPort, wsPort: availableWsPort };
162
- }
163
-
164
- export async function start(httpPort = 3000, wsPort = 3001, distDir = './.jux-dist') {
165
- return serve(httpPort, wsPort, distDir);
166
- }