@coherent.js/runtime 1.0.0-beta.2

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,3254 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/runtimes/browser.js
18
+ var browser_exports = {};
19
+ __export(browser_exports, {
20
+ BrowserRuntime: () => BrowserRuntime
21
+ });
22
+ import { render, withState, memo } from "@coherent.js/core";
23
+ import { hydrate, autoHydrate, makeHydratable } from "@coherent.js/client";
24
+ import { integrateWithWebComponents, defineCoherentElement } from "@coherent.js/web-components";
25
+ var BrowserRuntime;
26
+ var init_browser = __esm({
27
+ "src/runtimes/browser.js"() {
28
+ "use strict";
29
+ BrowserRuntime = class _BrowserRuntime {
30
+ constructor(options = {}) {
31
+ this.options = {
32
+ autoHydrate: true,
33
+ enableWebComponents: true,
34
+ enablePerformanceMonitoring: true,
35
+ routingMode: "hash",
36
+ // 'hash', 'history', or 'memory'
37
+ ...options
38
+ };
39
+ this.componentRegistry = /* @__PURE__ */ new Map();
40
+ this.routeRegistry = /* @__PURE__ */ new Map();
41
+ this.currentRoute = null;
42
+ this.isInitialized = false;
43
+ this.renderMetrics = [];
44
+ this.startTime = Date.now();
45
+ }
46
+ async initialize() {
47
+ if (this.isInitialized) return;
48
+ if (document.readyState === "loading") {
49
+ await new Promise((resolve) => {
50
+ document.addEventListener("DOMContentLoaded", resolve);
51
+ });
52
+ }
53
+ if (this.options.enableWebComponents) {
54
+ await this.initializeWebComponents();
55
+ }
56
+ if (this.options.routingMode !== "none") {
57
+ this.initializeRouting();
58
+ }
59
+ if (this.options.autoHydrate) {
60
+ await this.autoHydrate();
61
+ }
62
+ if (this.options.enablePerformanceMonitoring) {
63
+ this.initializePerformanceMonitoring();
64
+ }
65
+ this.isInitialized = true;
66
+ }
67
+ async initializeWebComponents() {
68
+ try {
69
+ await integrateWithWebComponents(
70
+ Object.fromEntries(this.componentRegistry),
71
+ this.options.webComponents || {}
72
+ );
73
+ } catch (error) {
74
+ console.warn("Failed to initialize Web Components:", error);
75
+ }
76
+ }
77
+ initializeRouting() {
78
+ const handleRouteChange = () => {
79
+ const newRoute = this.getCurrentRoute();
80
+ if (newRoute !== this.currentRoute) {
81
+ this.handleRouteChange(this.currentRoute, newRoute);
82
+ this.currentRoute = newRoute;
83
+ }
84
+ };
85
+ if (this.options.routingMode === "hash") {
86
+ window.addEventListener("hashchange", handleRouteChange);
87
+ } else if (this.options.routingMode === "history") {
88
+ window.addEventListener("popstate", handleRouteChange);
89
+ }
90
+ this.currentRoute = this.getCurrentRoute();
91
+ handleRouteChange();
92
+ }
93
+ getCurrentRoute() {
94
+ if (this.options.routingMode === "hash") {
95
+ return window.location.hash.slice(1) || "/";
96
+ } else if (this.options.routingMode === "history") {
97
+ return window.location.pathname;
98
+ }
99
+ return "/";
100
+ }
101
+ handleRouteChange(oldRoute, newRoute) {
102
+ const handler = this.routeRegistry.get(newRoute) || this.routeRegistry.get("*");
103
+ if (handler) {
104
+ try {
105
+ handler({ route: newRoute, oldRoute, params: this.parseRouteParams(newRoute) });
106
+ } catch (error) {
107
+ console.error("Route handler error:", error);
108
+ }
109
+ }
110
+ }
111
+ parseRouteParams(route) {
112
+ const params = {};
113
+ const parts = route.split("/").filter(Boolean);
114
+ parts.forEach((part, index) => {
115
+ if (part.startsWith(":")) {
116
+ const key = part.slice(1);
117
+ const value = parts[index];
118
+ if (value && !value.startsWith(":")) {
119
+ params[key] = value;
120
+ }
121
+ }
122
+ });
123
+ return params;
124
+ }
125
+ initializePerformanceMonitoring() {
126
+ if (typeof window === "undefined" || typeof window.PerformanceObserver === "undefined") return;
127
+ const observer = new window.PerformanceObserver((list) => {
128
+ for (const entry of list.getEntries()) {
129
+ if (entry.name.includes("coherent")) {
130
+ this.renderMetrics.push({
131
+ name: entry.name,
132
+ duration: entry.duration,
133
+ startTime: entry.startTime,
134
+ timestamp: Date.now()
135
+ });
136
+ }
137
+ }
138
+ });
139
+ try {
140
+ observer.observe({ entryTypes: ["measure", "mark"] });
141
+ } catch (error) {
142
+ console.warn("Performance monitoring not available:", error);
143
+ }
144
+ setInterval(() => {
145
+ const cutoff = Date.now() - 3e5;
146
+ this.renderMetrics = this.renderMetrics.filter((m) => m.timestamp > cutoff);
147
+ }, 6e4);
148
+ }
149
+ // Component management
150
+ registerComponent(name, component, options = {}) {
151
+ const hydratableComponent = makeHydratable(component, {
152
+ componentName: name,
153
+ ...options
154
+ });
155
+ this.componentRegistry.set(name, hydratableComponent);
156
+ if (this.options.enableWebComponents && this.isInitialized) {
157
+ try {
158
+ defineCoherentElement(name, hydratableComponent, options);
159
+ } catch (error) {
160
+ console.warn(`Failed to register Web Component ${name}:`, error);
161
+ }
162
+ }
163
+ return hydratableComponent;
164
+ }
165
+ getComponent(name) {
166
+ return this.componentRegistry.get(name);
167
+ }
168
+ // Routing
169
+ addRoute(path, handler) {
170
+ this.routeRegistry.set(path, handler);
171
+ }
172
+ navigate(path) {
173
+ if (this.options.routingMode === "hash") {
174
+ window.location.hash = path;
175
+ } else if (this.options.routingMode === "history") {
176
+ window.history.pushState({}, "", path);
177
+ this.handleRouteChange(this.currentRoute, path);
178
+ this.currentRoute = path;
179
+ }
180
+ }
181
+ // Rendering
182
+ async render(component, props = {}, target = null) {
183
+ const startMark = `coherent-render-start-${Date.now()}`;
184
+ const endMark = `coherent-render-end-${Date.now()}`;
185
+ try {
186
+ performance.mark(startMark);
187
+ const resolvedComponent = typeof component === "string" ? this.getComponent(component) : component;
188
+ if (!resolvedComponent) {
189
+ throw new Error(`Component not found: ${component}`);
190
+ }
191
+ const vdom = resolvedComponent(props);
192
+ const html = render(vdom);
193
+ let targetElement = target;
194
+ if (typeof target === "string") {
195
+ targetElement = document.querySelector(target);
196
+ }
197
+ if (!targetElement) {
198
+ targetElement = document.body;
199
+ }
200
+ targetElement.innerHTML = html;
201
+ const instance = await hydrate(targetElement.firstElementChild, resolvedComponent, props);
202
+ performance.mark(endMark);
203
+ performance.measure(`coherent-render-${resolvedComponent.name || "anonymous"}`, startMark, endMark);
204
+ return instance;
205
+ } catch (error) {
206
+ performance.mark(endMark);
207
+ console.error("Render error:", error);
208
+ throw error;
209
+ }
210
+ }
211
+ // Create a complete app
212
+ async createApp(_options = {}) {
213
+ await this.initialize();
214
+ return {
215
+ // Component management
216
+ component: (name, component, opts) => this.registerComponent(name, component, opts),
217
+ // Routing
218
+ route: (path, handler) => this.addRoute(path, handler),
219
+ navigate: (path) => this.navigate(path),
220
+ // Rendering
221
+ render: (component, props, target) => this.render(component, props, target),
222
+ // State management
223
+ state: withState,
224
+ memo,
225
+ // Hydration
226
+ hydrate: (element, component, props) => hydrate(element, component, props),
227
+ // Utilities
228
+ getRuntime: () => this,
229
+ getCurrentRoute: () => this.currentRoute,
230
+ getPerformanceMetrics: () => [...this.renderMetrics],
231
+ // Lifecycle
232
+ mount: async (component, target = "#app") => {
233
+ const app = await this.render(component, {}, target);
234
+ return app;
235
+ },
236
+ unmount: (target = "#app") => {
237
+ const element = typeof target === "string" ? document.querySelector(target) : target;
238
+ if (element) {
239
+ element.innerHTML = "";
240
+ }
241
+ }
242
+ };
243
+ }
244
+ // Auto-hydration
245
+ async autoHydrate() {
246
+ const componentMap = Object.fromEntries(this.componentRegistry);
247
+ await autoHydrate(componentMap);
248
+ }
249
+ // Static methods for quick setup
250
+ static async createQuickApp(components = {}, options = {}) {
251
+ const runtime = new _BrowserRuntime(options);
252
+ Object.entries(components).forEach(([name, component]) => {
253
+ runtime.registerComponent(name, component);
254
+ });
255
+ return await runtime.createApp(options);
256
+ }
257
+ static async renderToPage(component, props = {}, target = "#app") {
258
+ const runtime = new _BrowserRuntime({ autoHydrate: false });
259
+ await runtime.initialize();
260
+ return await runtime.render(component, props, target);
261
+ }
262
+ // Performance utilities
263
+ getPerformanceReport() {
264
+ const now = Date.now();
265
+ const uptime = now - this.startTime;
266
+ const recentMetrics = this.renderMetrics.filter((m) => m.timestamp >= now - 6e4);
267
+ const averageRenderTime = recentMetrics.length > 0 ? recentMetrics.reduce((sum, m) => sum + m.duration, 0) / recentMetrics.length : 0;
268
+ return {
269
+ uptime,
270
+ totalRenders: this.renderMetrics.length,
271
+ recentRenders: recentMetrics.length,
272
+ averageRenderTime: Math.round(averageRenderTime * 100) / 100,
273
+ registeredComponents: this.componentRegistry.size,
274
+ registeredRoutes: this.routeRegistry.size,
275
+ currentRoute: this.currentRoute,
276
+ memoryUsage: this.getMemoryUsage()
277
+ };
278
+ }
279
+ getMemoryUsage() {
280
+ if (typeof performance !== "undefined" && performance.memory) {
281
+ return {
282
+ used: Math.round(performance.memory.usedJSHeapSize / 1024 / 1024),
283
+ total: Math.round(performance.memory.totalJSHeapSize / 1024 / 1024),
284
+ limit: Math.round(performance.memory.jsHeapSizeLimit / 1024 / 1024)
285
+ };
286
+ }
287
+ return null;
288
+ }
289
+ // Development utilities
290
+ debug() {
291
+ return {
292
+ runtime: this,
293
+ components: Array.from(this.componentRegistry.keys()),
294
+ routes: Array.from(this.routeRegistry.keys()),
295
+ performance: this.getPerformanceReport(),
296
+ options: this.options
297
+ };
298
+ }
299
+ };
300
+ }
301
+ });
302
+
303
+ // src/runtimes/edge.js
304
+ var edge_exports = {};
305
+ __export(edge_exports, {
306
+ EdgeRuntime: () => EdgeRuntime2,
307
+ createBunHandler: () => createBunHandler,
308
+ createCloudflareWorker: () => createCloudflareWorker,
309
+ createDenoHandler: () => createDenoHandler
310
+ });
311
+ import { render as render2 } from "@coherent.js/core";
312
+ function createCloudflareWorker(app) {
313
+ return {
314
+ async fetch(request, _env, _ctx) {
315
+ return await app.fetch(request);
316
+ }
317
+ };
318
+ }
319
+ function createDenoHandler(app) {
320
+ return async (request) => {
321
+ return await app.fetch(request);
322
+ };
323
+ }
324
+ function createBunHandler(app) {
325
+ return {
326
+ async fetch(request) {
327
+ return await app.fetch(request);
328
+ },
329
+ port: 3e3
330
+ };
331
+ }
332
+ var EdgeRuntime2;
333
+ var init_edge = __esm({
334
+ "src/runtimes/edge.js"() {
335
+ "use strict";
336
+ EdgeRuntime2 = class _EdgeRuntime {
337
+ constructor(options = {}) {
338
+ this.options = {
339
+ caching: true,
340
+ streaming: false,
341
+ headers: {
342
+ "Content-Type": "text/html; charset=utf-8",
343
+ "Cache-Control": "public, max-age=3600",
344
+ ...options.headers
345
+ },
346
+ ...options
347
+ };
348
+ this.componentRegistry = /* @__PURE__ */ new Map();
349
+ this.routeRegistry = /* @__PURE__ */ new Map();
350
+ this.cache = /* @__PURE__ */ new Map();
351
+ this.middleware = [];
352
+ this.renderCount = 0;
353
+ if (this.options.caching) {
354
+ this.initializeCacheCleanup();
355
+ }
356
+ }
357
+ initializeCacheCleanup() {
358
+ if (typeof setInterval !== "undefined") {
359
+ setInterval(() => {
360
+ if (this.cache.size > 1e3) {
361
+ const entries = Array.from(this.cache.entries());
362
+ const toDelete = entries.slice(0, entries.length - 500);
363
+ toDelete.forEach(([key]) => this.cache.delete(key));
364
+ }
365
+ }, 3e5);
366
+ }
367
+ }
368
+ // Component management
369
+ registerComponent(name, component) {
370
+ this.componentRegistry.set(name, component);
371
+ return component;
372
+ }
373
+ getComponent(name) {
374
+ return this.componentRegistry.get(name);
375
+ }
376
+ // Route management
377
+ addRoute(pattern, handler) {
378
+ this.routeRegistry.set(pattern, handler);
379
+ }
380
+ matchRoute(pathname) {
381
+ for (const [pattern, handler] of this.routeRegistry) {
382
+ const match = this.matchPattern(pattern, pathname);
383
+ if (match) {
384
+ return { handler, params: match.params };
385
+ }
386
+ }
387
+ return null;
388
+ }
389
+ matchPattern(pattern, pathname) {
390
+ if (pattern === "*" || pattern === pathname) {
391
+ return { params: {} };
392
+ }
393
+ const patternParts = pattern.split("/").filter(Boolean);
394
+ const pathParts = pathname.split("/").filter(Boolean);
395
+ if (patternParts.length !== pathParts.length) {
396
+ return null;
397
+ }
398
+ const params = {};
399
+ for (let i = 0; i < patternParts.length; i++) {
400
+ const patternPart = patternParts[i];
401
+ const pathPart = pathParts[i];
402
+ if (patternPart.startsWith(":")) {
403
+ params[patternPart.slice(1)] = pathPart;
404
+ } else if (patternPart !== pathPart) {
405
+ return null;
406
+ }
407
+ }
408
+ return { params };
409
+ }
410
+ // Rendering
411
+ async renderComponent(component, props = {}, options = {}) {
412
+ const _startTime = Date.now();
413
+ try {
414
+ const resolvedComponent = typeof component === "string" ? this.getComponent(component) : component;
415
+ if (!resolvedComponent) {
416
+ throw new Error(`Component not found: ${component}`);
417
+ }
418
+ const cacheKey = this.generateCacheKey(resolvedComponent, props);
419
+ if (this.options.caching && this.cache.has(cacheKey)) {
420
+ const cached = this.cache.get(cacheKey);
421
+ if (Date.now() - cached.timestamp < (options.cacheMaxAge || 3e5)) {
422
+ return cached.html;
423
+ }
424
+ this.cache.delete(cacheKey);
425
+ }
426
+ const vdom = resolvedComponent(props);
427
+ const html = render2(vdom);
428
+ if (this.options.caching && options.cacheable !== false) {
429
+ this.cache.set(cacheKey, {
430
+ html,
431
+ timestamp: Date.now()
432
+ });
433
+ }
434
+ this.renderCount++;
435
+ return html;
436
+ } catch (error) {
437
+ console.error("Edge render error:", error);
438
+ throw error;
439
+ } finally {
440
+ if (typeof performance !== "undefined" && performance.mark) {
441
+ performance.mark(`coherent-edge-render-${Date.now()}`);
442
+ }
443
+ }
444
+ }
445
+ generateCacheKey(component, props) {
446
+ const componentName = component.name || "anonymous";
447
+ const propsHash = this.hashObject(props);
448
+ return `${componentName}-${propsHash}`;
449
+ }
450
+ hashObject(obj) {
451
+ const str = JSON.stringify(obj, Object.keys(obj).sort());
452
+ let hash = 0;
453
+ for (let i = 0; i < str.length; i++) {
454
+ const char = str.charCodeAt(i);
455
+ hash = (hash << 5) - hash + char;
456
+ hash = hash & hash;
457
+ }
458
+ return hash.toString(36);
459
+ }
460
+ // HTTP Request handling
461
+ async handleRequest(request) {
462
+ try {
463
+ const url = new URL(request.url);
464
+ const pathname = url.pathname;
465
+ const context = {
466
+ request,
467
+ url,
468
+ pathname,
469
+ params: {},
470
+ searchParams: Object.fromEntries(url.searchParams),
471
+ method: request.method,
472
+ headers: Object.fromEntries(request.headers),
473
+ runtime: this,
474
+ state: {}
475
+ // Shared state for middleware
476
+ };
477
+ let middlewareIndex = 0;
478
+ const next = async () => {
479
+ if (middlewareIndex < this.middleware.length) {
480
+ const middleware = this.middleware[middlewareIndex++];
481
+ return await middleware(context, next);
482
+ }
483
+ };
484
+ if (this.middleware.length > 0) {
485
+ await next();
486
+ }
487
+ if (context.response) {
488
+ return context.response;
489
+ }
490
+ const match = this.matchRoute(pathname);
491
+ if (!match) {
492
+ return this.createErrorResponse(404, "Not Found");
493
+ }
494
+ context.params = match.params;
495
+ const result = await match.handler(context);
496
+ if (result instanceof Response) {
497
+ return result;
498
+ }
499
+ if (typeof result === "string") {
500
+ return this.createHtmlResponse(result);
501
+ }
502
+ if (result && typeof result === "object") {
503
+ if (result.component) {
504
+ const html = await this.renderComponent(
505
+ result.component,
506
+ result.props || {},
507
+ result.options || {}
508
+ );
509
+ return this.createHtmlResponse(html, result.status, result.headers);
510
+ }
511
+ if (result.json) {
512
+ return this.createJsonResponse(result.json, result.status, result.headers);
513
+ }
514
+ if (result.redirect) {
515
+ return Response.redirect(result.redirect, result.status || 302);
516
+ }
517
+ }
518
+ return this.createJsonResponse(result);
519
+ } catch (error) {
520
+ console.error("Request handling error:", error);
521
+ return this.createErrorResponse(500, "Internal Server Error");
522
+ }
523
+ }
524
+ createHtmlResponse(html, status = 200, customHeaders = {}) {
525
+ return new Response(html, {
526
+ status,
527
+ headers: {
528
+ ...this.options.headers,
529
+ ...customHeaders
530
+ }
531
+ });
532
+ }
533
+ createJsonResponse(data, status = 200, customHeaders = {}) {
534
+ return new Response(JSON.stringify(data), {
535
+ status,
536
+ headers: {
537
+ "Content-Type": "application/json",
538
+ ...customHeaders
539
+ }
540
+ });
541
+ }
542
+ createErrorResponse(status, message) {
543
+ const errorHtml = `
544
+ <!DOCTYPE html>
545
+ <html>
546
+ <head>
547
+ <title>Error ${status}</title>
548
+ <style>
549
+ body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
550
+ h1 { color: #e74c3c; }
551
+ </style>
552
+ </head>
553
+ <body>
554
+ <h1>Error ${status}</h1>
555
+ <p>${message}</p>
556
+ </body>
557
+ </html>
558
+ `;
559
+ return new Response(errorHtml, {
560
+ status,
561
+ headers: { "Content-Type": "text/html; charset=utf-8" }
562
+ });
563
+ }
564
+ // API Routes
565
+ async handleApiRequest(request, handler) {
566
+ try {
567
+ const url = new URL(request.url);
568
+ const context = {
569
+ request,
570
+ url,
571
+ method: request.method,
572
+ headers: Object.fromEntries(request.headers),
573
+ searchParams: Object.fromEntries(url.searchParams),
574
+ runtime: this
575
+ };
576
+ if (request.method === "POST" || request.method === "PUT") {
577
+ const contentType = request.headers.get("content-type") || "";
578
+ if (contentType.includes("application/json")) {
579
+ context.body = await request.json();
580
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
581
+ const formData = await request.formData();
582
+ context.body = Object.fromEntries(formData);
583
+ } else {
584
+ context.body = await request.text();
585
+ }
586
+ }
587
+ const result = await handler(context);
588
+ if (result instanceof Response) {
589
+ return result;
590
+ }
591
+ return this.createJsonResponse(result);
592
+ } catch (error) {
593
+ console.error("API request error:", error);
594
+ return this.createJsonResponse({ error: error.message }, 500);
595
+ }
596
+ }
597
+ // Streaming support (for environments that support it)
598
+ async renderStream(component, props = {}) {
599
+ if (!this.options.streaming) {
600
+ return await this.renderComponent(component, props);
601
+ }
602
+ const encoder = new TextEncoder();
603
+ let buffer = "";
604
+ const chunkSize = this.options.streamChunkSize || 1024;
605
+ const stream = new ReadableStream({
606
+ async start(controller) {
607
+ try {
608
+ const flush = () => {
609
+ if (buffer.length > 0) {
610
+ controller.enqueue(encoder.encode(buffer));
611
+ buffer = "";
612
+ }
613
+ };
614
+ const renderNode = async (node) => {
615
+ if (!node || typeof node !== "object") {
616
+ if (node !== null && node !== void 0) {
617
+ buffer += String(node);
618
+ if (buffer.length >= chunkSize) {
619
+ flush();
620
+ }
621
+ }
622
+ return;
623
+ }
624
+ if (Array.isArray(node)) {
625
+ for (const child of node) {
626
+ await renderNode(child);
627
+ }
628
+ return;
629
+ }
630
+ for (const [tag, content] of Object.entries(node)) {
631
+ if (typeof content === "object" && content !== null) {
632
+ buffer += `<${tag}`;
633
+ for (const [key, value] of Object.entries(content)) {
634
+ if (key !== "children" && key !== "text" && value !== void 0) {
635
+ buffer += ` ${key}="${String(value)}"`;
636
+ }
637
+ }
638
+ buffer += ">";
639
+ if (buffer.length >= chunkSize) {
640
+ flush();
641
+ }
642
+ if (content.text) {
643
+ buffer += String(content.text);
644
+ if (buffer.length >= chunkSize) {
645
+ flush();
646
+ }
647
+ }
648
+ if (content.children) {
649
+ await renderNode(content.children);
650
+ }
651
+ buffer += `</${tag}>`;
652
+ if (buffer.length >= chunkSize) {
653
+ flush();
654
+ }
655
+ } else {
656
+ buffer += `<${tag}>${String(content)}</${tag}>`;
657
+ if (buffer.length >= chunkSize) {
658
+ flush();
659
+ }
660
+ }
661
+ }
662
+ };
663
+ await renderNode(component);
664
+ flush();
665
+ controller.close();
666
+ } catch (error) {
667
+ controller.error(error);
668
+ }
669
+ }
670
+ });
671
+ return new Response(stream, {
672
+ headers: {
673
+ "Content-Type": "text/html; charset=utf-8",
674
+ "Transfer-Encoding": "chunked"
675
+ }
676
+ });
677
+ }
678
+ // Create app factory
679
+ createApp() {
680
+ const app = {
681
+ // Component registration
682
+ component: (name, component, opts) => this.registerComponent(name, component, opts),
683
+ // Routing
684
+ get: (pattern, handler) => this.addRoute(pattern, handler),
685
+ post: (pattern, handler) => this.addRoute(pattern, handler),
686
+ put: (pattern, handler) => this.addRoute(pattern, handler),
687
+ delete: (pattern, handler) => this.addRoute(pattern, handler),
688
+ route: (pattern, handler) => this.addRoute(pattern, handler),
689
+ // API endpoints
690
+ api: (pattern, handler) => {
691
+ this.addRoute(pattern, (context) => this.handleApiRequest(context.request, handler));
692
+ },
693
+ // Static file serving (basic)
694
+ static: (pattern) => {
695
+ this.addRoute(pattern, async () => {
696
+ return this.createErrorResponse(404, "Static file serving not implemented");
697
+ });
698
+ },
699
+ // Middleware support
700
+ use: (middleware) => {
701
+ if (typeof middleware !== "function") {
702
+ throw new Error("Middleware must be a function");
703
+ }
704
+ this.middleware.push(middleware);
705
+ return app;
706
+ },
707
+ // Request handler
708
+ fetch: (request) => this.handleRequest(request),
709
+ // Utilities
710
+ render: (component, props, options) => this.renderComponent(component, props, options),
711
+ getRuntime: () => this,
712
+ getStats: () => ({
713
+ renderCount: this.renderCount,
714
+ cacheSize: this.cache.size,
715
+ componentCount: this.componentRegistry.size,
716
+ routeCount: this.routeRegistry.size
717
+ })
718
+ };
719
+ return app;
720
+ }
721
+ // Static factory methods
722
+ static createApp(options = {}) {
723
+ const runtime = new _EdgeRuntime(options);
724
+ return runtime.createApp(options);
725
+ }
726
+ static async handleRequest(request, components = {}, routes = {}) {
727
+ const runtime = new _EdgeRuntime();
728
+ Object.entries(components).forEach(([name, component]) => {
729
+ runtime.registerComponent(name, component);
730
+ });
731
+ Object.entries(routes).forEach(([pattern, handler]) => {
732
+ runtime.addRoute(pattern, handler);
733
+ });
734
+ return await runtime.handleRequest(request);
735
+ }
736
+ };
737
+ }
738
+ });
739
+
740
+ // src/runtimes/static.js
741
+ var static_exports = {};
742
+ __export(static_exports, {
743
+ StaticRuntime: () => StaticRuntime
744
+ });
745
+ import { render as render3 } from "@coherent.js/core";
746
+ var StaticRuntime;
747
+ var init_static = __esm({
748
+ "src/runtimes/static.js"() {
749
+ "use strict";
750
+ StaticRuntime = class _StaticRuntime {
751
+ constructor(options = {}) {
752
+ this.options = {
753
+ outputDir: "dist",
754
+ baseUrl: "",
755
+ generateSitemap: true,
756
+ generateManifest: true,
757
+ minifyHtml: true,
758
+ inlineCSS: false,
759
+ ...options
760
+ };
761
+ this.componentRegistry = /* @__PURE__ */ new Map();
762
+ this.pageRegistry = /* @__PURE__ */ new Map();
763
+ this.staticAssets = /* @__PURE__ */ new Map();
764
+ this.generatedPages = /* @__PURE__ */ new Map();
765
+ this.buildStats = {
766
+ startTime: Date.now(),
767
+ pagesGenerated: 0,
768
+ assetsProcessed: 0,
769
+ totalSize: 0,
770
+ errors: []
771
+ };
772
+ }
773
+ // Component management
774
+ registerComponent(name, component, options = {}) {
775
+ this.componentRegistry.set(name, {
776
+ component,
777
+ options
778
+ });
779
+ return component;
780
+ }
781
+ getComponent(name) {
782
+ const registration = this.componentRegistry.get(name);
783
+ return registration ? registration.component : null;
784
+ }
785
+ // Page registration
786
+ addPage(route, component, options = {}) {
787
+ this.pageRegistry.set(route, {
788
+ component: typeof component === "string" ? this.getComponent(component) : component,
789
+ options: {
790
+ title: options.title || "Page",
791
+ description: options.description || "",
792
+ keywords: options.keywords || "",
793
+ generatePath: options.generatePath || this.routeToPath(route),
794
+ props: options.props || {},
795
+ ...options
796
+ }
797
+ });
798
+ }
799
+ routeToPath(route) {
800
+ if (route === "/") return "/index.html";
801
+ if (route.includes(":")) {
802
+ console.warn(`Dynamic route ${route} requires explicit generatePath`);
803
+ return null;
804
+ }
805
+ return route.endsWith("/") ? `${route}index.html` : `${route}.html`;
806
+ }
807
+ // Static asset management
808
+ addAsset(path, content, options = {}) {
809
+ this.staticAssets.set(path, {
810
+ content,
811
+ type: options.type || this.inferContentType(path),
812
+ minify: options.minify !== false,
813
+ ...options
814
+ });
815
+ }
816
+ inferContentType(path) {
817
+ const ext = path.split(".").pop().toLowerCase();
818
+ const contentTypes = {
819
+ "html": "text/html",
820
+ "css": "text/css",
821
+ "js": "application/javascript",
822
+ "json": "application/json",
823
+ "png": "image/png",
824
+ "jpg": "image/jpeg",
825
+ "jpeg": "image/jpeg",
826
+ "gif": "image/gif",
827
+ "svg": "image/svg+xml",
828
+ "ico": "image/x-icon"
829
+ };
830
+ return contentTypes[ext] || "text/plain";
831
+ }
832
+ // HTML template generation
833
+ generateHtmlDocument(content, options = {}) {
834
+ const {
835
+ title = "Coherent.js App",
836
+ description = "",
837
+ keywords = "",
838
+ lang = "en",
839
+ charset = "utf-8",
840
+ viewport = "width=device-width, initial-scale=1",
841
+ favicon = "/favicon.ico",
842
+ styles = [],
843
+ scripts = [],
844
+ meta = [],
845
+ bodyClass = "",
846
+ hydrate: hydrate2 = false,
847
+ componentName = null,
848
+ componentProps = {}
849
+ } = options;
850
+ const metaTags = [
851
+ `<meta charset="${charset}">`,
852
+ `<meta name="viewport" content="${viewport}">`,
853
+ description && `<meta name="description" content="${description}">`,
854
+ keywords && `<meta name="keywords" content="${keywords}">`,
855
+ ...meta.map((m) => typeof m === "string" ? m : `<meta ${Object.entries(m).map(([k, v]) => `${k}="${v}"`).join(" ")}>`)
856
+ ].filter(Boolean).join("\n ");
857
+ const styleTags = styles.map(
858
+ (style) => typeof style === "string" ? style.startsWith("<") ? style : `<link rel="stylesheet" href="${style}">` : `<style>${style.content}</style>`
859
+ ).join("\n ");
860
+ const scriptTags = [
861
+ ...scripts.map(
862
+ (script) => typeof script === "string" ? script.startsWith("<") ? script : `<script src="${script}"></script>` : `<script>${script.content}</script>`
863
+ ),
864
+ // Add hydration script if enabled
865
+ hydrate2 && this.generateHydrationScript(componentName, componentProps)
866
+ ].filter(Boolean).join("\n ");
867
+ return `<!DOCTYPE html>
868
+ <html lang="${lang}">
869
+ <head>
870
+ ${metaTags}
871
+ <title>${this.escapeHtml(title)}</title>
872
+ <link rel="icon" href="${favicon}">
873
+ ${styleTags}
874
+ </head>
875
+ <body${bodyClass ? ` class="${bodyClass}"` : ""}>
876
+ ${content}
877
+ ${scriptTags}
878
+ </body>
879
+ </html>`;
880
+ }
881
+ generateHydrationScript(componentName) {
882
+ if (!componentName) return "";
883
+ return `
884
+ <script type="module">
885
+ import { autoHydrate } from '/coherent-client.js';
886
+
887
+ // Auto-hydrate on page load
888
+ document.addEventListener('DOMContentLoaded', () => {
889
+ autoHydrate({
890
+ '${componentName}': window.components?.['${componentName}']
891
+ });
892
+ });
893
+ </script>`;
894
+ }
895
+ escapeHtml(text) {
896
+ if (typeof text !== "string") return text;
897
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
898
+ }
899
+ // Build process
900
+ async build() {
901
+ this.buildStats.startTime = Date.now();
902
+ console.log("\u{1F3D7}\uFE0F Starting static site generation...");
903
+ try {
904
+ await this.generatePages();
905
+ await this.processAssets();
906
+ if (this.options.generateSitemap) {
907
+ await this.generateSitemap();
908
+ }
909
+ if (this.options.generateManifest) {
910
+ await this.generateManifest();
911
+ }
912
+ const buildTime = Date.now() - this.buildStats.startTime;
913
+ console.log(`\u2705 Build completed in ${buildTime}ms`);
914
+ console.log(`\u{1F4C4} Generated ${this.buildStats.pagesGenerated} pages`);
915
+ console.log(`\u{1F4E6} Processed ${this.buildStats.assetsProcessed} assets`);
916
+ return this.getBuildResult();
917
+ } catch (error) {
918
+ this.buildStats.errors.push(error);
919
+ console.error("\u274C Build failed:", error);
920
+ throw error;
921
+ }
922
+ }
923
+ async generatePages() {
924
+ for (const [route, pageConfig] of this.pageRegistry) {
925
+ try {
926
+ await this.generatePage(route, pageConfig);
927
+ this.buildStats.pagesGenerated++;
928
+ } catch (error) {
929
+ console.error(`Failed to generate page ${route}:`, error);
930
+ this.buildStats.errors.push({ route, error });
931
+ }
932
+ }
933
+ }
934
+ async generatePage(route, pageConfig) {
935
+ const { component, options } = pageConfig;
936
+ if (!component) {
937
+ throw new Error(`No component found for route: ${route}`);
938
+ }
939
+ const vdom = component(options.props || {});
940
+ const content = render3(vdom);
941
+ const html = this.generateHtmlDocument(content, {
942
+ title: options.title,
943
+ description: options.description,
944
+ keywords: options.keywords,
945
+ styles: options.styles || [],
946
+ scripts: options.scripts || [],
947
+ meta: options.meta || [],
948
+ hydrate: options.hydrate,
949
+ componentName: options.componentName,
950
+ componentProps: options.props || {},
951
+ ...options.htmlOptions
952
+ });
953
+ const finalHtml = this.options.minifyHtml ? this.minifyHtml(html) : html;
954
+ const outputPath = options.generatePath || this.routeToPath(route);
955
+ if (outputPath) {
956
+ this.generatedPages.set(outputPath, {
957
+ html: finalHtml,
958
+ size: finalHtml.length,
959
+ route,
960
+ options
961
+ });
962
+ this.buildStats.totalSize += finalHtml.length;
963
+ }
964
+ }
965
+ minifyHtml(html) {
966
+ return html.replace(/\s+/g, " ").replace(/>\s+</g, "><").replace(/\s+>/g, ">").replace(/<\s+/g, "<").trim();
967
+ }
968
+ async processAssets() {
969
+ for (const [path, asset] of this.staticAssets) {
970
+ try {
971
+ let content = asset.content;
972
+ if (asset.minify) {
973
+ content = this.minifyAsset(content, asset.type);
974
+ }
975
+ this.generatedPages.set(path, {
976
+ content,
977
+ type: asset.type,
978
+ size: content.length
979
+ });
980
+ this.buildStats.assetsProcessed++;
981
+ this.buildStats.totalSize += content.length;
982
+ } catch (error) {
983
+ console.error(`Failed to process asset ${path}:`, error);
984
+ this.buildStats.errors.push({ path, error });
985
+ }
986
+ }
987
+ }
988
+ minifyAsset(content, type) {
989
+ switch (type) {
990
+ case "text/css":
991
+ return content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").replace(/;\s*}/g, "}").replace(/\s*{\s*/g, "{").replace(/;\s*/g, ";").trim();
992
+ case "application/javascript":
993
+ return content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "").replace(/\s+/g, " ").replace(/\s*([{}();,])\s*/g, "$1").trim();
994
+ default:
995
+ return content;
996
+ }
997
+ }
998
+ async generateSitemap() {
999
+ const pages = Array.from(this.generatedPages.keys()).filter((path) => path.endsWith(".html"));
1000
+ const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
1001
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
1002
+ ${pages.map((path) => ` <url>
1003
+ <loc>${this.options.baseUrl}${path.replace("/index.html", "/")}</loc>
1004
+ <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>
1005
+ </url>`).join("\n")}
1006
+ </urlset>`;
1007
+ this.generatedPages.set("/sitemap.xml", {
1008
+ content: sitemap,
1009
+ type: "application/xml",
1010
+ size: sitemap.length
1011
+ });
1012
+ }
1013
+ async generateManifest() {
1014
+ const manifest = {
1015
+ name: this.options.name || "Coherent.js App",
1016
+ short_name: this.options.shortName || "App",
1017
+ description: this.options.description || "",
1018
+ start_url: "/",
1019
+ display: "standalone",
1020
+ theme_color: this.options.themeColor || "#000000",
1021
+ background_color: this.options.backgroundColor || "#ffffff",
1022
+ icons: this.options.icons || []
1023
+ };
1024
+ const manifestJson = JSON.stringify(manifest, null, 2);
1025
+ this.generatedPages.set("/manifest.json", {
1026
+ content: manifestJson,
1027
+ type: "application/json",
1028
+ size: manifestJson.length
1029
+ });
1030
+ }
1031
+ getBuildResult() {
1032
+ return {
1033
+ pages: this.generatedPages,
1034
+ stats: {
1035
+ ...this.buildStats,
1036
+ buildTime: Date.now() - this.buildStats.startTime
1037
+ },
1038
+ success: this.buildStats.errors.length === 0
1039
+ };
1040
+ }
1041
+ // Create static app factory
1042
+ createApp() {
1043
+ return {
1044
+ // Component registration
1045
+ component: (name, component, opts) => this.registerComponent(name, component, opts),
1046
+ // Page registration
1047
+ page: (route, component, opts) => this.addPage(route, component, opts),
1048
+ // Asset management
1049
+ asset: (path, content, opts) => this.addAsset(path, content, opts),
1050
+ // Build process
1051
+ build: () => this.build(),
1052
+ // Utilities
1053
+ getRuntime: () => this,
1054
+ getStats: () => this.buildStats,
1055
+ getPages: () => Array.from(this.pageRegistry.keys()),
1056
+ getAssets: () => Array.from(this.staticAssets.keys())
1057
+ };
1058
+ }
1059
+ // Static factory methods
1060
+ static createApp(options = {}) {
1061
+ const runtime = new _StaticRuntime(options);
1062
+ return runtime.createApp(options);
1063
+ }
1064
+ static async buildSite(pages = {}, components = {}, options = {}) {
1065
+ const runtime = new _StaticRuntime(options);
1066
+ Object.entries(components).forEach(([name, component]) => {
1067
+ runtime.registerComponent(name, component);
1068
+ });
1069
+ Object.entries(pages).forEach(([route, config]) => {
1070
+ runtime.addPage(route, config.component, config.options);
1071
+ });
1072
+ return await runtime.build();
1073
+ }
1074
+ };
1075
+ }
1076
+ });
1077
+
1078
+ // src/runtimes/node.js
1079
+ var node_exports = {};
1080
+ __export(node_exports, {
1081
+ NodeRuntime: () => NodeRuntime,
1082
+ createNodeRuntime: () => createNodeRuntime,
1083
+ default: () => node_default
1084
+ });
1085
+ import { render as render4 } from "@coherent.js/core";
1086
+ import { createServer } from "http";
1087
+ function createNodeRuntime(options = {}) {
1088
+ return new NodeRuntime(options);
1089
+ }
1090
+ var NodeRuntime, node_default;
1091
+ var init_node = __esm({
1092
+ "src/runtimes/node.js"() {
1093
+ "use strict";
1094
+ NodeRuntime = class {
1095
+ constructor(options = {}) {
1096
+ this.options = {
1097
+ port: 3e3,
1098
+ host: "localhost",
1099
+ caching: true,
1100
+ framework: null,
1101
+ // 'express', 'fastify', 'koa', or null for standalone
1102
+ headers: {
1103
+ "Content-Type": "text/html; charset=utf-8",
1104
+ "Cache-Control": "public, max-age=3600",
1105
+ ...options.headers
1106
+ },
1107
+ ...options
1108
+ };
1109
+ this.componentRegistry = /* @__PURE__ */ new Map();
1110
+ this.routeRegistry = /* @__PURE__ */ new Map();
1111
+ this.middleware = [];
1112
+ this.cache = /* @__PURE__ */ new Map();
1113
+ this.renderCount = 0;
1114
+ this.server = null;
1115
+ if (this.options.caching) {
1116
+ this.initializeCacheCleanup();
1117
+ }
1118
+ }
1119
+ initializeCacheCleanup() {
1120
+ setInterval(() => {
1121
+ if (this.cache.size > 1e3) {
1122
+ const entries = Array.from(this.cache.entries());
1123
+ const toDelete = entries.slice(0, entries.length - 500);
1124
+ toDelete.forEach(([key]) => this.cache.delete(key));
1125
+ }
1126
+ }, 3e5);
1127
+ }
1128
+ // Component management
1129
+ registerComponent(name, component) {
1130
+ this.componentRegistry.set(name, component);
1131
+ return component;
1132
+ }
1133
+ getComponent(name) {
1134
+ return this.componentRegistry.get(name);
1135
+ }
1136
+ // Route management
1137
+ addRoute(pattern, handler) {
1138
+ this.routeRegistry.set(pattern, handler);
1139
+ }
1140
+ matchRoute(pathname) {
1141
+ for (const [pattern, handler] of this.routeRegistry.entries()) {
1142
+ const match = this.matchPattern(pattern, pathname);
1143
+ if (match) {
1144
+ return { handler, params: match.params };
1145
+ }
1146
+ }
1147
+ return null;
1148
+ }
1149
+ matchPattern(pattern, pathname) {
1150
+ const patternParts = pattern.split("/").filter(Boolean);
1151
+ const pathParts = pathname.split("/").filter(Boolean);
1152
+ if (patternParts.length !== pathParts.length) {
1153
+ return null;
1154
+ }
1155
+ const params = {};
1156
+ for (let i = 0; i < patternParts.length; i++) {
1157
+ const patternPart = patternParts[i];
1158
+ const pathPart = pathParts[i];
1159
+ if (patternPart.startsWith(":")) {
1160
+ params[patternPart.slice(1)] = pathPart;
1161
+ } else if (patternPart !== pathPart) {
1162
+ return null;
1163
+ }
1164
+ }
1165
+ return { params };
1166
+ }
1167
+ // Rendering
1168
+ async renderComponent(component, props = {}, options = {}) {
1169
+ try {
1170
+ const resolvedComponent = typeof component === "string" ? this.getComponent(component) : component;
1171
+ if (!resolvedComponent) {
1172
+ throw new Error(`Component not found: ${component}`);
1173
+ }
1174
+ const cacheKey = this.generateCacheKey(resolvedComponent, props);
1175
+ if (this.options.caching && this.cache.has(cacheKey)) {
1176
+ const cached = this.cache.get(cacheKey);
1177
+ if (Date.now() - cached.timestamp < (options.cacheMaxAge || 3e5)) {
1178
+ return cached.html;
1179
+ }
1180
+ this.cache.delete(cacheKey);
1181
+ }
1182
+ const vdom = resolvedComponent(props);
1183
+ const html = render4(vdom);
1184
+ if (this.options.caching && options.cacheable !== false) {
1185
+ this.cache.set(cacheKey, {
1186
+ html,
1187
+ timestamp: Date.now()
1188
+ });
1189
+ }
1190
+ this.renderCount++;
1191
+ return html;
1192
+ } catch (error) {
1193
+ console.error("Node render error:", error);
1194
+ throw error;
1195
+ }
1196
+ }
1197
+ generateCacheKey(component, props) {
1198
+ const componentName = component.name || "anonymous";
1199
+ const propsHash = this.hashObject(props);
1200
+ return `${componentName}-${propsHash}`;
1201
+ }
1202
+ hashObject(obj) {
1203
+ const str = JSON.stringify(obj, Object.keys(obj).sort());
1204
+ let hash = 0;
1205
+ for (let i = 0; i < str.length; i++) {
1206
+ const char = str.charCodeAt(i);
1207
+ hash = (hash << 5) - hash + char;
1208
+ hash = hash & hash;
1209
+ }
1210
+ return hash.toString(36);
1211
+ }
1212
+ // HTTP Request handling (for standalone mode)
1213
+ async handleRequest(req, res) {
1214
+ try {
1215
+ const url = new URL(req.url, `http://${req.headers.host}`);
1216
+ const pathname = url.pathname;
1217
+ const context = {
1218
+ req,
1219
+ res,
1220
+ url,
1221
+ pathname,
1222
+ params: {},
1223
+ query: Object.fromEntries(url.searchParams),
1224
+ method: req.method,
1225
+ headers: req.headers,
1226
+ runtime: this,
1227
+ state: {}
1228
+ };
1229
+ let middlewareIndex = 0;
1230
+ const next = async () => {
1231
+ if (middlewareIndex < this.middleware.length) {
1232
+ const middleware = this.middleware[middlewareIndex++];
1233
+ return await middleware(context, next);
1234
+ }
1235
+ };
1236
+ if (this.middleware.length > 0) {
1237
+ await next();
1238
+ }
1239
+ if (res.headersSent) {
1240
+ return;
1241
+ }
1242
+ const match = this.matchRoute(pathname);
1243
+ if (!match) {
1244
+ res.writeHead(404, { "Content-Type": "text/html" });
1245
+ res.end("<h1>404 Not Found</h1>");
1246
+ return;
1247
+ }
1248
+ context.params = match.params;
1249
+ const result = await match.handler(context);
1250
+ if (res.headersSent) {
1251
+ return;
1252
+ }
1253
+ if (typeof result === "string") {
1254
+ res.writeHead(200, this.options.headers);
1255
+ res.end(result);
1256
+ return;
1257
+ }
1258
+ if (result && typeof result === "object") {
1259
+ if (result.component) {
1260
+ const html = await this.renderComponent(
1261
+ result.component,
1262
+ result.props || {},
1263
+ result.options || {}
1264
+ );
1265
+ res.writeHead(result.status || 200, {
1266
+ ...this.options.headers,
1267
+ ...result.headers
1268
+ });
1269
+ res.end(html);
1270
+ return;
1271
+ }
1272
+ if (result.json !== void 0) {
1273
+ res.writeHead(result.status || 200, {
1274
+ "Content-Type": "application/json",
1275
+ ...result.headers
1276
+ });
1277
+ res.end(JSON.stringify(result.json));
1278
+ return;
1279
+ }
1280
+ if (result.redirect) {
1281
+ res.writeHead(result.status || 302, {
1282
+ "Location": result.redirect
1283
+ });
1284
+ res.end();
1285
+ return;
1286
+ }
1287
+ res.writeHead(200, { "Content-Type": "application/json" });
1288
+ res.end(JSON.stringify(result));
1289
+ return;
1290
+ }
1291
+ res.writeHead(200, this.options.headers);
1292
+ res.end(String(result));
1293
+ } catch (error) {
1294
+ console.error("Request handling error:", error);
1295
+ if (!res.headersSent) {
1296
+ res.writeHead(500, { "Content-Type": "application/json" });
1297
+ res.end(JSON.stringify({ error: error.message }));
1298
+ }
1299
+ }
1300
+ }
1301
+ // Create app factory
1302
+ createApp() {
1303
+ const app = {
1304
+ // Component registration
1305
+ component: (name, component) => this.registerComponent(name, component),
1306
+ // Routing
1307
+ get: (pattern, handler) => this.addRoute(pattern, handler),
1308
+ post: (pattern, handler) => this.addRoute(pattern, handler),
1309
+ put: (pattern, handler) => this.addRoute(pattern, handler),
1310
+ delete: (pattern, handler) => this.addRoute(pattern, handler),
1311
+ route: (pattern, handler) => this.addRoute(pattern, handler),
1312
+ // Middleware support
1313
+ use: (middleware) => {
1314
+ if (typeof middleware !== "function") {
1315
+ throw new Error("Middleware must be a function");
1316
+ }
1317
+ this.middleware.push(middleware);
1318
+ return app;
1319
+ },
1320
+ // Server control
1321
+ listen: (port, callback) => {
1322
+ const serverPort = port || this.options.port;
1323
+ this.server = createServer((req, res) => this.handleRequest(req, res));
1324
+ this.server.listen(serverPort, this.options.host, () => {
1325
+ console.log(`Coherent.js Node runtime listening on http://${this.options.host}:${serverPort}`);
1326
+ if (callback) callback();
1327
+ });
1328
+ return this.server;
1329
+ },
1330
+ close: (callback) => {
1331
+ if (this.server) {
1332
+ this.server.close(callback);
1333
+ }
1334
+ },
1335
+ // Utilities
1336
+ render: (component, props, options) => this.renderComponent(component, props, options),
1337
+ getRuntime: () => this,
1338
+ getStats: () => ({
1339
+ renderCount: this.renderCount,
1340
+ cacheSize: this.cache.size,
1341
+ componentCount: this.componentRegistry.size,
1342
+ routeCount: this.routeRegistry.size,
1343
+ middlewareCount: this.middleware.length
1344
+ })
1345
+ };
1346
+ return app;
1347
+ }
1348
+ // Framework integration helpers
1349
+ expressMiddleware() {
1350
+ return async (req, res, next) => {
1351
+ req.coherent = {
1352
+ render: async (component, props, options) => {
1353
+ const html = await this.renderComponent(component, props, options);
1354
+ res.send(html);
1355
+ },
1356
+ runtime: this
1357
+ };
1358
+ next();
1359
+ };
1360
+ }
1361
+ fastifyPlugin() {
1362
+ return async (fastify) => {
1363
+ fastify.decorate("coherent", {
1364
+ render: async (component, props, renderOptions) => {
1365
+ return await this.renderComponent(component, props, renderOptions);
1366
+ },
1367
+ runtime: this
1368
+ });
1369
+ };
1370
+ }
1371
+ koaMiddleware() {
1372
+ return async (ctx, next) => {
1373
+ ctx.coherent = {
1374
+ render: async (component, props, options) => {
1375
+ const html = await this.renderComponent(component, props, options);
1376
+ ctx.type = "html";
1377
+ ctx.body = html;
1378
+ },
1379
+ runtime: this
1380
+ };
1381
+ await next();
1382
+ };
1383
+ }
1384
+ };
1385
+ node_default = NodeRuntime;
1386
+ }
1387
+ });
1388
+
1389
+ // src/index.js
1390
+ init_browser();
1391
+ init_edge();
1392
+ init_static();
1393
+ export * from "@coherent.js/core";
1394
+ export * from "@coherent.js/client";
1395
+ export * from "@coherent.js/web-components";
1396
+
1397
+ // src/runtimes/desktop.js
1398
+ init_browser();
1399
+ var DesktopRuntime = class _DesktopRuntime extends BrowserRuntime {
1400
+ constructor(options = {}) {
1401
+ super({
1402
+ enableFileSystem: true,
1403
+ enableNativeAPIs: true,
1404
+ ...options
1405
+ });
1406
+ this.desktopAPI = null;
1407
+ this.isElectron = typeof window !== "undefined" && !!window.require;
1408
+ this.isTauri = typeof window !== "undefined" && !!window.__TAURI__;
1409
+ }
1410
+ async initialize() {
1411
+ await super.initialize();
1412
+ if (this.isElectron) {
1413
+ this.initializeElectron();
1414
+ } else if (this.isTauri) {
1415
+ this.initializeTauri();
1416
+ }
1417
+ }
1418
+ initializeElectron() {
1419
+ try {
1420
+ this.desktopAPI = {
1421
+ platform: "electron",
1422
+ fs: window.require ? window.require("fs") : null,
1423
+ path: window.require ? window.require("path") : null,
1424
+ ipcRenderer: window.require ? window.require("electron").ipcRenderer : null
1425
+ };
1426
+ } catch (error) {
1427
+ console.warn("Failed to initialize Electron APIs:", error);
1428
+ }
1429
+ }
1430
+ async initializeTauri() {
1431
+ try {
1432
+ if (window.__TAURI__) {
1433
+ this.desktopAPI = {
1434
+ platform: "tauri",
1435
+ fs: window.__TAURI__.fs,
1436
+ path: window.__TAURI__.path,
1437
+ invoke: window.__TAURI__.invoke
1438
+ };
1439
+ }
1440
+ } catch (error) {
1441
+ console.warn("Failed to initialize Tauri APIs:", error);
1442
+ }
1443
+ }
1444
+ // Desktop-specific methods
1445
+ async readFile(path) {
1446
+ if (this.desktopAPI?.fs) {
1447
+ return await this.desktopAPI.fs.readTextFile(path);
1448
+ }
1449
+ throw new Error("File system access not available");
1450
+ }
1451
+ async writeFile(path, content) {
1452
+ if (this.desktopAPI?.fs) {
1453
+ return await this.desktopAPI.fs.writeTextFile(path, content);
1454
+ }
1455
+ throw new Error("File system access not available");
1456
+ }
1457
+ async showDialog(options) {
1458
+ if (this.isElectron && this.desktopAPI?.ipcRenderer) {
1459
+ return await this.desktopAPI.ipcRenderer.invoke("show-dialog", options);
1460
+ } else if (this.isTauri && this.desktopAPI?.invoke) {
1461
+ return await this.desktopAPI.invoke("show_dialog", options);
1462
+ }
1463
+ console.warn("Desktop dialog not available, rejecting by default");
1464
+ return Promise.resolve(false);
1465
+ }
1466
+ static createApp(options = {}) {
1467
+ const runtime = new _DesktopRuntime(options);
1468
+ return runtime.createApp(options);
1469
+ }
1470
+ };
1471
+
1472
+ // src/loaders/universal-loader.js
1473
+ var UniversalLoader = class _UniversalLoader {
1474
+ constructor(options = {}) {
1475
+ this.options = {
1476
+ baseUrl: "",
1477
+ moduleMap: {},
1478
+ fallbackUrls: [],
1479
+ cache: true,
1480
+ ...options
1481
+ };
1482
+ this.moduleCache = /* @__PURE__ */ new Map();
1483
+ this.loadingPromises = /* @__PURE__ */ new Map();
1484
+ this.environment = this.detectEnvironment();
1485
+ }
1486
+ detectEnvironment() {
1487
+ if (typeof Deno !== "undefined") return "deno";
1488
+ if (typeof Bun !== "undefined") return "bun";
1489
+ if (typeof window !== "undefined") return "browser";
1490
+ if (typeof global !== "undefined" && typeof __require !== "undefined") return "node";
1491
+ if (typeof WorkerGlobalScope !== "undefined") return "worker";
1492
+ return "unknown";
1493
+ }
1494
+ // Universal module loading
1495
+ async load(modulePath, options = {}) {
1496
+ const resolvedPath = this.resolvePath(modulePath, options);
1497
+ const cacheKey = resolvedPath + JSON.stringify(options);
1498
+ if (this.options.cache && this.moduleCache.has(cacheKey)) {
1499
+ return this.moduleCache.get(cacheKey);
1500
+ }
1501
+ if (this.loadingPromises.has(cacheKey)) {
1502
+ return this.loadingPromises.get(cacheKey);
1503
+ }
1504
+ const loadingPromise = this.loadModule(resolvedPath, options);
1505
+ this.loadingPromises.set(cacheKey, loadingPromise);
1506
+ try {
1507
+ const module = await loadingPromise;
1508
+ if (this.options.cache) {
1509
+ this.moduleCache.set(cacheKey, module);
1510
+ }
1511
+ return module;
1512
+ } finally {
1513
+ this.loadingPromises.delete(cacheKey);
1514
+ }
1515
+ }
1516
+ async loadModule(modulePath, options = {}) {
1517
+ switch (this.environment) {
1518
+ case "browser":
1519
+ return await this.loadBrowserModule(modulePath, options);
1520
+ case "node":
1521
+ return await this.loadNodeModule(modulePath, options);
1522
+ case "deno":
1523
+ return await this.loadDenoModule(modulePath, options);
1524
+ case "bun":
1525
+ return await this.loadBunModule(modulePath, options);
1526
+ case "worker":
1527
+ return await this.loadWorkerModule(modulePath, options);
1528
+ default:
1529
+ return await this.loadGenericModule(modulePath, options);
1530
+ }
1531
+ }
1532
+ async loadBrowserModule(modulePath, options = {}) {
1533
+ if (modulePath.startsWith("http") || modulePath.startsWith("/")) {
1534
+ try {
1535
+ return await import(modulePath);
1536
+ } catch {
1537
+ return await this.loadScript(modulePath, options);
1538
+ }
1539
+ } else {
1540
+ const cdnUrl = this.toCdnUrl(modulePath);
1541
+ return await import(cdnUrl);
1542
+ }
1543
+ }
1544
+ async loadNodeModule(modulePath) {
1545
+ if (typeof __require !== "undefined") {
1546
+ try {
1547
+ return __require(modulePath);
1548
+ } catch {
1549
+ return await import(modulePath);
1550
+ }
1551
+ } else {
1552
+ return await import(modulePath);
1553
+ }
1554
+ }
1555
+ async loadDenoModule(modulePath) {
1556
+ if (modulePath.startsWith("npm:")) {
1557
+ return await import(modulePath);
1558
+ } else if (modulePath.startsWith("http")) {
1559
+ return await import(modulePath);
1560
+ } else {
1561
+ return await import(`npm:${modulePath}`);
1562
+ }
1563
+ }
1564
+ async loadBunModule(modulePath) {
1565
+ try {
1566
+ return await import(modulePath);
1567
+ } catch (error) {
1568
+ if (typeof __require !== "undefined") {
1569
+ return __require(modulePath);
1570
+ }
1571
+ throw error;
1572
+ }
1573
+ }
1574
+ async loadWorkerModule(modulePath) {
1575
+ return await import(modulePath);
1576
+ }
1577
+ async loadGenericModule(modulePath) {
1578
+ return await import(modulePath);
1579
+ }
1580
+ async loadScript(src, options = {}) {
1581
+ return new Promise((resolve, reject) => {
1582
+ const script = document.createElement("script");
1583
+ script.type = "module";
1584
+ script.src = src;
1585
+ script.onload = () => {
1586
+ const moduleName = options.globalName || this.getModuleNameFromPath(src);
1587
+ const module = window[moduleName] || {};
1588
+ resolve(module);
1589
+ };
1590
+ script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
1591
+ document.head.appendChild(script);
1592
+ });
1593
+ }
1594
+ resolvePath(modulePath, options = {}) {
1595
+ if (modulePath.startsWith("http://") || modulePath.startsWith("https://")) {
1596
+ return modulePath;
1597
+ }
1598
+ if (modulePath.startsWith("./") || modulePath.startsWith("../")) {
1599
+ return this.resolveRelativePath(modulePath, options.baseUrl || this.options.baseUrl);
1600
+ }
1601
+ if (this.options.moduleMap[modulePath]) {
1602
+ return this.options.moduleMap[modulePath];
1603
+ }
1604
+ return this.options.baseUrl + modulePath;
1605
+ }
1606
+ resolveRelativePath(relativePath, baseUrl) {
1607
+ if (!baseUrl) return relativePath;
1608
+ const base = new URL(baseUrl, location?.href || "file:///");
1609
+ const resolved = new URL(relativePath, base);
1610
+ return resolved.href;
1611
+ }
1612
+ toCdnUrl(packageName, version = "latest") {
1613
+ const _cleanName = packageName.replace(/^@/, "").replace("/", "-");
1614
+ return `https://unpkg.com/${packageName}@${version}/dist/index.js`;
1615
+ }
1616
+ getModuleNameFromPath(path) {
1617
+ const filename = path.split("/").pop().split(".")[0];
1618
+ return filename.replace(/[-_]/g, "");
1619
+ }
1620
+ // Batch loading
1621
+ async loadAll(modulePaths, options = {}) {
1622
+ const loadPromises = modulePaths.map(
1623
+ (path) => this.load(path, options).catch((error) => ({ error, path }))
1624
+ );
1625
+ return await Promise.all(loadPromises);
1626
+ }
1627
+ // Preloading
1628
+ async preload(modulePaths, options = {}) {
1629
+ const preloadPromises = modulePaths.map(async (path) => {
1630
+ try {
1631
+ await this.load(path, { ...options, preload: true });
1632
+ return { success: true, path };
1633
+ } catch (error) {
1634
+ return { success: false, path, error };
1635
+ }
1636
+ });
1637
+ return await Promise.all(preloadPromises);
1638
+ }
1639
+ // Cache management
1640
+ clearCache() {
1641
+ this.moduleCache.clear();
1642
+ }
1643
+ getCacheStats() {
1644
+ return {
1645
+ size: this.moduleCache.size,
1646
+ modules: Array.from(this.moduleCache.keys())
1647
+ };
1648
+ }
1649
+ // Environment detection helpers
1650
+ static isSupported() {
1651
+ return (() => {
1652
+ try {
1653
+ return typeof Function('return import("")') === "function";
1654
+ } catch {
1655
+ return false;
1656
+ }
1657
+ })() || typeof __require !== "undefined";
1658
+ }
1659
+ static getCapabilities() {
1660
+ return {
1661
+ dynamicImport: (() => {
1662
+ try {
1663
+ return typeof Function('return import("")') === "function";
1664
+ } catch {
1665
+ return false;
1666
+ }
1667
+ })(),
1668
+ require: typeof __require !== "undefined",
1669
+ fetch: typeof fetch !== "undefined",
1670
+ worker: typeof Worker !== "undefined",
1671
+ environment: new _UniversalLoader().environment
1672
+ };
1673
+ }
1674
+ };
1675
+ var universalLoader = new UniversalLoader();
1676
+
1677
+ // src/loaders/component-loader.js
1678
+ var ComponentLoader = class {
1679
+ constructor(options = {}) {
1680
+ this.options = {
1681
+ componentRegistry: /* @__PURE__ */ new Map(),
1682
+ lazyLoad: true,
1683
+ preloadComponents: [],
1684
+ componentPaths: {},
1685
+ ...options
1686
+ };
1687
+ this.loader = universalLoader;
1688
+ this.loadingQueue = /* @__PURE__ */ new Map();
1689
+ this.dependencyGraph = /* @__PURE__ */ new Map();
1690
+ this.loadedComponents = /* @__PURE__ */ new Set();
1691
+ }
1692
+ // Register a component with its metadata
1693
+ registerComponent(name, componentOrPath, options = {}) {
1694
+ const registration = {
1695
+ name,
1696
+ path: typeof componentOrPath === "string" ? componentOrPath : null,
1697
+ component: typeof componentOrPath === "function" ? componentOrPath : null,
1698
+ loaded: typeof componentOrPath === "function",
1699
+ dependencies: options.dependencies || [],
1700
+ lazy: options.lazy !== false,
1701
+ preload: options.preload || false,
1702
+ metadata: options.metadata || {},
1703
+ ...options
1704
+ };
1705
+ this.options.componentRegistry.set(name, registration);
1706
+ if (registration.dependencies.length > 0) {
1707
+ this.dependencyGraph.set(name, registration.dependencies);
1708
+ }
1709
+ if (!registration.lazy && registration.path && !registration.loaded) {
1710
+ this.loadComponent(name);
1711
+ }
1712
+ return registration;
1713
+ }
1714
+ // Load a component by name
1715
+ async loadComponent(name, options = {}) {
1716
+ const registration = this.options.componentRegistry.get(name);
1717
+ if (!registration) {
1718
+ throw new Error(`Component '${name}' not found in registry`);
1719
+ }
1720
+ if (registration.loaded && registration.component) {
1721
+ return registration.component;
1722
+ }
1723
+ if (this.loadingQueue.has(name)) {
1724
+ return this.loadingQueue.get(name);
1725
+ }
1726
+ const loadingPromise = this.doLoadComponent(registration, options);
1727
+ this.loadingQueue.set(name, loadingPromise);
1728
+ try {
1729
+ const component = await loadingPromise;
1730
+ registration.component = component;
1731
+ registration.loaded = true;
1732
+ this.loadedComponents.add(name);
1733
+ return component;
1734
+ } finally {
1735
+ this.loadingQueue.delete(name);
1736
+ }
1737
+ }
1738
+ async doLoadComponent(registration, options = {}) {
1739
+ const { name, path, dependencies } = registration;
1740
+ try {
1741
+ if (dependencies.length > 0) {
1742
+ await this.loadDependencies(dependencies, options);
1743
+ }
1744
+ let component;
1745
+ if (path) {
1746
+ const module = await this.loader.load(path, options);
1747
+ component = this.extractComponent(module, name);
1748
+ } else if (registration.component) {
1749
+ component = registration.component;
1750
+ } else {
1751
+ throw new Error(`No component or path specified for '${name}'`);
1752
+ }
1753
+ return this.processComponent(component, registration, options);
1754
+ } catch (error) {
1755
+ console.error(`Failed to load component '${name}':`, error);
1756
+ throw error;
1757
+ }
1758
+ }
1759
+ extractComponent(module, componentName) {
1760
+ if (module.default && typeof module.default === "function") {
1761
+ return module.default;
1762
+ }
1763
+ if (module[componentName] && typeof module[componentName] === "function") {
1764
+ return module[componentName];
1765
+ }
1766
+ for (const [key, value] of Object.entries(module)) {
1767
+ if (typeof value === "function" && key !== "default") {
1768
+ return value;
1769
+ }
1770
+ }
1771
+ throw new Error(`No valid component function found in module for '${componentName}'`);
1772
+ }
1773
+ processComponent(component, registration, options = {}) {
1774
+ if (registration.metadata) {
1775
+ Object.assign(component, {
1776
+ $meta: registration.metadata,
1777
+ $name: registration.name
1778
+ });
1779
+ }
1780
+ if (options.wrapper) {
1781
+ return options.wrapper(component, registration);
1782
+ }
1783
+ return component;
1784
+ }
1785
+ async loadDependencies(dependencies, options = {}) {
1786
+ const dependencyPromises = dependencies.map((depName) => {
1787
+ return this.loadComponent(depName, options);
1788
+ });
1789
+ await Promise.all(dependencyPromises);
1790
+ }
1791
+ // Batch component loading
1792
+ async loadComponents(componentNames, options = {}) {
1793
+ const loadPromises = componentNames.map(
1794
+ (name) => this.loadComponent(name, options).catch((error) => ({ error, name }))
1795
+ );
1796
+ const results = await Promise.all(loadPromises);
1797
+ const loaded = {};
1798
+ const errors = [];
1799
+ results.forEach((result, index) => {
1800
+ const name = componentNames[index];
1801
+ if (result && result.error) {
1802
+ errors.push({ name, error: result.error });
1803
+ } else {
1804
+ loaded[name] = result;
1805
+ }
1806
+ });
1807
+ return { loaded, errors };
1808
+ }
1809
+ // Preload components
1810
+ async preloadComponents(componentNames = null) {
1811
+ const toPreload = componentNames || this.getPreloadableComponents();
1812
+ const preloadResults = await Promise.allSettled(
1813
+ toPreload.map((name) => this.loadComponent(name, { preload: true }))
1814
+ );
1815
+ const results = {
1816
+ successful: [],
1817
+ failed: []
1818
+ };
1819
+ preloadResults.forEach((result, index) => {
1820
+ const name = toPreload[index];
1821
+ if (result.status === "fulfilled") {
1822
+ results.successful.push(name);
1823
+ } else {
1824
+ results.failed.push({ name, error: result.reason });
1825
+ }
1826
+ });
1827
+ return results;
1828
+ }
1829
+ getPreloadableComponents() {
1830
+ return Array.from(this.options.componentRegistry.values()).filter((reg) => reg.preload && !reg.loaded).map((reg) => reg.name);
1831
+ }
1832
+ // Component discovery
1833
+ async discoverComponents(basePath, options = {}) {
1834
+ const discovered = [];
1835
+ try {
1836
+ if (typeof fetch !== "undefined") {
1837
+ discovered.push(...await this.discoverFromManifest(basePath, options));
1838
+ } else if (typeof __require !== "undefined") {
1839
+ discovered.push(...await this.discoverFromFileSystem(basePath, options));
1840
+ }
1841
+ } catch (error) {
1842
+ console.warn("Component discovery failed:", error);
1843
+ }
1844
+ return discovered;
1845
+ }
1846
+ async discoverFromManifest(basePath, _options = {}) {
1847
+ try {
1848
+ const manifestUrl = `${basePath}/components.json`;
1849
+ const response = await fetch(manifestUrl);
1850
+ const manifest = await response.json();
1851
+ return manifest.components || [];
1852
+ } catch {
1853
+ return [];
1854
+ }
1855
+ }
1856
+ async discoverFromFileSystem(basePath, _options = {}) {
1857
+ return [];
1858
+ }
1859
+ // Auto-registration from patterns
1860
+ registerComponentPattern(pattern, options = {}) {
1861
+ this.componentPatterns = this.componentPatterns || [];
1862
+ this.componentPatterns.push({ pattern, options });
1863
+ }
1864
+ // Dependency analysis
1865
+ analyzeDependencies() {
1866
+ const analysis = {
1867
+ circular: [],
1868
+ missing: [],
1869
+ unused: [],
1870
+ depth: /* @__PURE__ */ new Map()
1871
+ };
1872
+ analysis.circular = this.findCircularDependencies();
1873
+ analysis.missing = this.findMissingDependencies();
1874
+ analysis.unused = this.findUnusedComponents();
1875
+ analysis.depth = this.calculateDependencyDepths();
1876
+ return analysis;
1877
+ }
1878
+ findCircularDependencies() {
1879
+ const circular = [];
1880
+ const visited = /* @__PURE__ */ new Set();
1881
+ const recursionStack = /* @__PURE__ */ new Set();
1882
+ const visit = (componentName, path = []) => {
1883
+ if (recursionStack.has(componentName)) {
1884
+ circular.push([...path, componentName]);
1885
+ return;
1886
+ }
1887
+ if (visited.has(componentName)) return;
1888
+ visited.add(componentName);
1889
+ recursionStack.add(componentName);
1890
+ const dependencies = this.dependencyGraph.get(componentName) || [];
1891
+ dependencies.forEach((dep) => {
1892
+ visit(dep, [...path, componentName]);
1893
+ });
1894
+ recursionStack.delete(componentName);
1895
+ };
1896
+ Array.from(this.dependencyGraph.keys()).forEach(visit);
1897
+ return circular;
1898
+ }
1899
+ findMissingDependencies() {
1900
+ const missing = [];
1901
+ for (const [component, dependencies] of this.dependencyGraph) {
1902
+ for (const dep of dependencies) {
1903
+ if (!this.options.componentRegistry.has(dep)) {
1904
+ missing.push({ component, dependency: dep });
1905
+ }
1906
+ }
1907
+ }
1908
+ return missing;
1909
+ }
1910
+ findUnusedComponents() {
1911
+ const used = /* @__PURE__ */ new Set();
1912
+ for (const dependencies of this.dependencyGraph.values()) {
1913
+ dependencies.forEach((dep) => used.add(dep));
1914
+ }
1915
+ const unused = [];
1916
+ for (const name of this.options.componentRegistry.keys()) {
1917
+ if (!used.has(name)) {
1918
+ unused.push(name);
1919
+ }
1920
+ }
1921
+ return unused;
1922
+ }
1923
+ calculateDependencyDepths() {
1924
+ const depths = /* @__PURE__ */ new Map();
1925
+ const calculateDepth = (componentName, visited = /* @__PURE__ */ new Set()) => {
1926
+ if (depths.has(componentName)) {
1927
+ return depths.get(componentName);
1928
+ }
1929
+ if (visited.has(componentName)) {
1930
+ return Infinity;
1931
+ }
1932
+ visited.add(componentName);
1933
+ const dependencies = this.dependencyGraph.get(componentName) || [];
1934
+ const maxDepth = dependencies.length === 0 ? 0 : Math.max(...dependencies.map((dep) => calculateDepth(dep, new Set(visited)))) + 1;
1935
+ depths.set(componentName, maxDepth);
1936
+ return maxDepth;
1937
+ };
1938
+ for (const componentName of this.options.componentRegistry.keys()) {
1939
+ calculateDepth(componentName);
1940
+ }
1941
+ return depths;
1942
+ }
1943
+ // Utilities
1944
+ getRegisteredComponents() {
1945
+ return Array.from(this.options.componentRegistry.keys());
1946
+ }
1947
+ getLoadedComponents() {
1948
+ return Array.from(this.loadedComponents);
1949
+ }
1950
+ getComponentInfo(name) {
1951
+ return this.options.componentRegistry.get(name);
1952
+ }
1953
+ isComponentLoaded(name) {
1954
+ return this.loadedComponents.has(name);
1955
+ }
1956
+ clearCache() {
1957
+ this.loader.clearCache();
1958
+ this.loadingQueue.clear();
1959
+ }
1960
+ getStats() {
1961
+ return {
1962
+ registered: this.options.componentRegistry.size,
1963
+ loaded: this.loadedComponents.size,
1964
+ loading: this.loadingQueue.size,
1965
+ dependencies: this.dependencyGraph.size
1966
+ };
1967
+ }
1968
+ };
1969
+ var componentLoader = new ComponentLoader();
1970
+
1971
+ // src/runtime-factory.js
1972
+ var RuntimeEnvironment = {
1973
+ BROWSER: "browser",
1974
+ NODE: "node",
1975
+ EDGE: "edge",
1976
+ CLOUDFLARE: "cloudflare",
1977
+ DENO: "deno",
1978
+ BUN: "bun",
1979
+ ELECTRON: "electron",
1980
+ TAURI: "tauri",
1981
+ STATIC: "static"
1982
+ };
1983
+ function detectRuntime() {
1984
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1985
+ if (typeof window.require !== "undefined" || typeof window.process !== "undefined" && window.process.versions?.electron) {
1986
+ return RuntimeEnvironment.ELECTRON;
1987
+ }
1988
+ if (typeof window.__TAURI__ !== "undefined") {
1989
+ return RuntimeEnvironment.TAURI;
1990
+ }
1991
+ return RuntimeEnvironment.BROWSER;
1992
+ }
1993
+ if (typeof process !== "undefined") {
1994
+ if (process.versions?.node) {
1995
+ return RuntimeEnvironment.NODE;
1996
+ }
1997
+ }
1998
+ if (typeof EdgeRuntime !== "undefined") {
1999
+ return RuntimeEnvironment.EDGE;
2000
+ }
2001
+ if (typeof caches !== "undefined" && typeof Request !== "undefined" && typeof Response !== "undefined" && typeof addEventListener !== "undefined") {
2002
+ return RuntimeEnvironment.CLOUDFLARE;
2003
+ }
2004
+ if (typeof Deno !== "undefined") {
2005
+ return RuntimeEnvironment.DENO;
2006
+ }
2007
+ if (typeof Bun !== "undefined") {
2008
+ return RuntimeEnvironment.BUN;
2009
+ }
2010
+ return RuntimeEnvironment.BROWSER;
2011
+ }
2012
+ async function createRuntime(options = {}) {
2013
+ const environment = options.environment || detectRuntime();
2014
+ switch (environment) {
2015
+ case RuntimeEnvironment.BROWSER:
2016
+ case RuntimeEnvironment.ELECTRON:
2017
+ case RuntimeEnvironment.TAURI: {
2018
+ const { BrowserRuntime: BrowserRuntime2 } = await Promise.resolve().then(() => (init_browser(), browser_exports));
2019
+ return new BrowserRuntime2(options);
2020
+ }
2021
+ case RuntimeEnvironment.EDGE:
2022
+ case RuntimeEnvironment.CLOUDFLARE:
2023
+ case RuntimeEnvironment.DENO:
2024
+ case RuntimeEnvironment.BUN: {
2025
+ const { EdgeRuntime: EdgeRuntime3 } = await Promise.resolve().then(() => (init_edge(), edge_exports));
2026
+ return new EdgeRuntime3(options);
2027
+ }
2028
+ case RuntimeEnvironment.NODE: {
2029
+ const { NodeRuntime: NodeRuntime2 } = await Promise.resolve().then(() => (init_node(), node_exports));
2030
+ return new NodeRuntime2(options);
2031
+ }
2032
+ case RuntimeEnvironment.STATIC: {
2033
+ const { StaticRuntime: StaticRuntime2 } = await Promise.resolve().then(() => (init_static(), static_exports));
2034
+ return new StaticRuntime2(options);
2035
+ }
2036
+ default:
2037
+ throw new Error(`Unsupported runtime environment: ${environment}`);
2038
+ }
2039
+ }
2040
+
2041
+ // src/utils/runtime-detector.js
2042
+ var RuntimeEnvironment2 = {
2043
+ BROWSER: "browser",
2044
+ NODE: "node",
2045
+ DENO: "deno",
2046
+ BUN: "bun",
2047
+ EDGE: "edge",
2048
+ CLOUDFLARE: "cloudflare",
2049
+ ELECTRON: "electron",
2050
+ TAURI: "tauri",
2051
+ WEBVIEW: "webview",
2052
+ STATIC: "static",
2053
+ UNKNOWN: "unknown"
2054
+ };
2055
+ var RuntimeDetector = class _RuntimeDetector {
2056
+ constructor() {
2057
+ this.detectionResult = null;
2058
+ this.capabilities = null;
2059
+ }
2060
+ // Reset detection cache (useful for testing)
2061
+ reset() {
2062
+ this.detectionResult = null;
2063
+ this.capabilities = null;
2064
+ }
2065
+ // Main detection method
2066
+ detect() {
2067
+ if (this.detectionResult) {
2068
+ return this.detectionResult;
2069
+ }
2070
+ this.detectionResult = this.performDetection();
2071
+ return this.detectionResult;
2072
+ }
2073
+ performDetection() {
2074
+ if (this.isTauri()) return RuntimeEnvironment2.TAURI;
2075
+ if (this.isElectron()) return RuntimeEnvironment2.ELECTRON;
2076
+ if (this.isWebView()) return RuntimeEnvironment2.WEBVIEW;
2077
+ if (this.isDeno()) return RuntimeEnvironment2.DENO;
2078
+ if (this.isBun()) return RuntimeEnvironment2.BUN;
2079
+ if (this.isCloudflareWorkers()) return RuntimeEnvironment2.CLOUDFLARE;
2080
+ if (this.isEdgeRuntime()) return RuntimeEnvironment2.EDGE;
2081
+ if (this.isBrowser()) return RuntimeEnvironment2.BROWSER;
2082
+ if (this.isNodeJS()) return RuntimeEnvironment2.NODE;
2083
+ return RuntimeEnvironment2.UNKNOWN;
2084
+ }
2085
+ // Environment-specific detection methods
2086
+ isBrowser() {
2087
+ return typeof window !== "undefined" && typeof document !== "undefined" && typeof navigator !== "undefined";
2088
+ }
2089
+ isNodeJS() {
2090
+ return typeof process !== "undefined" && process.versions && process.versions.node && typeof __require !== "undefined";
2091
+ }
2092
+ isDeno() {
2093
+ return typeof Deno !== "undefined" && typeof Deno.version !== "undefined";
2094
+ }
2095
+ isBun() {
2096
+ return typeof Bun !== "undefined" || typeof process !== "undefined" && process.versions && process.versions.bun;
2097
+ }
2098
+ isElectron() {
2099
+ return typeof window !== "undefined" && typeof window.require !== "undefined" && typeof window.require("electron") !== "undefined";
2100
+ }
2101
+ isTauri() {
2102
+ return typeof window !== "undefined" && typeof window.__TAURI__ !== "undefined";
2103
+ }
2104
+ isWebView() {
2105
+ return typeof window !== "undefined" && (typeof window.webkit !== "undefined" || typeof window.external !== "undefined") && !this.isElectron() && !this.isTauri();
2106
+ }
2107
+ isCloudflareWorkers() {
2108
+ return typeof caches !== "undefined" && typeof fetch !== "undefined" && typeof Response !== "undefined" && typeof addEventListener !== "undefined" && typeof window === "undefined";
2109
+ }
2110
+ isEdgeRuntime() {
2111
+ return typeof EdgeRuntime !== "undefined" || typeof globalThis !== "undefined" && typeof globalThis.EdgeRuntime !== "undefined" || this.isVercelEdge() || this.isNetlifyEdge();
2112
+ }
2113
+ isVercelEdge() {
2114
+ return typeof process !== "undefined" && process.env && process.env.VERCEL === "1" && typeof EdgeRuntime !== "undefined";
2115
+ }
2116
+ isNetlifyEdge() {
2117
+ return typeof Netlify !== "undefined" || typeof process !== "undefined" && process.env && process.env.NETLIFY === "true";
2118
+ }
2119
+ // Detailed capability analysis
2120
+ getCapabilities(environment = null) {
2121
+ const env = environment || this.detect();
2122
+ if (this.capabilities && !environment) {
2123
+ return this.capabilities;
2124
+ }
2125
+ const capabilities = this.analyzeCapabilities(env);
2126
+ if (!environment) {
2127
+ this.capabilities = capabilities;
2128
+ }
2129
+ return capabilities;
2130
+ }
2131
+ analyzeCapabilities(environment) {
2132
+ const base = {
2133
+ environment,
2134
+ dom: false,
2135
+ ssr: false,
2136
+ filesystem: false,
2137
+ fetch: false,
2138
+ websockets: false,
2139
+ workers: false,
2140
+ storage: false,
2141
+ crypto: false,
2142
+ streams: false,
2143
+ modules: {
2144
+ esm: false,
2145
+ commonjs: false,
2146
+ dynamicImport: false
2147
+ },
2148
+ apis: {
2149
+ console: false,
2150
+ timers: false,
2151
+ events: false,
2152
+ url: false,
2153
+ base64: false
2154
+ }
2155
+ };
2156
+ switch (environment) {
2157
+ case RuntimeEnvironment2.BROWSER:
2158
+ return {
2159
+ ...base,
2160
+ dom: true,
2161
+ fetch: typeof fetch !== "undefined",
2162
+ websockets: typeof WebSocket !== "undefined",
2163
+ workers: typeof Worker !== "undefined",
2164
+ storage: typeof localStorage !== "undefined",
2165
+ crypto: typeof crypto !== "undefined",
2166
+ streams: typeof ReadableStream !== "undefined",
2167
+ modules: {
2168
+ esm: true,
2169
+ commonjs: false,
2170
+ dynamicImport: (() => {
2171
+ try {
2172
+ return typeof Function('return import("")') === "function";
2173
+ } catch {
2174
+ return false;
2175
+ }
2176
+ })()
2177
+ },
2178
+ apis: {
2179
+ console: typeof console !== "undefined",
2180
+ timers: typeof setTimeout !== "undefined",
2181
+ events: typeof EventTarget !== "undefined",
2182
+ url: typeof URL !== "undefined",
2183
+ base64: typeof btoa !== "undefined"
2184
+ }
2185
+ };
2186
+ case RuntimeEnvironment2.NODE:
2187
+ return {
2188
+ ...base,
2189
+ ssr: true,
2190
+ filesystem: true,
2191
+ fetch: typeof fetch !== "undefined",
2192
+ websockets: true,
2193
+ crypto: true,
2194
+ streams: true,
2195
+ modules: {
2196
+ esm: true,
2197
+ commonjs: true,
2198
+ dynamicImport: (() => {
2199
+ try {
2200
+ return typeof Function('return import("")') === "function";
2201
+ } catch {
2202
+ return false;
2203
+ }
2204
+ })()
2205
+ },
2206
+ apis: {
2207
+ console: true,
2208
+ timers: true,
2209
+ events: true,
2210
+ url: typeof URL !== "undefined",
2211
+ base64: typeof Buffer !== "undefined"
2212
+ }
2213
+ };
2214
+ case RuntimeEnvironment2.DENO:
2215
+ return {
2216
+ ...base,
2217
+ ssr: true,
2218
+ filesystem: typeof Deno.readTextFile !== "undefined",
2219
+ fetch: typeof fetch !== "undefined",
2220
+ websockets: typeof WebSocket !== "undefined",
2221
+ crypto: typeof crypto !== "undefined",
2222
+ streams: typeof ReadableStream !== "undefined",
2223
+ modules: {
2224
+ esm: true,
2225
+ commonjs: false,
2226
+ dynamicImport: true
2227
+ },
2228
+ apis: {
2229
+ console: true,
2230
+ timers: true,
2231
+ events: true,
2232
+ url: typeof URL !== "undefined",
2233
+ base64: typeof btoa !== "undefined"
2234
+ }
2235
+ };
2236
+ case RuntimeEnvironment2.BUN:
2237
+ return {
2238
+ ...base,
2239
+ ssr: true,
2240
+ filesystem: true,
2241
+ fetch: typeof fetch !== "undefined",
2242
+ websockets: typeof WebSocket !== "undefined",
2243
+ crypto: typeof crypto !== "undefined",
2244
+ streams: typeof ReadableStream !== "undefined",
2245
+ modules: {
2246
+ esm: true,
2247
+ commonjs: true,
2248
+ dynamicImport: true
2249
+ },
2250
+ apis: {
2251
+ console: true,
2252
+ timers: true,
2253
+ events: true,
2254
+ url: typeof URL !== "undefined",
2255
+ base64: typeof btoa !== "undefined"
2256
+ }
2257
+ };
2258
+ case RuntimeEnvironment2.CLOUDFLARE:
2259
+ return {
2260
+ ...base,
2261
+ ssr: true,
2262
+ fetch: typeof fetch !== "undefined",
2263
+ websockets: typeof WebSocket !== "undefined",
2264
+ storage: typeof caches !== "undefined",
2265
+ crypto: typeof crypto !== "undefined",
2266
+ streams: typeof ReadableStream !== "undefined",
2267
+ modules: {
2268
+ esm: true,
2269
+ commonjs: false,
2270
+ dynamicImport: true
2271
+ },
2272
+ apis: {
2273
+ console: true,
2274
+ timers: true,
2275
+ events: true,
2276
+ url: typeof URL !== "undefined",
2277
+ base64: typeof btoa !== "undefined"
2278
+ }
2279
+ };
2280
+ case RuntimeEnvironment2.ELECTRON:
2281
+ return {
2282
+ ...base,
2283
+ dom: true,
2284
+ ssr: true,
2285
+ filesystem: true,
2286
+ fetch: typeof fetch !== "undefined",
2287
+ websockets: typeof WebSocket !== "undefined",
2288
+ workers: typeof Worker !== "undefined",
2289
+ storage: typeof localStorage !== "undefined",
2290
+ crypto: typeof crypto !== "undefined",
2291
+ streams: typeof ReadableStream !== "undefined",
2292
+ modules: {
2293
+ esm: true,
2294
+ commonjs: true,
2295
+ dynamicImport: true
2296
+ },
2297
+ apis: {
2298
+ console: true,
2299
+ timers: true,
2300
+ events: true,
2301
+ url: typeof URL !== "undefined",
2302
+ base64: typeof btoa !== "undefined"
2303
+ }
2304
+ };
2305
+ case RuntimeEnvironment2.TAURI:
2306
+ return {
2307
+ ...base,
2308
+ dom: true,
2309
+ ssr: true,
2310
+ filesystem: typeof window !== "undefined" && typeof window.__TAURI__ !== "undefined",
2311
+ fetch: typeof fetch !== "undefined",
2312
+ websockets: typeof WebSocket !== "undefined",
2313
+ storage: typeof localStorage !== "undefined",
2314
+ crypto: typeof crypto !== "undefined",
2315
+ streams: typeof ReadableStream !== "undefined",
2316
+ modules: {
2317
+ esm: true,
2318
+ commonjs: false,
2319
+ dynamicImport: true
2320
+ },
2321
+ apis: {
2322
+ console: true,
2323
+ timers: true,
2324
+ events: true,
2325
+ url: typeof URL !== "undefined",
2326
+ base64: typeof btoa !== "undefined"
2327
+ }
2328
+ };
2329
+ default:
2330
+ return base;
2331
+ }
2332
+ }
2333
+ // Get detailed runtime information
2334
+ getRuntimeInfo() {
2335
+ const environment = this.detect();
2336
+ const capabilities = this.getCapabilities(environment);
2337
+ return {
2338
+ environment,
2339
+ capabilities,
2340
+ version: this.getRuntimeVersion(environment),
2341
+ features: this.getAvailableFeatures(),
2342
+ userAgent: this.getUserAgent(),
2343
+ platform: this.getPlatformInfo()
2344
+ };
2345
+ }
2346
+ // Alias method for backward compatibility
2347
+ getEnvironmentInfo() {
2348
+ return this.getRuntimeInfo();
2349
+ }
2350
+ getRuntimeVersion(environment) {
2351
+ switch (environment) {
2352
+ case RuntimeEnvironment2.NODE:
2353
+ return typeof process !== "undefined" ? process.version : null;
2354
+ case RuntimeEnvironment2.DENO:
2355
+ return typeof Deno !== "undefined" ? Deno.version.deno : null;
2356
+ case RuntimeEnvironment2.BUN:
2357
+ return typeof Bun !== "undefined" ? Bun.version : typeof process !== "undefined" ? process.versions.bun : null;
2358
+ case RuntimeEnvironment2.BROWSER:
2359
+ return typeof navigator !== "undefined" ? navigator.userAgent : null;
2360
+ default:
2361
+ return null;
2362
+ }
2363
+ }
2364
+ getAvailableFeatures() {
2365
+ const features = [];
2366
+ if (typeof fetch !== "undefined") features.push("fetch");
2367
+ if (typeof WebSocket !== "undefined") features.push("websockets");
2368
+ if (typeof Worker !== "undefined") features.push("workers");
2369
+ if (typeof crypto !== "undefined") features.push("crypto");
2370
+ if (typeof localStorage !== "undefined") features.push("localStorage");
2371
+ if (typeof sessionStorage !== "undefined") features.push("sessionStorage");
2372
+ if (typeof IndexedDB !== "undefined") features.push("indexedDB");
2373
+ if (typeof WebAssembly !== "undefined") features.push("webassembly");
2374
+ if (typeof SharedArrayBuffer !== "undefined") features.push("sharedArrayBuffer");
2375
+ if (typeof BigInt !== "undefined") features.push("bigint");
2376
+ if ((() => {
2377
+ try {
2378
+ return typeof Function('return import("")') === "function";
2379
+ } catch {
2380
+ return false;
2381
+ }
2382
+ })()) features.push("dynamicImport");
2383
+ return features;
2384
+ }
2385
+ getUserAgent() {
2386
+ if (typeof navigator !== "undefined" && navigator.userAgent) {
2387
+ return navigator.userAgent;
2388
+ }
2389
+ return null;
2390
+ }
2391
+ getPlatformInfo() {
2392
+ if (typeof navigator !== "undefined") {
2393
+ return {
2394
+ platform: navigator.platform,
2395
+ language: navigator.language,
2396
+ cookieEnabled: navigator.cookieEnabled,
2397
+ onLine: navigator.onLine
2398
+ };
2399
+ }
2400
+ if (typeof process !== "undefined") {
2401
+ return {
2402
+ platform: process.platform,
2403
+ arch: process.arch,
2404
+ version: process.version,
2405
+ pid: process.pid
2406
+ };
2407
+ }
2408
+ if (typeof Deno !== "undefined") {
2409
+ return {
2410
+ os: Deno.build.os,
2411
+ arch: Deno.build.arch,
2412
+ version: Deno.version
2413
+ };
2414
+ }
2415
+ return null;
2416
+ }
2417
+ // Compatibility checking
2418
+ isCompatible(requirements) {
2419
+ const capabilities = this.getCapabilities();
2420
+ for (const [feature, required] of Object.entries(requirements)) {
2421
+ if (required && !capabilities[feature]) {
2422
+ return false;
2423
+ }
2424
+ }
2425
+ return true;
2426
+ }
2427
+ getIncompatibilities(requirements) {
2428
+ const capabilities = this.getCapabilities();
2429
+ const incompatibilities = [];
2430
+ for (const [feature, required] of Object.entries(requirements)) {
2431
+ if (required && !capabilities[feature]) {
2432
+ incompatibilities.push(feature);
2433
+ }
2434
+ }
2435
+ return incompatibilities;
2436
+ }
2437
+ // Static methods for quick access
2438
+ static detect() {
2439
+ return new _RuntimeDetector().detect();
2440
+ }
2441
+ static getCapabilities(environment = null) {
2442
+ return new _RuntimeDetector().getCapabilities(environment);
2443
+ }
2444
+ static getRuntimeInfo() {
2445
+ return new _RuntimeDetector().getRuntimeInfo();
2446
+ }
2447
+ static isCompatible(requirements) {
2448
+ return new _RuntimeDetector().isCompatible(requirements);
2449
+ }
2450
+ };
2451
+ function detectRuntime2() {
2452
+ return RuntimeDetector.detect();
2453
+ }
2454
+ var runtimeDetector = new RuntimeDetector();
2455
+
2456
+ // src/utils/module-resolver.js
2457
+ var ModuleResolver = class {
2458
+ constructor(options = {}) {
2459
+ this.options = {
2460
+ baseUrl: "",
2461
+ paths: {},
2462
+ aliases: {},
2463
+ extensions: [".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx"],
2464
+ moduleMap: {},
2465
+ cdnTemplate: "https://unpkg.com/{name}@{version}/{path}",
2466
+ fallbacks: [],
2467
+ ...options
2468
+ };
2469
+ this.environment = detectRuntime2();
2470
+ this.resolutionCache = /* @__PURE__ */ new Map();
2471
+ }
2472
+ // Main resolution method
2473
+ resolve(modulePath, context = {}) {
2474
+ const cacheKey = this.getCacheKey(modulePath, context);
2475
+ if (this.resolutionCache.has(cacheKey)) {
2476
+ return this.resolutionCache.get(cacheKey);
2477
+ }
2478
+ const resolved = this.doResolve(modulePath, context);
2479
+ this.resolutionCache.set(cacheKey, resolved);
2480
+ return resolved;
2481
+ }
2482
+ doResolve(modulePath, context = {}) {
2483
+ const pathInfo = this.analyzePath(modulePath);
2484
+ switch (pathInfo.type) {
2485
+ case "absolute":
2486
+ return this.resolveAbsolute(pathInfo, context);
2487
+ case "relative":
2488
+ return this.resolveRelative(pathInfo, context);
2489
+ case "package":
2490
+ return this.resolvePackage(pathInfo, context);
2491
+ case "alias":
2492
+ return this.resolveAlias(pathInfo, context);
2493
+ case "mapped":
2494
+ return this.resolveMapped(pathInfo, context);
2495
+ default:
2496
+ throw new Error(`Unable to resolve module: ${modulePath}`);
2497
+ }
2498
+ }
2499
+ analyzePath(modulePath) {
2500
+ if (/^https?:\/\//.test(modulePath)) {
2501
+ return { type: "absolute", path: modulePath, original: modulePath };
2502
+ }
2503
+ if (modulePath.startsWith("file://")) {
2504
+ return { type: "absolute", path: modulePath, original: modulePath };
2505
+ }
2506
+ if (modulePath.startsWith("./") || modulePath.startsWith("../")) {
2507
+ return { type: "relative", path: modulePath, original: modulePath };
2508
+ }
2509
+ if (this.options.moduleMap[modulePath]) {
2510
+ return {
2511
+ type: "mapped",
2512
+ path: modulePath,
2513
+ mapped: this.options.moduleMap[modulePath],
2514
+ original: modulePath
2515
+ };
2516
+ }
2517
+ const aliasKey = Object.keys(this.options.aliases).find(
2518
+ (alias) => modulePath.startsWith(`${alias}/`) || modulePath === alias
2519
+ );
2520
+ if (aliasKey) {
2521
+ return {
2522
+ type: "alias",
2523
+ path: modulePath,
2524
+ alias: aliasKey,
2525
+ remainder: modulePath.slice(aliasKey.length + 1),
2526
+ original: modulePath
2527
+ };
2528
+ }
2529
+ return { type: "package", path: modulePath, original: modulePath };
2530
+ }
2531
+ resolveAbsolute(pathInfo) {
2532
+ return {
2533
+ resolved: pathInfo.path,
2534
+ type: "absolute",
2535
+ original: pathInfo.original
2536
+ };
2537
+ }
2538
+ resolveRelative(pathInfo, context) {
2539
+ let baseUrl = context.baseUrl || this.options.baseUrl || "";
2540
+ if (this.environment === RuntimeEnvironment2.BROWSER && !baseUrl) {
2541
+ baseUrl = window.location.href;
2542
+ }
2543
+ if (!baseUrl) {
2544
+ throw new Error(`Cannot resolve relative path "${pathInfo.path}" without base URL`);
2545
+ }
2546
+ const resolved = new URL(pathInfo.path, baseUrl).href;
2547
+ return {
2548
+ resolved,
2549
+ type: "relative",
2550
+ original: pathInfo.original,
2551
+ baseUrl
2552
+ };
2553
+ }
2554
+ resolvePackage(pathInfo, context) {
2555
+ const packageName = this.parsePackageName(pathInfo.path);
2556
+ switch (this.environment) {
2557
+ case RuntimeEnvironment2.BROWSER:
2558
+ return this.resolveBrowserPackage(packageName, context);
2559
+ case RuntimeEnvironment2.NODE:
2560
+ return this.resolveNodePackage(packageName, context);
2561
+ case RuntimeEnvironment2.DENO:
2562
+ return this.resolveDenoPackage(packageName, context);
2563
+ case RuntimeEnvironment2.BUN:
2564
+ return this.resolveBunPackage(packageName, context);
2565
+ case RuntimeEnvironment2.CLOUDFLARE:
2566
+ case RuntimeEnvironment2.EDGE:
2567
+ return this.resolveEdgePackage(packageName, context);
2568
+ default:
2569
+ return this.resolveGenericPackage(packageName, context);
2570
+ }
2571
+ }
2572
+ parsePackageName(modulePath) {
2573
+ const parts = modulePath.split("/");
2574
+ if (modulePath.startsWith("@")) {
2575
+ return {
2576
+ name: `${parts[0]}/${parts[1]}`,
2577
+ subpath: parts.slice(2).join("/"),
2578
+ scope: parts[0],
2579
+ packageName: parts[1]
2580
+ };
2581
+ } else {
2582
+ return {
2583
+ name: parts[0],
2584
+ subpath: parts.slice(1).join("/"),
2585
+ scope: null,
2586
+ packageName: parts[0]
2587
+ };
2588
+ }
2589
+ }
2590
+ resolveBrowserPackage(packageInfo, context) {
2591
+ const cdnUrl = this.resolveToCdn(packageInfo, context);
2592
+ return {
2593
+ resolved: cdnUrl,
2594
+ type: "package",
2595
+ strategy: "cdn",
2596
+ original: packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : ""),
2597
+ package: packageInfo
2598
+ };
2599
+ }
2600
+ resolveNodePackage(packageInfo) {
2601
+ const modulePath = packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : "");
2602
+ return {
2603
+ resolved: modulePath,
2604
+ type: "package",
2605
+ strategy: "node",
2606
+ original: modulePath,
2607
+ package: packageInfo
2608
+ };
2609
+ }
2610
+ resolveDenoPackage(packageInfo) {
2611
+ const modulePath = `npm:${packageInfo.name}${packageInfo.subpath ? `/${packageInfo.subpath}` : ""}`;
2612
+ return {
2613
+ resolved: modulePath,
2614
+ type: "package",
2615
+ strategy: "deno-npm",
2616
+ original: packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : ""),
2617
+ package: packageInfo
2618
+ };
2619
+ }
2620
+ resolveBunPackage(packageInfo) {
2621
+ const modulePath = packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : "");
2622
+ return {
2623
+ resolved: modulePath,
2624
+ type: "package",
2625
+ strategy: "bun",
2626
+ original: modulePath,
2627
+ package: packageInfo
2628
+ };
2629
+ }
2630
+ resolveEdgePackage(packageInfo, context) {
2631
+ const cdnUrl = this.resolveToCdn(packageInfo, context);
2632
+ return {
2633
+ resolved: cdnUrl,
2634
+ type: "package",
2635
+ strategy: "edge-cdn",
2636
+ original: packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : ""),
2637
+ package: packageInfo
2638
+ };
2639
+ }
2640
+ resolveGenericPackage(packageInfo) {
2641
+ const modulePath = packageInfo.name + (packageInfo.subpath ? `/${packageInfo.subpath}` : "");
2642
+ return {
2643
+ resolved: modulePath,
2644
+ type: "package",
2645
+ strategy: "generic",
2646
+ original: modulePath,
2647
+ package: packageInfo
2648
+ };
2649
+ }
2650
+ resolveToCdn(packageInfo, context = {}) {
2651
+ const version = context.version || "latest";
2652
+ const subpath = packageInfo.subpath || "dist/index.js";
2653
+ return this.options.cdnTemplate.replace("{name}", packageInfo.name).replace("{version}", version).replace("{path}", subpath);
2654
+ }
2655
+ resolveAlias(pathInfo, context) {
2656
+ const aliasTarget = this.options.aliases[pathInfo.alias];
2657
+ const resolvedPath = pathInfo.remainder ? `${aliasTarget}/${pathInfo.remainder}` : aliasTarget;
2658
+ const resolved = this.doResolve(resolvedPath, context);
2659
+ return {
2660
+ ...resolved,
2661
+ type: "alias",
2662
+ alias: pathInfo.alias,
2663
+ aliasTarget,
2664
+ original: pathInfo.original
2665
+ };
2666
+ }
2667
+ resolveMapped(pathInfo, context) {
2668
+ const mapped = pathInfo.mapped;
2669
+ if (typeof mapped === "function") {
2670
+ const result = mapped(pathInfo.path, context);
2671
+ return {
2672
+ resolved: result,
2673
+ type: "mapped",
2674
+ original: pathInfo.original,
2675
+ mapFunction: true
2676
+ };
2677
+ }
2678
+ return {
2679
+ resolved: mapped,
2680
+ type: "mapped",
2681
+ original: pathInfo.original
2682
+ };
2683
+ }
2684
+ // Path utilities
2685
+ addExtension(path, extensions = null) {
2686
+ const exts = extensions || this.options.extensions;
2687
+ if (exts.some((ext) => path.endsWith(ext))) {
2688
+ return path;
2689
+ }
2690
+ return path + exts[0];
2691
+ }
2692
+ stripExtension(path) {
2693
+ const ext = this.options.extensions.find((e) => path.endsWith(e));
2694
+ return ext ? path.slice(0, -ext.length) : path;
2695
+ }
2696
+ isRelative(path) {
2697
+ return path.startsWith("./") || path.startsWith("../");
2698
+ }
2699
+ isAbsolute(path) {
2700
+ return /^https?:\/\//.test(path) || path.startsWith("file://");
2701
+ }
2702
+ // Configuration methods
2703
+ addAlias(alias, target) {
2704
+ this.options.aliases[alias] = target;
2705
+ this.clearCache();
2706
+ }
2707
+ addMapping(from, to) {
2708
+ this.options.moduleMap[from] = to;
2709
+ this.clearCache();
2710
+ }
2711
+ setBaseUrl(baseUrl) {
2712
+ this.options.baseUrl = baseUrl;
2713
+ this.clearCache();
2714
+ }
2715
+ setCdnTemplate(template) {
2716
+ this.options.cdnTemplate = template;
2717
+ this.clearCache();
2718
+ }
2719
+ // Path patterns and wildcards
2720
+ resolvePattern(pattern, replacements = {}) {
2721
+ let resolved = pattern;
2722
+ Object.entries(replacements).forEach(([key, value]) => {
2723
+ resolved = resolved.replace(new RegExp(`\\{${key}\\}`, "g"), value);
2724
+ });
2725
+ return resolved;
2726
+ }
2727
+ // Batch resolution
2728
+ resolveAll(modulePaths, context = {}) {
2729
+ return modulePaths.map((path) => {
2730
+ try {
2731
+ return { path, resolution: this.resolve(path, context), success: true };
2732
+ } catch (error) {
2733
+ return { path, error, success: false };
2734
+ }
2735
+ });
2736
+ }
2737
+ // Cache management
2738
+ getCacheKey(modulePath, context) {
2739
+ return `${modulePath}::${JSON.stringify(context)}`;
2740
+ }
2741
+ clearCache() {
2742
+ this.resolutionCache.clear();
2743
+ }
2744
+ getCacheStats() {
2745
+ return {
2746
+ size: this.resolutionCache.size,
2747
+ keys: Array.from(this.resolutionCache.keys())
2748
+ };
2749
+ }
2750
+ // Validation
2751
+ validateResolution(resolution) {
2752
+ if (!resolution || !resolution.resolved) {
2753
+ return { valid: false, error: "Invalid resolution object" };
2754
+ }
2755
+ switch (resolution.type) {
2756
+ case "absolute":
2757
+ if (!this.isAbsolute(resolution.resolved)) {
2758
+ return { valid: false, error: "Absolute resolution must be a valid URL" };
2759
+ }
2760
+ break;
2761
+ case "relative":
2762
+ if (!resolution.baseUrl) {
2763
+ return { valid: false, error: "Relative resolution must include baseUrl" };
2764
+ }
2765
+ break;
2766
+ }
2767
+ return { valid: true };
2768
+ }
2769
+ // Debug utilities
2770
+ debug(modulePath, context = {}) {
2771
+ const pathInfo = this.analyzePath(modulePath);
2772
+ const resolution = this.resolve(modulePath, context);
2773
+ const validation = this.validateResolution(resolution);
2774
+ return {
2775
+ input: modulePath,
2776
+ context,
2777
+ pathInfo,
2778
+ resolution,
2779
+ validation,
2780
+ environment: this.environment,
2781
+ options: this.options
2782
+ };
2783
+ }
2784
+ };
2785
+ var moduleResolver = new ModuleResolver();
2786
+
2787
+ // src/utils/asset-manager.js
2788
+ var AssetManager = class {
2789
+ constructor(options = {}) {
2790
+ this.options = {
2791
+ baseUrl: "",
2792
+ assetPaths: {},
2793
+ preloadAssets: [],
2794
+ lazyLoad: true,
2795
+ cacheAssets: true,
2796
+ optimizeImages: true,
2797
+ inlineThreshold: 1024,
2798
+ // Inline assets smaller than this (bytes)
2799
+ supportedFormats: {
2800
+ images: ["png", "jpg", "jpeg", "gif", "svg", "webp", "avif"],
2801
+ styles: ["css"],
2802
+ fonts: ["woff", "woff2", "ttf", "otf"],
2803
+ scripts: ["js", "mjs"]
2804
+ },
2805
+ ...options
2806
+ };
2807
+ this.environment = detectRuntime2();
2808
+ this.loadedAssets = /* @__PURE__ */ new Map();
2809
+ this.loadingAssets = /* @__PURE__ */ new Map();
2810
+ this.assetCache = /* @__PURE__ */ new Map();
2811
+ }
2812
+ // Main asset loading method
2813
+ async loadAsset(assetPath, options = {}) {
2814
+ const resolvedPath = this.resolvePath(assetPath, options);
2815
+ const assetType = this.getAssetType(resolvedPath);
2816
+ const cacheKey = this.getCacheKey(resolvedPath, options);
2817
+ if (this.options.cacheAssets && this.loadedAssets.has(cacheKey)) {
2818
+ return this.loadedAssets.get(cacheKey);
2819
+ }
2820
+ if (this.loadingAssets.has(cacheKey)) {
2821
+ return this.loadingAssets.get(cacheKey);
2822
+ }
2823
+ const loadingPromise = this.doLoadAsset(resolvedPath, assetType, options);
2824
+ this.loadingAssets.set(cacheKey, loadingPromise);
2825
+ try {
2826
+ const asset = await loadingPromise;
2827
+ if (this.options.cacheAssets) {
2828
+ this.loadedAssets.set(cacheKey, asset);
2829
+ }
2830
+ return asset;
2831
+ } finally {
2832
+ this.loadingAssets.delete(cacheKey);
2833
+ }
2834
+ }
2835
+ async doLoadAsset(assetPath, assetType, options = {}) {
2836
+ switch (assetType) {
2837
+ case "css":
2838
+ return await this.loadStylesheet(assetPath, options);
2839
+ case "image":
2840
+ return await this.loadImage(assetPath, options);
2841
+ case "font":
2842
+ return await this.loadFont(assetPath, options);
2843
+ case "script":
2844
+ return await this.loadScript(assetPath, options);
2845
+ case "data":
2846
+ return await this.loadData(assetPath, options);
2847
+ default:
2848
+ return await this.loadGeneric(assetPath, options);
2849
+ }
2850
+ }
2851
+ // CSS loading
2852
+ async loadStylesheet(cssPath, options = {}) {
2853
+ if (this.environment === RuntimeEnvironment2.BROWSER) {
2854
+ return await this.loadBrowserStylesheet(cssPath, options);
2855
+ } else {
2856
+ return await this.loadServerStylesheet(cssPath, options);
2857
+ }
2858
+ }
2859
+ async loadBrowserStylesheet(cssPath, options = {}) {
2860
+ return new Promise((resolve, reject) => {
2861
+ const existing = document.querySelector(`link[href="${cssPath}"]`);
2862
+ if (existing) {
2863
+ resolve({ element: existing, cached: true });
2864
+ return;
2865
+ }
2866
+ const link = document.createElement("link");
2867
+ link.rel = "stylesheet";
2868
+ link.href = cssPath;
2869
+ if (options.media) link.media = options.media;
2870
+ if (options.crossorigin) link.crossOrigin = options.crossorigin;
2871
+ link.onload = () => {
2872
+ resolve({ element: link, loaded: true });
2873
+ };
2874
+ link.onerror = () => {
2875
+ reject(new Error(`Failed to load stylesheet: ${cssPath}`));
2876
+ };
2877
+ document.head.appendChild(link);
2878
+ });
2879
+ }
2880
+ async loadServerStylesheet(cssPath) {
2881
+ try {
2882
+ const response = await fetch(cssPath);
2883
+ const content = await response.text();
2884
+ return {
2885
+ content,
2886
+ path: cssPath,
2887
+ inline: true
2888
+ };
2889
+ } catch (error) {
2890
+ throw new Error(`Failed to load stylesheet: ${cssPath} - ${error.message}`);
2891
+ }
2892
+ }
2893
+ // Image loading
2894
+ async loadImage(imagePath, options = {}) {
2895
+ if (this.environment === RuntimeEnvironment2.BROWSER) {
2896
+ return await this.loadBrowserImage(imagePath, options);
2897
+ } else {
2898
+ return await this.loadServerImage(imagePath, options);
2899
+ }
2900
+ }
2901
+ async loadBrowserImage(imagePath, options = {}) {
2902
+ return new Promise((resolve, reject) => {
2903
+ const img = new Image();
2904
+ if (options.crossorigin) img.crossOrigin = options.crossorigin;
2905
+ if (options.loading) img.loading = options.loading;
2906
+ if (options.sizes) img.sizes = options.sizes;
2907
+ if (options.srcset) img.srcset = options.srcset;
2908
+ img.onload = () => {
2909
+ resolve({
2910
+ element: img,
2911
+ width: img.naturalWidth,
2912
+ height: img.naturalHeight,
2913
+ path: imagePath
2914
+ });
2915
+ };
2916
+ img.onerror = () => {
2917
+ reject(new Error(`Failed to load image: ${imagePath}`));
2918
+ };
2919
+ img.src = imagePath;
2920
+ });
2921
+ }
2922
+ async loadServerImage(imagePath) {
2923
+ try {
2924
+ const response = await fetch(imagePath);
2925
+ const blob = await response.blob();
2926
+ return {
2927
+ blob,
2928
+ size: blob.size,
2929
+ type: blob.type,
2930
+ path: imagePath
2931
+ };
2932
+ } catch (error) {
2933
+ throw new Error(`Failed to load image: ${imagePath} - ${error.message}`);
2934
+ }
2935
+ }
2936
+ // Font loading
2937
+ async loadFont(fontPath, options = {}) {
2938
+ if (this.environment === RuntimeEnvironment2.BROWSER && "fonts" in document) {
2939
+ return await this.loadBrowserFont(fontPath, options);
2940
+ } else {
2941
+ return await this.loadGeneric(fontPath, options);
2942
+ }
2943
+ }
2944
+ async loadBrowserFont(fontPath, options = {}) {
2945
+ try {
2946
+ const fontFace = new FontFace(
2947
+ options.family || "CustomFont",
2948
+ `url(${fontPath})`,
2949
+ {
2950
+ style: options.style || "normal",
2951
+ weight: options.weight || "normal",
2952
+ stretch: options.stretch || "normal"
2953
+ }
2954
+ );
2955
+ await fontFace.load();
2956
+ document.fonts.add(fontFace);
2957
+ return {
2958
+ fontFace,
2959
+ family: options.family,
2960
+ loaded: true
2961
+ };
2962
+ } catch (error) {
2963
+ throw new Error(`Failed to load font: ${fontPath} - ${error.message}`);
2964
+ }
2965
+ }
2966
+ // Script loading
2967
+ async loadScript(scriptPath, options = {}) {
2968
+ if (this.environment === RuntimeEnvironment2.BROWSER) {
2969
+ return await this.loadBrowserScript(scriptPath, options);
2970
+ } else {
2971
+ return await this.loadServerScript(scriptPath, options);
2972
+ }
2973
+ }
2974
+ async loadBrowserScript(scriptPath, options = {}) {
2975
+ return new Promise((resolve, reject) => {
2976
+ const existing = document.querySelector(`script[src="${scriptPath}"]`);
2977
+ if (existing) {
2978
+ resolve({ element: existing, cached: true });
2979
+ return;
2980
+ }
2981
+ const script = document.createElement("script");
2982
+ script.src = scriptPath;
2983
+ if (options.type) script.type = options.type;
2984
+ if (options.async !== void 0) script.async = options.async;
2985
+ if (options.defer !== void 0) script.defer = options.defer;
2986
+ if (options.crossorigin) script.crossOrigin = options.crossorigin;
2987
+ script.onload = () => {
2988
+ resolve({ element: script, loaded: true });
2989
+ };
2990
+ script.onerror = () => {
2991
+ reject(new Error(`Failed to load script: ${scriptPath}`));
2992
+ };
2993
+ document.head.appendChild(script);
2994
+ });
2995
+ }
2996
+ async loadServerScript(scriptPath, options = {}) {
2997
+ try {
2998
+ const response = await fetch(scriptPath);
2999
+ const content = await response.text();
3000
+ return {
3001
+ content,
3002
+ path: scriptPath,
3003
+ type: options.type || "text/javascript"
3004
+ };
3005
+ } catch (error) {
3006
+ throw new Error(`Failed to load script: ${scriptPath} - ${error.message}`);
3007
+ }
3008
+ }
3009
+ // Data loading (JSON, XML, etc.)
3010
+ async loadData(dataPath) {
3011
+ try {
3012
+ const response = await fetch(dataPath);
3013
+ const contentType = response.headers.get("content-type") || "";
3014
+ let data;
3015
+ if (contentType.includes("application/json")) {
3016
+ data = await response.json();
3017
+ } else if (contentType.includes("text/xml") || contentType.includes("application/xml")) {
3018
+ const text = await response.text();
3019
+ data = this.parseXML(text);
3020
+ } else {
3021
+ data = await response.text();
3022
+ }
3023
+ return {
3024
+ data,
3025
+ contentType,
3026
+ path: dataPath
3027
+ };
3028
+ } catch (error) {
3029
+ throw new Error(`Failed to load data: ${dataPath} - ${error.message}`);
3030
+ }
3031
+ }
3032
+ parseXML(xmlString) {
3033
+ if (typeof DOMParser !== "undefined") {
3034
+ const parser = new DOMParser();
3035
+ return parser.parseFromString(xmlString, "text/xml");
3036
+ }
3037
+ return xmlString;
3038
+ }
3039
+ // Generic loading
3040
+ async loadGeneric(assetPath) {
3041
+ try {
3042
+ const response = await fetch(assetPath);
3043
+ const blob = await response.blob();
3044
+ return {
3045
+ blob,
3046
+ size: blob.size,
3047
+ type: blob.type,
3048
+ path: assetPath
3049
+ };
3050
+ } catch (error) {
3051
+ throw new Error(`Failed to load asset: ${assetPath} - ${error.message}`);
3052
+ }
3053
+ }
3054
+ // Path resolution
3055
+ resolvePath(assetPath, options = {}) {
3056
+ if (typeof assetPath !== "string") {
3057
+ throw new Error(`Expected string path, got ${typeof assetPath}: ${assetPath}`);
3058
+ }
3059
+ if (assetPath.startsWith("http://") || assetPath.startsWith("https://")) {
3060
+ return assetPath;
3061
+ }
3062
+ if (assetPath.startsWith("data:")) {
3063
+ return assetPath;
3064
+ }
3065
+ if (assetPath.startsWith("blob:")) {
3066
+ return assetPath;
3067
+ }
3068
+ if (this.options.assetPaths[assetPath]) {
3069
+ return this.options.assetPaths[assetPath];
3070
+ }
3071
+ const baseUrl = options.baseUrl || this.options.baseUrl;
3072
+ if (baseUrl) {
3073
+ return new URL(assetPath, baseUrl).href;
3074
+ }
3075
+ return assetPath;
3076
+ }
3077
+ // Asset type detection
3078
+ getAssetType(assetPath) {
3079
+ const extension = this.getFileExtension(assetPath).toLowerCase();
3080
+ if (this.options.supportedFormats.images.includes(extension)) {
3081
+ return "image";
3082
+ }
3083
+ if (this.options.supportedFormats.styles.includes(extension)) {
3084
+ return "css";
3085
+ }
3086
+ if (this.options.supportedFormats.fonts.includes(extension)) {
3087
+ return "font";
3088
+ }
3089
+ if (this.options.supportedFormats.scripts.includes(extension)) {
3090
+ return "script";
3091
+ }
3092
+ if (["json", "xml"].includes(extension)) {
3093
+ return "data";
3094
+ }
3095
+ return "generic";
3096
+ }
3097
+ getFileExtension(path) {
3098
+ const cleanPath = path.split("?")[0].split("#")[0];
3099
+ const parts = cleanPath.split(".");
3100
+ return parts.length > 1 ? parts.pop() : "";
3101
+ }
3102
+ // Batch operations
3103
+ async loadAssets(assetPaths, options = {}) {
3104
+ const loadPromises = assetPaths.map(
3105
+ (path) => this.loadAsset(path, options).catch((error) => ({ error, path }))
3106
+ );
3107
+ const results = await Promise.all(loadPromises);
3108
+ return {
3109
+ successful: results.filter((r) => !r.error),
3110
+ failed: results.filter((r) => r.error)
3111
+ };
3112
+ }
3113
+ // Preloading
3114
+ async preloadAssets(assetPaths = null) {
3115
+ const toPreload = assetPaths || this.options.preloadAssets;
3116
+ if (this.environment === RuntimeEnvironment2.BROWSER) {
3117
+ return await this.preloadBrowserAssets(toPreload);
3118
+ } else {
3119
+ return await this.loadAssets(toPreload, { preload: true });
3120
+ }
3121
+ }
3122
+ async preloadBrowserAssets(assetPaths) {
3123
+ const preloadPromises = assetPaths.map(async (assetPath) => {
3124
+ try {
3125
+ const link = document.createElement("link");
3126
+ link.rel = "preload";
3127
+ link.href = this.resolvePath(assetPath);
3128
+ const assetType = this.getAssetType(assetPath);
3129
+ switch (assetType) {
3130
+ case "css":
3131
+ link.as = "style";
3132
+ break;
3133
+ case "script":
3134
+ link.as = "script";
3135
+ break;
3136
+ case "font":
3137
+ link.as = "font";
3138
+ link.crossOrigin = "anonymous";
3139
+ break;
3140
+ case "image":
3141
+ link.as = "image";
3142
+ break;
3143
+ }
3144
+ document.head.appendChild(link);
3145
+ return { success: true, path: assetPath };
3146
+ } catch (error) {
3147
+ return { success: false, path: assetPath, error };
3148
+ }
3149
+ });
3150
+ return await Promise.all(preloadPromises);
3151
+ }
3152
+ // Cache management
3153
+ getCacheKey(assetPath, options) {
3154
+ return `${assetPath}::${JSON.stringify(options)}`;
3155
+ }
3156
+ clearCache() {
3157
+ this.loadedAssets.clear();
3158
+ this.assetCache.clear();
3159
+ }
3160
+ getCacheStats() {
3161
+ return {
3162
+ loaded: this.loadedAssets.size,
3163
+ loading: this.loadingAssets.size,
3164
+ cached: this.assetCache.size
3165
+ };
3166
+ }
3167
+ // Asset optimization
3168
+ shouldInline(assetPath, size = null) {
3169
+ if (size && size <= this.options.inlineThreshold) {
3170
+ return true;
3171
+ }
3172
+ return false;
3173
+ }
3174
+ async optimizeImage(imagePath, options = {}) {
3175
+ return await this.loadImage(imagePath, options);
3176
+ }
3177
+ // Utilities
3178
+ addAssetPath(alias, path) {
3179
+ this.options.assetPaths[alias] = path;
3180
+ }
3181
+ setBaseUrl(baseUrl) {
3182
+ this.options.baseUrl = baseUrl;
3183
+ }
3184
+ isAssetLoaded(assetPath) {
3185
+ const resolvedPath = this.resolvePath(assetPath);
3186
+ return this.loadedAssets.has(this.getCacheKey(resolvedPath, {}));
3187
+ }
3188
+ getLoadedAssets() {
3189
+ return Array.from(this.loadedAssets.keys());
3190
+ }
3191
+ };
3192
+ var assetManager = new AssetManager();
3193
+
3194
+ // src/index.js
3195
+ async function createCoherentApp(options = {}) {
3196
+ const runtime = await createRuntime(options);
3197
+ return runtime.createApp(options);
3198
+ }
3199
+ function renderApp(component, props = {}, target = null) {
3200
+ const runtime = detectRuntime();
3201
+ if (typeof runtime === "object" && runtime.renderApp) {
3202
+ return runtime.renderApp(component, props, target);
3203
+ }
3204
+ throw new Error("renderApp requires a proper runtime implementation");
3205
+ }
3206
+ if (typeof window !== "undefined") {
3207
+ window.Coherent = {
3208
+ // Core functionality
3209
+ render: async (obj) => {
3210
+ const { render: render5 } = await import("@coherent.js/core");
3211
+ return render5(obj);
3212
+ },
3213
+ // Hydration
3214
+ hydrate: async (element, component, props) => {
3215
+ const { hydrate: hydrate2 } = await import("@coherent.js/client");
3216
+ return hydrate2(element, component, props);
3217
+ },
3218
+ // Web Components
3219
+ defineComponent: async (name, component, options) => {
3220
+ const { defineComponent } = await import("@coherent.js/web-components");
3221
+ return defineComponent(name, component, options);
3222
+ },
3223
+ // Universal app creation
3224
+ createApp: createCoherentApp,
3225
+ renderApp,
3226
+ // Version info
3227
+ VERSION: "1.1.1"
3228
+ };
3229
+ if (document.querySelector("[data-coherent-auto]")) {
3230
+ document.addEventListener("DOMContentLoaded", async () => {
3231
+ const { autoHydrate: autoHydrate2 } = await import("@coherent.js/client");
3232
+ autoHydrate2(window.componentRegistry || {});
3233
+ });
3234
+ }
3235
+ }
3236
+ var VERSION = "1.1.1";
3237
+ export {
3238
+ AssetManager,
3239
+ BrowserRuntime,
3240
+ ComponentLoader,
3241
+ DesktopRuntime,
3242
+ EdgeRuntime2 as EdgeRuntime,
3243
+ ModuleResolver,
3244
+ RuntimeDetector,
3245
+ RuntimeEnvironment,
3246
+ StaticRuntime,
3247
+ UniversalLoader,
3248
+ VERSION,
3249
+ createCoherentApp,
3250
+ createRuntime,
3251
+ detectRuntime,
3252
+ renderApp
3253
+ };
3254
+ //# sourceMappingURL=coherent-universal.js.map