juxscript 1.1.0 → 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.
- package/machinery/ast.js +347 -0
- package/machinery/build.js +466 -0
- package/machinery/build3.js +159 -0
- package/machinery/bundleAssets.js +0 -0
- package/machinery/bundleJux.js +0 -0
- package/machinery/bundleVendors.js +0 -0
- package/machinery/compiler3.js +628 -0
- package/machinery/config.js +155 -0
- package/machinery/doc-generator.js +136 -0
- package/machinery/imports.js +155 -0
- package/machinery/serve.js +255 -0
- package/machinery/ts-shim.js +46 -0
- package/machinery/validators/file-validator.js +123 -0
- package/machinery/watcher.js +59 -0
- package/package.json +3 -2
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
|
|
5
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = path.dirname(__filename);
|
|
7
|
+
|
|
8
|
+
// Default configuration
|
|
9
|
+
export const defaultConfig = {
|
|
10
|
+
sourceDir: 'jux',
|
|
11
|
+
distDir: '.jux-dist',
|
|
12
|
+
ports: {
|
|
13
|
+
http: 3000,
|
|
14
|
+
ws: 3001
|
|
15
|
+
},
|
|
16
|
+
build: {
|
|
17
|
+
minify: false,
|
|
18
|
+
sourcemap: true
|
|
19
|
+
},
|
|
20
|
+
bootstrap: []
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// Load user configuration
|
|
24
|
+
export async function loadConfig(projectRoot) {
|
|
25
|
+
const configPath = path.join(projectRoot, 'juxconfig.js');
|
|
26
|
+
|
|
27
|
+
if (fs.existsSync(configPath)) {
|
|
28
|
+
try {
|
|
29
|
+
const configModule = await import(`file://${configPath}`);
|
|
30
|
+
const userConfig = configModule.default || configModule;
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
...defaultConfig,
|
|
34
|
+
...userConfig,
|
|
35
|
+
ports: { ...defaultConfig.ports, ...(userConfig.ports || {}) },
|
|
36
|
+
build: { ...defaultConfig.build, ...(userConfig.build || {}) }
|
|
37
|
+
};
|
|
38
|
+
} catch (err) {
|
|
39
|
+
console.warn(`⚠️ Failed to load juxconfig.js: ${err.message}`);
|
|
40
|
+
console.warn(` Using default configuration\n`);
|
|
41
|
+
return defaultConfig;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
console.log('ℹ️ No juxconfig.js found, using defaults');
|
|
46
|
+
return defaultConfig;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Run bootstrap functions
|
|
50
|
+
export async function runBootstrap(bootstrapFunctions = []) {
|
|
51
|
+
if (!Array.isArray(bootstrapFunctions) || bootstrapFunctions.length === 0) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
console.log('🚀 Running bootstrap functions...\n');
|
|
56
|
+
|
|
57
|
+
for (const fn of bootstrapFunctions) {
|
|
58
|
+
if (typeof fn === 'function') {
|
|
59
|
+
try {
|
|
60
|
+
await fn();
|
|
61
|
+
} catch (err) {
|
|
62
|
+
console.error(`❌ Bootstrap function failed:`, err.message);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
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;
|
|
155
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { glob } from 'glob';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Generate documentation from TypeScript component files
|
|
7
|
+
*
|
|
8
|
+
* @param {string} juxLibPath - Absolute path to jux/lib directory
|
|
9
|
+
*/
|
|
10
|
+
export async function generateDocs(juxLibPath) {
|
|
11
|
+
const componentsDir = path.join(juxLibPath, 'components');
|
|
12
|
+
|
|
13
|
+
if (!fs.existsSync(componentsDir)) {
|
|
14
|
+
throw new Error(`Components directory not found: ${componentsDir}`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
console.log(` Scanning: ${componentsDir}`);
|
|
18
|
+
|
|
19
|
+
// Find all component TypeScript files
|
|
20
|
+
const componentFiles = glob.sync('*.ts', {
|
|
21
|
+
cwd: componentsDir,
|
|
22
|
+
absolute: true,
|
|
23
|
+
ignore: ['reactivity.ts', 'error-handler.ts']
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
console.log(` Found ${componentFiles.length} component files`);
|
|
27
|
+
|
|
28
|
+
const components = [];
|
|
29
|
+
|
|
30
|
+
for (const filePath of componentFiles) {
|
|
31
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
32
|
+
const componentDoc = parseComponentFile(content, filePath);
|
|
33
|
+
|
|
34
|
+
if (componentDoc) {
|
|
35
|
+
components.push(componentDoc);
|
|
36
|
+
console.log(` ✓ ${componentDoc.name}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Sort by category and name
|
|
41
|
+
components.sort((a, b) => {
|
|
42
|
+
const categoryCompare = (a.category || 'ZZZ').localeCompare(b.category || 'ZZZ');
|
|
43
|
+
if (categoryCompare !== 0) return categoryCompare;
|
|
44
|
+
return a.name.localeCompare(b.name);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
// Generate the docs data
|
|
48
|
+
const docsData = {
|
|
49
|
+
components,
|
|
50
|
+
version: '1.0.0',
|
|
51
|
+
lastUpdated: new Date().toISOString()
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Write to JSON file
|
|
55
|
+
const outputPath = path.join(componentsDir, 'docs-data.json');
|
|
56
|
+
fs.writeFileSync(outputPath, JSON.stringify(docsData, null, 2));
|
|
57
|
+
|
|
58
|
+
console.log(` Generated: ${outputPath}`);
|
|
59
|
+
|
|
60
|
+
return docsData;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Parse a single component file
|
|
65
|
+
*/
|
|
66
|
+
function parseComponentFile(content, filePath) {
|
|
67
|
+
const fileName = path.basename(filePath, '.ts');
|
|
68
|
+
const className = fileName.charAt(0).toUpperCase() + fileName.slice(1);
|
|
69
|
+
|
|
70
|
+
const category = inferCategory(className, content);
|
|
71
|
+
const descMatch = content.match(/\/\*\*\s*\n\s*\*\s*([^\n*]+)/);
|
|
72
|
+
const description = descMatch ? descMatch[1].trim() : `${className} component`;
|
|
73
|
+
const factoryMatch = content.match(/export function\s+\w+\(([^)]*)\)/);
|
|
74
|
+
const constructorSig = factoryMatch
|
|
75
|
+
? `jux.${fileName}(${factoryMatch[1]})`
|
|
76
|
+
: `new ${className}()`;
|
|
77
|
+
const fluentMethods = extractFluentMethods(content, className);
|
|
78
|
+
const exampleMatch = content.match(/\*\s+Usage:\s*\n\s*\*\s+(.+?)(?:\n|$)/);
|
|
79
|
+
let example = exampleMatch
|
|
80
|
+
? exampleMatch[1].trim()
|
|
81
|
+
: `jux.${fileName}('id').render()`;
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
name: className,
|
|
85
|
+
category,
|
|
86
|
+
description,
|
|
87
|
+
constructor: constructorSig,
|
|
88
|
+
fluentMethods,
|
|
89
|
+
example
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Extract fluent API methods from class
|
|
95
|
+
*/
|
|
96
|
+
function extractFluentMethods(content, className) {
|
|
97
|
+
const methods = [];
|
|
98
|
+
const methodRegex = /^\s*(\w+)\(([^)]*)\):\s*this\s*\{/gm;
|
|
99
|
+
let match;
|
|
100
|
+
|
|
101
|
+
while ((match = methodRegex.exec(content)) !== null) {
|
|
102
|
+
const methodName = match[1];
|
|
103
|
+
const params = match[2];
|
|
104
|
+
if (methodName.startsWith('_') || methodName === 'constructor') continue;
|
|
105
|
+
const cleanParams = params.split(',').map(p => p.trim().split(':')[0].trim()).filter(p => p).join(', ');
|
|
106
|
+
methods.push({
|
|
107
|
+
name: methodName,
|
|
108
|
+
params: cleanParams ? `(${cleanParams})` : '()',
|
|
109
|
+
returns: 'this',
|
|
110
|
+
description: `Set ${methodName}`
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const renderMatch = content.match(/^\s*render\(([^)]*)\):\s*(\w+)/m);
|
|
115
|
+
if (renderMatch && !methods.find(m => m.name === 'render')) {
|
|
116
|
+
methods.push({
|
|
117
|
+
name: 'render',
|
|
118
|
+
params: renderMatch[1] ? `(${renderMatch[1]})` : '()',
|
|
119
|
+
returns: renderMatch[2],
|
|
120
|
+
description: 'Render component to DOM'
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return methods;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Infer category from component name or content
|
|
129
|
+
*/
|
|
130
|
+
function inferCategory(name, content) {
|
|
131
|
+
const dataComponents = ['Table', 'List', 'Chart', 'Data'];
|
|
132
|
+
const coreComponents = ['App', 'Layout', 'Theme', 'Style', 'Script', 'Import'];
|
|
133
|
+
if (dataComponents.some(dc => name.includes(dc))) return 'Data Components';
|
|
134
|
+
if (coreComponents.includes(name)) return 'Core';
|
|
135
|
+
return 'UI Components';
|
|
136
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
|
|
5
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = path.dirname(__filename);
|
|
7
|
+
const REGISTRY_PATH = path.join(__dirname, '../lib/registry/packages.json');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Load package registry
|
|
11
|
+
*/
|
|
12
|
+
function loadRegistry() {
|
|
13
|
+
if (!fs.existsSync(REGISTRY_PATH)) {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf-8'));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Parse @import directives from Jux code
|
|
21
|
+
*/
|
|
22
|
+
export function parseImports(juxCode) {
|
|
23
|
+
const imports = [];
|
|
24
|
+
const lines = juxCode.split('\n');
|
|
25
|
+
|
|
26
|
+
for (let i = 0; i < lines.length; i++) {
|
|
27
|
+
const line = lines[i].trim();
|
|
28
|
+
|
|
29
|
+
// Stop parsing when we hit actual code (non-directive, non-comment)
|
|
30
|
+
if (line && !line.startsWith('@') && !line.startsWith('//') && !line.startsWith('/*')) {
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Match @import directive
|
|
35
|
+
const importMatch = line.match(/^@import\s+(.+)$/);
|
|
36
|
+
if (importMatch) {
|
|
37
|
+
const importSpec = importMatch[1].trim();
|
|
38
|
+
imports.push({
|
|
39
|
+
line: i + 1,
|
|
40
|
+
raw: importSpec,
|
|
41
|
+
resolved: resolveImport(importSpec)
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
if (process.env.JUX_VERBOSE) {
|
|
45
|
+
console.log(` [Line ${i + 1}] Found @import: ${importSpec}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return imports;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Resolve import specification to URL/path
|
|
55
|
+
*/
|
|
56
|
+
export function resolveImport(importSpec) {
|
|
57
|
+
// Remove quotes if present
|
|
58
|
+
const cleaned = importSpec.replace(/^['"]|['"]$/g, '');
|
|
59
|
+
|
|
60
|
+
// Direct URL (starts with http:// or https://)
|
|
61
|
+
if (cleaned.startsWith('http://') || cleaned.startsWith('https://')) {
|
|
62
|
+
return {
|
|
63
|
+
type: 'cdn',
|
|
64
|
+
url: cleaned,
|
|
65
|
+
source: 'direct'
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Local file (starts with ./ or ../ or /)
|
|
70
|
+
if (cleaned.startsWith('./') || cleaned.startsWith('../') || cleaned.startsWith('/')) {
|
|
71
|
+
return {
|
|
72
|
+
type: 'local',
|
|
73
|
+
path: cleaned,
|
|
74
|
+
source: 'file'
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Unknown/unsupported
|
|
79
|
+
return {
|
|
80
|
+
type: 'unknown',
|
|
81
|
+
name: cleaned,
|
|
82
|
+
error: `Import "${cleaned}" must be a URL (https://...) or relative path (./...)`
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Auto-detect component dependencies
|
|
88
|
+
*/
|
|
89
|
+
function detectComponentDependencies(usedComponents) {
|
|
90
|
+
const componentDeps = {
|
|
91
|
+
'chart': 'chart.js'
|
|
92
|
+
// Add more mappings as needed
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const deps = new Set();
|
|
96
|
+
|
|
97
|
+
usedComponents.forEach(comp => {
|
|
98
|
+
if (componentDeps[comp]) {
|
|
99
|
+
deps.add(componentDeps[comp]);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
return Array.from(deps).map(pkg => ({
|
|
104
|
+
auto: true,
|
|
105
|
+
resolved: resolveImport(pkg)
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Generate HTML script tags from resolved imports
|
|
111
|
+
*/
|
|
112
|
+
export function generateImportTags(imports) {
|
|
113
|
+
const tags = [];
|
|
114
|
+
const seen = new Set();
|
|
115
|
+
|
|
116
|
+
for (const imp of imports) {
|
|
117
|
+
const resolved = imp.resolved;
|
|
118
|
+
|
|
119
|
+
if (resolved.type === 'unknown') {
|
|
120
|
+
tags.push(`<!-- ERROR: ${resolved.error} -->`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const key = resolved.url || resolved.path;
|
|
125
|
+
if (seen.has(key)) continue;
|
|
126
|
+
seen.add(key);
|
|
127
|
+
|
|
128
|
+
if (resolved.type === 'cdn') {
|
|
129
|
+
tags.push(` <script src="${resolved.url}"></script>`);
|
|
130
|
+
} else if (resolved.type === 'local') {
|
|
131
|
+
tags.push(` <script type="module" src="${resolved.path}"></script>`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return tags.join('\n');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Validate all imports are resolvable
|
|
140
|
+
*/
|
|
141
|
+
export function validateImports(imports) {
|
|
142
|
+
const errors = [];
|
|
143
|
+
|
|
144
|
+
imports.forEach(imp => {
|
|
145
|
+
if (imp.resolved.type === 'unknown') {
|
|
146
|
+
errors.push({
|
|
147
|
+
line: imp.line,
|
|
148
|
+
message: imp.resolved.error,
|
|
149
|
+
raw: imp.raw
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
return errors;
|
|
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);
|