@zenithbuild/compiler 1.3.2 → 1.3.9

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