@zenithbuild/cli 1.3.4 → 1.3.7

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.
@@ -0,0 +1,931 @@
1
+ /**
2
+ * Zenith SPA Build System
3
+ *
4
+ * Builds all pages into a single index.html with:
5
+ * - Route manifest
6
+ * - Compiled page modules (inlined)
7
+ * - Runtime router
8
+ * - Shell HTML with router outlet
9
+ */
10
+
11
+ import fs from "fs"
12
+ import path from "path"
13
+ // Import new compiler
14
+ import { compile } from "@zenithbuild/compiler"
15
+ import { discoverComponents } from "./discovery/componentDiscovery"
16
+ import { discoverLayouts } from "./discovery/layouts"
17
+ import {
18
+ discoverPages,
19
+ generateRouteDefinition,
20
+ routePathToRegex
21
+ } from "@zenithbuild/router/manifest"
22
+
23
+ interface CompiledPage {
24
+ routePath: string
25
+ filePath: string
26
+ html: string
27
+ scripts: string[]
28
+ styles: string
29
+ score: number
30
+ paramNames: string[]
31
+ regex: RegExp
32
+ }
33
+
34
+ interface SPABuildOptions {
35
+ /** Pages directory */
36
+ pagesDir: string
37
+ /** Output directory */
38
+ outDir: string
39
+ /** Base directory for components/layouts */
40
+ baseDir?: string
41
+ }
42
+
43
+ /**
44
+ * Compile a single page file
45
+ */
46
+ async function compilePage(
47
+ pagePath: string,
48
+ pagesDir: string,
49
+ baseDir: string = process.cwd()
50
+ ): Promise<CompiledPage> {
51
+ try {
52
+ const srcDir = path.dirname(pagesDir)
53
+ const layoutsDir = path.join(srcDir, 'layouts')
54
+ const componentsDir = path.join(srcDir, 'components')
55
+
56
+ const layouts = discoverLayouts(layoutsDir)
57
+ const components = new Map([...layouts])
58
+
59
+ if (fs.existsSync(componentsDir)) {
60
+ const discovered = discoverComponents(componentsDir)
61
+ for (const [k, v] of discovered) {
62
+ components.set(k, v)
63
+ }
64
+ }
65
+
66
+ const source = fs.readFileSync(pagePath, 'utf-8')
67
+
68
+ // Use new unified compiler pipeline
69
+ const result = await compile(source, pagePath, {
70
+ components
71
+ })
72
+
73
+ if (!result.finalized) {
74
+ throw new Error(`Compilation failed: No finalized output`)
75
+ }
76
+
77
+ // Extract compiled output
78
+ const html = result.finalized.html
79
+ const js = result.finalized.js
80
+ const styles = result.finalized.styles
81
+
82
+ // Convert JS bundle to scripts array (for compatibility)
83
+ const scripts = js ? [js] : []
84
+
85
+ // Generate route definition
86
+ const routeDef = generateRouteDefinition(pagePath, pagesDir)
87
+ const regex = routePathToRegex(routeDef.path)
88
+
89
+ return {
90
+ routePath: routeDef.path,
91
+ filePath: pagePath,
92
+ html,
93
+ scripts,
94
+ styles,
95
+ score: routeDef.score,
96
+ paramNames: routeDef.paramNames,
97
+ regex
98
+ }
99
+ } catch (error: any) {
100
+ console.error(`[Zenith Build] Compilation failed for ${pagePath}:`, error.message)
101
+ throw error
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Generate the runtime router code (inlined into the bundle)
107
+ */
108
+ function generateRuntimeRouterCode(): string {
109
+ return `
110
+ // ============================================
111
+ // Zenith Runtime Router
112
+ // ============================================
113
+
114
+ (function() {
115
+ 'use strict';
116
+
117
+ // Current route state
118
+ let currentRoute = {
119
+ path: '/',
120
+ params: {},
121
+ query: {}
122
+ };
123
+
124
+ // Route listeners
125
+ const routeListeners = new Set();
126
+
127
+ // Router outlet element
128
+ let routerOutlet = null;
129
+
130
+ // Page modules registry
131
+ const pageModules = {};
132
+
133
+ // Route manifest
134
+ let routeManifest = [];
135
+
136
+ /**
137
+ * Parse query string
138
+ */
139
+ function parseQueryString(search) {
140
+ const query = {};
141
+ if (!search || search === '?') return query;
142
+ const params = new URLSearchParams(search);
143
+ params.forEach((value, key) => { query[key] = value; });
144
+ return query;
145
+ }
146
+
147
+ /**
148
+ * Resolve route from pathname
149
+ */
150
+ function resolveRoute(pathname) {
151
+ const normalizedPath = pathname === '' ? '/' : pathname;
152
+
153
+ for (const route of routeManifest) {
154
+ const match = route.regex.exec(normalizedPath);
155
+ if (match) {
156
+ const params = {};
157
+ for (let i = 0; i < route.paramNames.length; i++) {
158
+ const paramValue = match[i + 1];
159
+ if (paramValue !== undefined) {
160
+ params[route.paramNames[i]] = decodeURIComponent(paramValue);
161
+ }
162
+ }
163
+ return { record: route, params };
164
+ }
165
+ }
166
+ return null;
167
+ }
168
+
169
+ /**
170
+ * Clean up previous page
171
+ */
172
+ function cleanupPreviousPage() {
173
+ // Trigger unmount lifecycle hooks
174
+ if (window.__zenith && window.__zenith.triggerUnmount) {
175
+ window.__zenith.triggerUnmount();
176
+ }
177
+
178
+ // Remove previous page styles
179
+ document.querySelectorAll('style[data-zen-page-style]').forEach(s => s.remove());
180
+
181
+ // Clean up window properties (state variables, functions)
182
+ // This is important for proper state isolation between pages
183
+ if (window.__zenith_cleanup) {
184
+ window.__zenith_cleanup.forEach(key => {
185
+ try { delete window[key]; } catch(e) {}
186
+ });
187
+ }
188
+ window.__zenith_cleanup = [];
189
+ }
190
+
191
+ /**
192
+ * Inject styles
193
+ */
194
+ function injectStyles(styles) {
195
+ if (!styles) return;
196
+ const style = document.createElement('style');
197
+ style.setAttribute('data-zen-page-style', '0');
198
+ style.textContent = styles;
199
+ document.head.appendChild(style);
200
+ }
201
+
202
+ /**
203
+ * Execute scripts
204
+ */
205
+ function executeScripts(scripts) {
206
+ scripts.forEach(content => {
207
+ try {
208
+ const fn = new Function(content);
209
+ fn();
210
+ } catch (e) {
211
+ console.error('[Zenith Router] Script error:', e);
212
+ }
213
+ });
214
+ }
215
+
216
+ /**
217
+ * Render page
218
+ */
219
+ function renderPage(pageModule) {
220
+ if (!routerOutlet) {
221
+ console.warn('[Zenith Router] No router outlet');
222
+ return;
223
+ }
224
+
225
+ cleanupPreviousPage();
226
+ routerOutlet.innerHTML = pageModule.html;
227
+ injectStyles(pageModule.styles);
228
+ executeScripts(pageModule.scripts);
229
+
230
+ // Trigger mount lifecycle hooks after scripts are executed
231
+ if (window.__zenith && window.__zenith.triggerMount) {
232
+ window.__zenith.triggerMount();
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Notify listeners
238
+ */
239
+ function notifyListeners(route, prevRoute) {
240
+ routeListeners.forEach(listener => {
241
+ try { listener(route, prevRoute); } catch(e) {}
242
+ });
243
+ }
244
+
245
+ /**
246
+ * Resolve and render
247
+ */
248
+ function resolveAndRender(path, query, updateHistory, replace) {
249
+ replace = replace || false;
250
+ const prevRoute = { ...currentRoute };
251
+ const resolved = resolveRoute(path);
252
+
253
+ if (resolved) {
254
+ currentRoute = {
255
+ path,
256
+ params: resolved.params,
257
+ query,
258
+ matched: resolved.record
259
+ };
260
+
261
+ const pageModule = pageModules[resolved.record.path];
262
+ if (pageModule) {
263
+ renderPage(pageModule);
264
+ }
265
+ } else {
266
+ currentRoute = { path, params: {}, query, matched: undefined };
267
+ console.warn('[Zenith Router] No route matched:', path);
268
+
269
+ // Render 404 if available, otherwise show message
270
+ if (routerOutlet) {
271
+ routerOutlet.innerHTML = '<div style="padding: 2rem; text-align: center;"><h1>404</h1><p>Page not found</p></div>';
272
+ }
273
+ }
274
+
275
+ if (updateHistory) {
276
+ const url = path + (Object.keys(query).length ? '?' + new URLSearchParams(query) : '');
277
+ if (replace) {
278
+ window.history.replaceState(null, '', url);
279
+ } else {
280
+ window.history.pushState(null, '', url);
281
+ }
282
+ }
283
+
284
+ notifyListeners(currentRoute, prevRoute);
285
+ window.__zenith_route = currentRoute;
286
+ }
287
+
288
+ /**
289
+ * Handle popstate
290
+ */
291
+ function handlePopState() {
292
+ // Don't update history on popstate - browser already changed it
293
+ resolveAndRender(
294
+ window.location.pathname,
295
+ parseQueryString(window.location.search),
296
+ false,
297
+ false
298
+ );
299
+ }
300
+
301
+ /**
302
+ * Navigate (public API)
303
+ */
304
+ function navigate(to, options) {
305
+ options = options || {};
306
+ let path, query = {};
307
+
308
+ if (to.includes('?')) {
309
+ const parts = to.split('?');
310
+ path = parts[0];
311
+ query = parseQueryString('?' + parts[1]);
312
+ } else {
313
+ path = to;
314
+ }
315
+
316
+ if (!path.startsWith('/')) {
317
+ const currentDir = currentRoute.path.split('/').slice(0, -1).join('/');
318
+ path = currentDir + '/' + path;
319
+ }
320
+
321
+ // Normalize path for comparison
322
+ const normalizedPath = path === '' ? '/' : path;
323
+ const currentPath = currentRoute.path === '' ? '/' : currentRoute.path;
324
+
325
+ // Check if we're already on this path
326
+ const isSamePath = normalizedPath === currentPath;
327
+
328
+ // If same path and same query, don't navigate (idempotent)
329
+ if (isSamePath && JSON.stringify(query) === JSON.stringify(currentRoute.query)) {
330
+ return;
331
+ }
332
+
333
+ // Resolve and render with replace option if specified
334
+ resolveAndRender(path, query, true, options.replace || false);
335
+ }
336
+
337
+ /**
338
+ * Get current route
339
+ */
340
+ function getRoute() {
341
+ return { ...currentRoute };
342
+ }
343
+
344
+ /**
345
+ * Subscribe to route changes
346
+ */
347
+ function onRouteChange(listener) {
348
+ routeListeners.add(listener);
349
+ return () => routeListeners.delete(listener);
350
+ }
351
+
352
+ /**
353
+ * Check if path is active
354
+ */
355
+ function isActive(path, exact) {
356
+ if (exact) return currentRoute.path === path;
357
+ return currentRoute.path.startsWith(path);
358
+ }
359
+
360
+ /**
361
+ * Prefetch a route (preload page module)
362
+ */
363
+ const prefetchedRoutes = new Set();
364
+ function prefetch(path) {
365
+ const normalizedPath = path === '' ? '/' : path;
366
+ console.log('[Zenith Router] Prefetch requested for:', normalizedPath);
367
+
368
+ if (prefetchedRoutes.has(normalizedPath)) {
369
+ console.log('[Zenith Router] Route already prefetched:', normalizedPath);
370
+ return Promise.resolve();
371
+ }
372
+ prefetchedRoutes.add(normalizedPath);
373
+
374
+ // Find matching route
375
+ const resolved = resolveRoute(normalizedPath);
376
+ if (!resolved) {
377
+ console.warn('[Zenith Router] Prefetch: No route found for:', normalizedPath);
378
+ return Promise.resolve();
379
+ }
380
+
381
+ console.log('[Zenith Router] Prefetch: Route resolved:', resolved.record.path);
382
+
383
+ // Preload the module if it exists
384
+ if (pageModules[resolved.record.path]) {
385
+ console.log('[Zenith Router] Prefetch: Module already loaded:', resolved.record.path);
386
+ // Module already loaded
387
+ return Promise.resolve();
388
+ }
389
+
390
+ console.log('[Zenith Router] Prefetch: Module not yet loaded (all modules are pre-loaded in SPA build)');
391
+ // In SPA build, all modules are already loaded, so this is a no-op
392
+ // Could prefetch here if we had a way to load modules dynamically
393
+ return Promise.resolve();
394
+ }
395
+
396
+ /**
397
+ * Initialize router
398
+ */
399
+ function initRouter(manifest, modules, outlet) {
400
+ routeManifest = manifest;
401
+ Object.assign(pageModules, modules);
402
+
403
+ if (outlet) {
404
+ routerOutlet = typeof outlet === 'string'
405
+ ? document.querySelector(outlet)
406
+ : outlet;
407
+ }
408
+
409
+ window.addEventListener('popstate', handlePopState);
410
+
411
+ // Initial route resolution
412
+ resolveAndRender(
413
+ window.location.pathname,
414
+ parseQueryString(window.location.search),
415
+ false
416
+ );
417
+ }
418
+
419
+ // Expose router API globally
420
+ window.__zenith_router = {
421
+ navigate,
422
+ getRoute,
423
+ onRouteChange,
424
+ isActive,
425
+ prefetch,
426
+ initRouter
427
+ };
428
+
429
+ // Also expose navigate directly for convenience
430
+ window.navigate = navigate;
431
+
432
+ })();
433
+ `
434
+ }
435
+
436
+ /**
437
+ * Generate the Zen primitives runtime code
438
+ * This makes zen* primitives available globally for auto-imports
439
+ */
440
+ function generateZenPrimitivesRuntime(): string {
441
+ return `
442
+ // ============================================
443
+ // Zenith Reactivity Primitives Runtime
444
+ // ============================================
445
+ // Auto-imported zen* primitives are resolved from window.__zenith
446
+
447
+ (function() {
448
+ 'use strict';
449
+
450
+ // ============================================
451
+ // Dependency Tracking System
452
+ // ============================================
453
+
454
+ let currentEffect = null;
455
+ const effectStack = [];
456
+ let batchDepth = 0;
457
+ const pendingEffects = new Set();
458
+
459
+ function pushContext(effect) {
460
+ effectStack.push(currentEffect);
461
+ currentEffect = effect;
462
+ }
463
+
464
+ function popContext() {
465
+ currentEffect = effectStack.pop() || null;
466
+ }
467
+
468
+ function trackDependency(subscribers) {
469
+ if (currentEffect) {
470
+ subscribers.add(currentEffect);
471
+ currentEffect.dependencies.add(subscribers);
472
+ }
473
+ }
474
+
475
+ function notifySubscribers(subscribers) {
476
+ const effects = [...subscribers];
477
+ for (const effect of effects) {
478
+ if (batchDepth > 0) {
479
+ pendingEffects.add(effect);
480
+ } else {
481
+ effect.run();
482
+ }
483
+ }
484
+ }
485
+
486
+ function cleanupEffect(effect) {
487
+ for (const deps of effect.dependencies) {
488
+ deps.delete(effect);
489
+ }
490
+ effect.dependencies.clear();
491
+ }
492
+
493
+ // ============================================
494
+ // zenSignal - Atomic reactive value
495
+ // ============================================
496
+
497
+ function zenSignal(initialValue) {
498
+ let value = initialValue;
499
+ const subscribers = new Set();
500
+
501
+ function signal(newValue) {
502
+ if (arguments.length === 0) {
503
+ trackDependency(subscribers);
504
+ return value;
505
+ }
506
+ if (newValue !== value) {
507
+ value = newValue;
508
+ notifySubscribers(subscribers);
509
+ // Bridge to Phase 5 Hydration: Trigger global update
510
+ if (typeof window !== 'undefined' && window.__zenith_update && window.__ZENITH_STATE__) {
511
+ window.__zenith_update(window.__ZENITH_STATE__);
512
+ }
513
+ }
514
+ return value;
515
+ }
516
+
517
+ // Add .value property for Vue/Ref-like usage
518
+ Object.defineProperty(signal, 'value', {
519
+ get() {
520
+ return signal();
521
+ },
522
+ set(newValue) {
523
+ signal(newValue);
524
+ }
525
+ });
526
+
527
+ return signal;
528
+ }
529
+
530
+ // ============================================
531
+ // zenState - Deep reactive object
532
+ // ============================================
533
+
534
+ function zenState(initialObj) {
535
+ const subscribers = new Map(); // path -> Set of effects
536
+
537
+ function getSubscribers(path) {
538
+ if (!subscribers.has(path)) {
539
+ subscribers.set(path, new Set());
540
+ }
541
+ return subscribers.get(path);
542
+ }
543
+
544
+ function createProxy(obj, path = '') {
545
+ if (typeof obj !== 'object' || obj === null) return obj;
546
+
547
+ return new Proxy(obj, {
548
+ get(target, prop) {
549
+ const propPath = path ? path + '.' + String(prop) : String(prop);
550
+ trackDependency(getSubscribers(propPath));
551
+ const value = target[prop];
552
+ if (typeof value === 'object' && value !== null) {
553
+ return createProxy(value, propPath);
554
+ }
555
+ return value;
556
+ },
557
+ set(target, prop, value) {
558
+ const propPath = path ? path + '.' + String(prop) : String(prop);
559
+ target[prop] = value;
560
+ notifySubscribers(getSubscribers(propPath));
561
+ // Also notify parent path for nested updates
562
+ if (path) {
563
+ notifySubscribers(getSubscribers(path));
564
+ }
565
+ return true;
566
+ }
567
+ });
568
+ }
569
+
570
+ return createProxy(initialObj);
571
+ }
572
+
573
+ // ============================================
574
+ // zenEffect - Auto-tracked side effect
575
+ // ============================================
576
+
577
+ function zenEffect(fn) {
578
+ const effect = {
579
+ fn,
580
+ dependencies: new Set(),
581
+ run() {
582
+ cleanupEffect(this);
583
+ pushContext(this);
584
+ try {
585
+ this.fn();
586
+ } finally {
587
+ popContext();
588
+ }
589
+ },
590
+ dispose() {
591
+ cleanupEffect(this);
592
+ }
593
+ };
594
+
595
+ effect.run();
596
+ return () => effect.dispose();
597
+ }
598
+
599
+ // ============================================
600
+ // zenMemo - Cached computed value
601
+ // ============================================
602
+
603
+ function zenMemo(fn) {
604
+ let cachedValue;
605
+ let dirty = true;
606
+ const subscribers = new Set();
607
+
608
+ const effect = {
609
+ dependencies: new Set(),
610
+ run() {
611
+ dirty = true;
612
+ notifySubscribers(subscribers);
613
+ }
614
+ };
615
+
616
+ function compute() {
617
+ if (dirty) {
618
+ cleanupEffect(effect);
619
+ pushContext(effect);
620
+ try {
621
+ cachedValue = fn();
622
+ dirty = false;
623
+ } finally {
624
+ popContext();
625
+ }
626
+ }
627
+ trackDependency(subscribers);
628
+ return cachedValue;
629
+ }
630
+
631
+ return compute;
632
+ }
633
+
634
+ // ============================================
635
+ // zenRef - Non-reactive mutable container
636
+ // ============================================
637
+
638
+ function zenRef(initialValue) {
639
+ return { current: initialValue !== undefined ? initialValue : null };
640
+ }
641
+
642
+ // ============================================
643
+ // zenBatch - Batch updates
644
+ // ============================================
645
+
646
+ function zenBatch(fn) {
647
+ batchDepth++;
648
+ try {
649
+ fn();
650
+ } finally {
651
+ batchDepth--;
652
+ if (batchDepth === 0) {
653
+ const effects = [...pendingEffects];
654
+ pendingEffects.clear();
655
+ for (const effect of effects) {
656
+ effect.run();
657
+ }
658
+ }
659
+ }
660
+ }
661
+
662
+ // ============================================
663
+ // zenUntrack - Read without tracking
664
+ // ============================================
665
+
666
+ function zenUntrack(fn) {
667
+ const prevEffect = currentEffect;
668
+ currentEffect = null;
669
+ try {
670
+ return fn();
671
+ } finally {
672
+ currentEffect = prevEffect;
673
+ }
674
+ }
675
+
676
+ // ============================================
677
+ // Lifecycle Hooks
678
+ // ============================================
679
+
680
+ const mountCallbacks = [];
681
+ const unmountCallbacks = [];
682
+ let isMounted = false;
683
+
684
+ function zenOnMount(fn) {
685
+ if (isMounted) {
686
+ // Already mounted, run immediately
687
+ const cleanup = fn();
688
+ if (typeof cleanup === 'function') {
689
+ unmountCallbacks.push(cleanup);
690
+ }
691
+ } else {
692
+ mountCallbacks.push(fn);
693
+ }
694
+ }
695
+
696
+ function zenOnUnmount(fn) {
697
+ unmountCallbacks.push(fn);
698
+ }
699
+
700
+ // Called by router when page mounts
701
+ function triggerMount() {
702
+ isMounted = true;
703
+ for (const cb of mountCallbacks) {
704
+ const cleanup = cb();
705
+ if (typeof cleanup === 'function') {
706
+ unmountCallbacks.push(cleanup);
707
+ }
708
+ }
709
+ mountCallbacks.length = 0;
710
+ }
711
+
712
+ // Called by router when page unmounts
713
+ function triggerUnmount() {
714
+ isMounted = false;
715
+ for (const cb of unmountCallbacks) {
716
+ try { cb(); } catch(e) { console.error('[Zenith] Unmount error:', e); }
717
+ }
718
+ unmountCallbacks.length = 0;
719
+ }
720
+
721
+ // ============================================
722
+ // Export to window.__zenith
723
+ // ============================================
724
+
725
+ window.__zenith = Object.assign(window.__zenith || {}, {
726
+ // Reactivity primitives
727
+ signal: zenSignal,
728
+ state: zenState,
729
+ effect: zenEffect,
730
+ memo: zenMemo,
731
+ ref: zenRef,
732
+ batch: zenBatch,
733
+ untrack: zenUntrack,
734
+ // Lifecycle
735
+ onMount: zenOnMount,
736
+ onUnmount: zenOnUnmount,
737
+ // Internal hooks for router
738
+ triggerMount,
739
+ triggerUnmount
740
+ });
741
+
742
+ // Also expose with zen* prefix for direct usage
743
+ window.zenSignal = zenSignal;
744
+ window.zenState = zenState;
745
+ window.zenEffect = zenEffect;
746
+ window.zenMemo = zenMemo;
747
+ window.zenRef = zenRef;
748
+ window.zenBatch = zenBatch;
749
+ window.zenUntrack = zenUntrack;
750
+ window.zenOnMount = zenOnMount;
751
+ window.zenOnUnmount = zenOnUnmount;
752
+
753
+ // Clean aliases
754
+ window.signal = zenSignal;
755
+ window.state = zenState;
756
+ window.effect = zenEffect;
757
+ window.memo = zenMemo;
758
+ window.ref = zenRef;
759
+ window.batch = zenBatch;
760
+ window.untrack = zenUntrack;
761
+ window.onMount = zenOnMount;
762
+ window.onUnmount = zenOnUnmount;
763
+
764
+ })();
765
+ `
766
+ }
767
+
768
+ /**
769
+ * Generate the HTML shell
770
+ */
771
+ function generateHTMLShell(
772
+ pages: CompiledPage[],
773
+ layoutStyles: string[]
774
+ ): string {
775
+ // Collect all global styles (from layouts)
776
+ const globalStyles = layoutStyles.join("\n")
777
+
778
+ // Generate route manifest JavaScript
779
+ const manifestJS = pages.map(page => ({
780
+ path: page.routePath,
781
+ regex: page.regex.toString(),
782
+ paramNames: page.paramNames,
783
+ score: page.score,
784
+ filePath: page.filePath
785
+ }))
786
+
787
+ // Generate page modules JavaScript
788
+ const modulesJS = pages.map(page => {
789
+ const escapedHtml = JSON.stringify(page.html)
790
+ const escapedScripts = JSON.stringify(page.scripts)
791
+ const escapedStyles = JSON.stringify(page.styles)
792
+
793
+ return `${JSON.stringify(page.routePath)}: {
794
+ html: ${escapedHtml},
795
+ scripts: ${escapedScripts},
796
+ styles: ${escapedStyles}
797
+ }`
798
+ }).join(",\n ")
799
+
800
+ // Generate manifest with actual RegExp objects
801
+ const manifestCode = `[
802
+ ${pages.map(page => `{
803
+ path: ${JSON.stringify(page.routePath)},
804
+ regex: ${page.regex.toString()},
805
+ paramNames: ${JSON.stringify(page.paramNames)},
806
+ score: ${page.score}
807
+ }`).join(",\n ")}
808
+ ]`
809
+
810
+ return `<!DOCTYPE html>
811
+ <html lang="en">
812
+ <head>
813
+ <meta charset="UTF-8">
814
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
815
+ <title>Zenith App</title>
816
+ <link rel="icon" type="image/x-icon" href="./favicon.ico">
817
+ <style>
818
+ /* Global/Layout Styles */
819
+ ${globalStyles}
820
+ </style>
821
+ </head>
822
+ <body>
823
+ <!-- Router Outlet -->
824
+ <div id="app"></div>
825
+
826
+ <!-- Zenith Primitives Runtime -->
827
+ <script>
828
+ ${generateZenPrimitivesRuntime()}
829
+ </script>
830
+
831
+ <!-- Zenith Runtime Router -->
832
+ <script>
833
+ ${generateRuntimeRouterCode()}
834
+ </script>
835
+
836
+ <!-- Route Manifest & Page Modules -->
837
+ <script>
838
+ (function() {
839
+ // Route manifest (sorted by score, highest first)
840
+ const manifest = ${manifestCode};
841
+
842
+ // Page modules keyed by route path
843
+ const modules = {
844
+ ${modulesJS}
845
+ };
846
+
847
+ // Initialize router when DOM is ready
848
+ if (document.readyState === 'loading') {
849
+ document.addEventListener('DOMContentLoaded', function() {
850
+ window.__zenith_router.initRouter(manifest, modules, '#app');
851
+ });
852
+ } else {
853
+ window.__zenith_router.initRouter(manifest, modules, '#app');
854
+ }
855
+ })();
856
+ </script>
857
+ </body>
858
+ </html>`
859
+ }
860
+
861
+ /**
862
+ * Build SPA from pages directory
863
+ */
864
+ export async function buildSPA(options: SPABuildOptions): Promise<void> {
865
+ const { pagesDir, outDir, baseDir } = options
866
+
867
+ // Clean output directory
868
+ if (fs.existsSync(outDir)) {
869
+ fs.rmSync(outDir, { recursive: true, force: true })
870
+ }
871
+ fs.mkdirSync(outDir, { recursive: true })
872
+
873
+ // Discover all pages
874
+ const pageFiles = discoverPages(pagesDir)
875
+
876
+ if (pageFiles.length === 0) {
877
+ console.warn("[Zenith Build] No pages found in", pagesDir)
878
+ return
879
+ }
880
+
881
+
882
+
883
+ // Compile all pages
884
+ const compiledPages: CompiledPage[] = []
885
+ const layoutStyles: string[] = []
886
+
887
+ for (const pageFile of pageFiles) {
888
+
889
+
890
+ try {
891
+ const compiled = await compilePage(pageFile, pagesDir)
892
+ compiledPages.push(compiled)
893
+ } catch (error) {
894
+ console.error(`[Zenith Build] Error compiling ${pageFile}:`, error)
895
+ throw error
896
+ }
897
+ }
898
+
899
+ // Sort pages by score (highest first)
900
+ compiledPages.sort((a, b) => b.score - a.score)
901
+
902
+ // Extract layout styles (they should be global)
903
+ // For now, we'll include any styles from the first page that uses a layout
904
+ // TODO: Better layout handling
905
+
906
+ // Generate HTML shell
907
+ const htmlShell = generateHTMLShell(compiledPages, layoutStyles)
908
+
909
+ // Write index.html
910
+ fs.writeFileSync(path.join(outDir, "index.html"), htmlShell)
911
+
912
+ // Copy favicon if it exists
913
+ const faviconPath = path.join(path.dirname(pagesDir), "favicon.ico")
914
+ if (fs.existsSync(faviconPath)) {
915
+ fs.copyFileSync(faviconPath, path.join(outDir, "favicon.ico"))
916
+ }
917
+
918
+
919
+
920
+ // Log route manifest
921
+
922
+ }
923
+
924
+ /**
925
+ * Watch mode for development (future)
926
+ */
927
+ export function watchSPA(_options: SPABuildOptions): void {
928
+ // TODO: Implement file watching
929
+
930
+ }
931
+