@sigx/runtime-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1123 @@
1
+ import { detectAccess, effect, effectScope, signal, signal as signal$1, untrack, watch } from "@sigx/reactivity";
2
+
3
+ //#region src/platform.ts
4
+ let platformSyncProcessor = null;
5
+ /**
6
+ * Set the platform-specific sync processor for intrinsic elements.
7
+ * Called by runtime-dom to handle checkbox/radio/select sync bindings.
8
+ */
9
+ function setPlatformSyncProcessor(fn) {
10
+ platformSyncProcessor = fn;
11
+ }
12
+ /**
13
+ * Get the current platform sync processor (for internal use).
14
+ */
15
+ function getPlatformSyncProcessor() {
16
+ return platformSyncProcessor;
17
+ }
18
+
19
+ //#endregion
20
+ //#region src/plugins.ts
21
+ const plugins = [];
22
+ function registerComponentPlugin(plugin) {
23
+ plugins.push(plugin);
24
+ }
25
+ /**
26
+ * Get all registered plugins (internal use)
27
+ */
28
+ function getComponentPlugins() {
29
+ return plugins;
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/app.ts
34
+ const isDev = typeof process !== "undefined" && true || true;
35
+ /**
36
+ * Unique symbol for app context injection
37
+ */
38
+ const AppContextKey = Symbol("sigx:app");
39
+ let defaultMountFn = null;
40
+ /**
41
+ * Set the default mount function for the platform.
42
+ * Called by platform packages (runtime-dom, runtime-terminal) on import.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * // In @sigx/runtime-dom
47
+ * import { setDefaultMount } from '@sigx/runtime-core';
48
+ * setDefaultMount(domMount);
49
+ * ```
50
+ */
51
+ function setDefaultMount(mountFn) {
52
+ defaultMountFn = mountFn;
53
+ }
54
+ /**
55
+ * Get the current default mount function.
56
+ * @internal
57
+ */
58
+ function getDefaultMount() {
59
+ return defaultMountFn;
60
+ }
61
+ /**
62
+ * Create an application instance.
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * import { defineApp, defineInjectable } from '@sigx/runtime-core';
67
+ * import { render } from '@sigx/runtime-dom';
68
+ *
69
+ * // Define an injectable service
70
+ * const useApiConfig = defineInjectable(() => ({ baseUrl: 'https://api.example.com' }));
71
+ *
72
+ * const app = defineApp(<App />);
73
+ *
74
+ * app.use(myPlugin, { option: 'value' });
75
+ *
76
+ * // Provide using the injectable token (works with inject())
77
+ * app.provide(useApiConfig, { baseUrl: 'https://custom.api.com' });
78
+ *
79
+ * app.mount(document.getElementById('app')!, render);
80
+ * ```
81
+ */
82
+ function defineApp(rootComponent) {
83
+ const installedPlugins = /* @__PURE__ */ new Set();
84
+ const context = {
85
+ app: null,
86
+ provides: /* @__PURE__ */ new Map(),
87
+ config: {},
88
+ hooks: []
89
+ };
90
+ let isMounted = false;
91
+ let container = null;
92
+ let unmountFn = null;
93
+ const app = {
94
+ config: context.config,
95
+ use(plugin, options) {
96
+ if (installedPlugins.has(plugin)) {
97
+ if (isDev) console.warn(`Plugin ${plugin.name || "anonymous"} is already installed.`);
98
+ return app;
99
+ }
100
+ installedPlugins.add(plugin);
101
+ if (typeof plugin === "function") plugin(app, options);
102
+ else if (plugin && typeof plugin.install === "function") plugin.install(app, options);
103
+ else if (isDev) console.warn("Invalid plugin: must be a function or have an install() method.");
104
+ return app;
105
+ },
106
+ provide(token, value) {
107
+ const actualToken = token?._token ?? token;
108
+ if (isDev && context.provides.has(actualToken)) console.warn(`App-level provide: token is being overwritten.`);
109
+ context.provides.set(actualToken, value);
110
+ return app;
111
+ },
112
+ hook(hooks) {
113
+ context.hooks.push(hooks);
114
+ return app;
115
+ },
116
+ mount(target, renderFn) {
117
+ if (isMounted) {
118
+ if (isDev) console.warn("App is already mounted. Call app.unmount() first.");
119
+ return app;
120
+ }
121
+ const mountFn = renderFn ?? defaultMountFn;
122
+ if (!mountFn) throw new Error("No mount function provided and no default mount function set. Either pass a mount function to app.mount(), or import a platform package (e.g., @sigx/runtime-dom or @sigx/runtime-terminal) that sets the default.");
123
+ container = target;
124
+ isMounted = true;
125
+ const result = mountFn(rootComponent, target, context);
126
+ if (typeof result === "function") unmountFn = result;
127
+ return app;
128
+ },
129
+ unmount() {
130
+ if (!isMounted) {
131
+ if (isDev) console.warn("App is not mounted.");
132
+ return;
133
+ }
134
+ if (unmountFn) unmountFn();
135
+ context.provides.clear();
136
+ isMounted = false;
137
+ container = null;
138
+ },
139
+ get _context() {
140
+ return context;
141
+ },
142
+ get _isMounted() {
143
+ return isMounted;
144
+ },
145
+ get _container() {
146
+ return container;
147
+ }
148
+ };
149
+ context.app = app;
150
+ return app;
151
+ }
152
+ /**
153
+ * Notify all app hooks that a component was created.
154
+ * Called by the renderer after setup() returns.
155
+ */
156
+ function notifyComponentCreated(context, instance) {
157
+ if (!context) return;
158
+ for (const hooks of context.hooks) try {
159
+ hooks.onComponentCreated?.(instance);
160
+ } catch (err) {
161
+ handleHookError(context, err, instance, "onComponentCreated");
162
+ }
163
+ }
164
+ /**
165
+ * Notify all app hooks that a component was mounted.
166
+ * Called by the renderer after mount hooks run.
167
+ */
168
+ function notifyComponentMounted(context, instance) {
169
+ if (!context) return;
170
+ for (const hooks of context.hooks) try {
171
+ hooks.onComponentMounted?.(instance);
172
+ } catch (err) {
173
+ handleHookError(context, err, instance, "onComponentMounted");
174
+ }
175
+ }
176
+ /**
177
+ * Notify all app hooks that a component was unmounted.
178
+ * Called by the renderer before cleanup.
179
+ */
180
+ function notifyComponentUnmounted(context, instance) {
181
+ if (!context) return;
182
+ for (const hooks of context.hooks) try {
183
+ hooks.onComponentUnmounted?.(instance);
184
+ } catch (err) {
185
+ handleHookError(context, err, instance, "onComponentUnmounted");
186
+ }
187
+ }
188
+ /**
189
+ * Notify all app hooks that a component updated.
190
+ * Called by the renderer after re-render.
191
+ */
192
+ function notifyComponentUpdated(context, instance) {
193
+ if (!context) return;
194
+ for (const hooks of context.hooks) try {
195
+ hooks.onComponentUpdated?.(instance);
196
+ } catch (err) {
197
+ handleHookError(context, err, instance, "onComponentUpdated");
198
+ }
199
+ }
200
+ /**
201
+ * Handle an error in a component. Returns true if the error was handled.
202
+ * Called by the renderer when an error occurs in setup or render.
203
+ */
204
+ function handleComponentError(context, err, instance, info) {
205
+ if (!context) return false;
206
+ for (const hooks of context.hooks) try {
207
+ if (hooks.onComponentError?.(err, instance, info) === true) return true;
208
+ } catch (hookErr) {
209
+ console.error("Error in onComponentError hook:", hookErr);
210
+ }
211
+ if (context.config.errorHandler) try {
212
+ if (context.config.errorHandler(err, instance, info) === true) return true;
213
+ } catch (handlerErr) {
214
+ console.error("Error in app.config.errorHandler:", handlerErr);
215
+ }
216
+ return false;
217
+ }
218
+ /**
219
+ * Handle errors that occur in hooks themselves
220
+ */
221
+ function handleHookError(context, err, instance, hookName) {
222
+ console.error(`Error in ${hookName} hook:`, err);
223
+ if (context.config.errorHandler) try {
224
+ context.config.errorHandler(err, instance, `plugin hook: ${hookName}`);
225
+ } catch {}
226
+ }
227
+
228
+ //#endregion
229
+ //#region src/component.ts
230
+ let currentComponentContext = null;
231
+ function getCurrentInstance() {
232
+ return currentComponentContext;
233
+ }
234
+ function setCurrentInstance(ctx) {
235
+ const prev = currentComponentContext;
236
+ currentComponentContext = ctx;
237
+ return prev;
238
+ }
239
+ function onMount(fn) {
240
+ if (currentComponentContext) currentComponentContext.onMount(fn);
241
+ else console.warn("onMount called outside of component setup");
242
+ }
243
+ function onCleanup(fn) {
244
+ if (currentComponentContext) currentComponentContext.onCleanup(fn);
245
+ else console.warn("onCleanup called outside of component setup");
246
+ }
247
+ const componentRegistry = /* @__PURE__ */ new Map();
248
+ /**
249
+ * Get component metadata (for DevTools)
250
+ */
251
+ function getComponentMeta(factory) {
252
+ return componentRegistry.get(factory);
253
+ }
254
+ /**
255
+ * Helper to create a proxy that tracks property access
256
+ */
257
+ function createPropsProxy(target, onAccess) {
258
+ return new Proxy(target, { get(obj, prop) {
259
+ if (typeof prop === "string" && onAccess) onAccess(prop);
260
+ return obj[prop];
261
+ } });
262
+ }
263
+ /**
264
+ * Define a component. Returns a JSX factory function.
265
+ *
266
+ * @param setup - Setup function that receives context and returns a render function
267
+ * @param options - Optional configuration (e.g., name for DevTools)
268
+ *
269
+ * @example
270
+ * ```tsx
271
+ * type CardProps = DefineProp<"title", string> & DefineSlot<"header">;
272
+ *
273
+ * export const Card = defineComponent<CardProps>((ctx) => {
274
+ * const { title } = ctx.props;
275
+ * const { slots } = ctx;
276
+ *
277
+ * return () => (
278
+ * <div class="card">
279
+ * {slots.header?.() ?? <h2>{title}</h2>}
280
+ * {slots.default()}
281
+ * </div>
282
+ * );
283
+ * });
284
+ * ```
285
+ */
286
+ function defineComponent(setup, options) {
287
+ const factory = function(props) {
288
+ return {
289
+ type: factory,
290
+ props: props || {},
291
+ key: props?.key || null,
292
+ children: [],
293
+ dom: null
294
+ };
295
+ };
296
+ factory.__setup = setup;
297
+ factory.__name = options?.name;
298
+ factory.__props = null;
299
+ factory.__events = null;
300
+ factory.__ref = null;
301
+ factory.__slots = null;
302
+ componentRegistry.set(factory, {
303
+ name: options?.name,
304
+ setup
305
+ });
306
+ getComponentPlugins().forEach((p) => p.onDefine?.(options?.name, factory, setup));
307
+ return factory;
308
+ }
309
+
310
+ //#endregion
311
+ //#region src/jsx-runtime.ts
312
+ const Fragment = Symbol.for("sigx.Fragment");
313
+ const Text = Symbol.for("sigx.Text");
314
+ function normalizeChildren(children) {
315
+ if (children == null || children === false || children === true) return [];
316
+ if (Array.isArray(children)) return children.flatMap((c) => normalizeChildren(c));
317
+ if (typeof children === "string" || typeof children === "number") return [{
318
+ type: Text,
319
+ props: {},
320
+ key: null,
321
+ children: [],
322
+ dom: null,
323
+ text: children
324
+ }];
325
+ if (children.type) return [children];
326
+ return [];
327
+ }
328
+ /**
329
+ * Check if a type is a sigx component (has __setup)
330
+ */
331
+ function isComponent$1(type) {
332
+ return typeof type === "function" && "__setup" in type;
333
+ }
334
+ /**
335
+ * Create a JSX element - this is the core function called by TSX transpilation
336
+ */
337
+ function jsx(type, props, key) {
338
+ const processedProps = { ...props || {} };
339
+ if (props) {
340
+ for (const propKey in props) if (propKey === "sync") {
341
+ let syncBinding = props[propKey];
342
+ if (typeof syncBinding === "function") {
343
+ const detected = detectAccess(syncBinding);
344
+ if (detected) syncBinding = detected;
345
+ }
346
+ if (Array.isArray(syncBinding) && syncBinding.length === 2) {
347
+ const [stateObj, key$1] = syncBinding;
348
+ let handled = false;
349
+ const platformProcessor = getPlatformSyncProcessor();
350
+ if (typeof type === "string" && platformProcessor) handled = platformProcessor(type, processedProps, [stateObj, key$1], props);
351
+ if (!handled) {
352
+ processedProps.value = stateObj[key$1];
353
+ const existingHandler = processedProps["onUpdate:value"];
354
+ processedProps["onUpdate:value"] = (v) => {
355
+ stateObj[key$1] = v;
356
+ if (existingHandler) existingHandler(v);
357
+ };
358
+ }
359
+ delete processedProps.sync;
360
+ }
361
+ } else if (propKey.startsWith("sync:")) {
362
+ const syncBinding = props[propKey];
363
+ if (Array.isArray(syncBinding) && syncBinding.length === 2) {
364
+ const [stateObj, key$1] = syncBinding;
365
+ const name = propKey.slice(5);
366
+ processedProps[name] = stateObj[key$1];
367
+ const eventName = `onUpdate:${name}`;
368
+ const existingHandler = processedProps[eventName];
369
+ processedProps[eventName] = (v) => {
370
+ stateObj[key$1] = v;
371
+ if (existingHandler) existingHandler(v);
372
+ };
373
+ delete processedProps[propKey];
374
+ }
375
+ }
376
+ }
377
+ if (isComponent$1(type)) {
378
+ const { children: children$1, ...rest$1 } = processedProps;
379
+ return {
380
+ type,
381
+ props: {
382
+ ...rest$1,
383
+ children: children$1
384
+ },
385
+ key: key || rest$1.key || null,
386
+ children: [],
387
+ dom: null
388
+ };
389
+ }
390
+ if (typeof type === "function" && type !== Fragment) return type(processedProps);
391
+ const { children, ...rest } = processedProps;
392
+ return {
393
+ type,
394
+ props: rest,
395
+ key: key || rest.key || null,
396
+ children: normalizeChildren(children),
397
+ dom: null
398
+ };
399
+ }
400
+ /**
401
+ * JSX Factory for fragments
402
+ */
403
+ function jsxs(type, props, key) {
404
+ return jsx(type, props, key);
405
+ }
406
+ const jsxDEV = jsx;
407
+
408
+ //#endregion
409
+ //#region src/utils/index.ts
410
+ var Utils = class {
411
+ static isPromise(value) {
412
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
413
+ }
414
+ };
415
+ function guid$1() {
416
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
417
+ var r = Math.random() * 16 | 0;
418
+ return (c == "x" ? r : r & 3 | 8).toString(16);
419
+ });
420
+ }
421
+
422
+ //#endregion
423
+ //#region src/models/index.ts
424
+ const guid = guid$1;
425
+ let InstanceLifetimes = /* @__PURE__ */ function(InstanceLifetimes$1) {
426
+ InstanceLifetimes$1[InstanceLifetimes$1["Transient"] = 0] = "Transient";
427
+ InstanceLifetimes$1[InstanceLifetimes$1["Scoped"] = 1] = "Scoped";
428
+ InstanceLifetimes$1[InstanceLifetimes$1["Singleton"] = 2] = "Singleton";
429
+ return InstanceLifetimes$1;
430
+ }({});
431
+ function valueOf(obj) {
432
+ return obj;
433
+ }
434
+
435
+ //#endregion
436
+ //#region src/messaging/index.ts
437
+ function createTopic(options) {
438
+ let subscribers = [];
439
+ const publish = (data) => {
440
+ subscribers.forEach((s) => s(data));
441
+ };
442
+ const subscribe = (handler) => {
443
+ subscribers.push(handler);
444
+ const unsubscribe = () => {
445
+ const idx = subscribers.indexOf(handler);
446
+ if (idx > -1) subscribers.splice(idx, 1);
447
+ };
448
+ try {
449
+ onCleanup(unsubscribe);
450
+ } catch (e) {}
451
+ return { unsubscribe };
452
+ };
453
+ const destroy = () => {
454
+ subscribers = [];
455
+ };
456
+ return {
457
+ publish,
458
+ subscribe,
459
+ destroy
460
+ };
461
+ }
462
+ function toSubscriber(topic) {
463
+ return { subscribe: (handler) => topic.subscribe(handler) };
464
+ }
465
+
466
+ //#endregion
467
+ //#region src/di/injectable.ts
468
+ function inject(token) {
469
+ const ctx = getCurrentInstance();
470
+ if (!ctx) return void 0;
471
+ let current = ctx;
472
+ while (current) {
473
+ if (current.provides && current.provides.has(token)) return current.provides.get(token);
474
+ current = current.parent;
475
+ }
476
+ const appContext = getAppContext(ctx);
477
+ if (appContext && appContext.provides.has(token)) return appContext.provides.get(token);
478
+ }
479
+ /**
480
+ * Get the app context from the current component context
481
+ */
482
+ function getAppContext(ctx) {
483
+ let current = ctx;
484
+ while (current) {
485
+ if (current._appContext) return current._appContext;
486
+ current = current.parent;
487
+ }
488
+ return null;
489
+ }
490
+ /**
491
+ * Inject the App instance (useful for plugins)
492
+ */
493
+ function injectApp() {
494
+ return inject(AppContextKey);
495
+ }
496
+ function provide(token, value) {
497
+ const ctx = getCurrentInstance();
498
+ if (!ctx) {
499
+ console.warn("provide called outside of component setup");
500
+ return;
501
+ }
502
+ if (!ctx.provides) ctx.provides = /* @__PURE__ */ new Map();
503
+ ctx.provides.set(token, value);
504
+ }
505
+ const globalInstances = /* @__PURE__ */ new Map();
506
+ function defineInjectable(factory) {
507
+ const token = factory;
508
+ const useFn = () => {
509
+ const injected = inject(token);
510
+ if (injected) return injected;
511
+ if (!globalInstances.has(token)) globalInstances.set(token, factory());
512
+ return globalInstances.get(token);
513
+ };
514
+ useFn._factory = factory;
515
+ useFn._token = token;
516
+ return useFn;
517
+ }
518
+ function defineProvide(useFn) {
519
+ const factory = useFn._factory;
520
+ const token = useFn._token;
521
+ if (!factory || !token) throw new Error("defineProvide must be called with a function created by defineInjectable");
522
+ const instance = factory();
523
+ provide(token, instance);
524
+ return instance;
525
+ }
526
+
527
+ //#endregion
528
+ //#region src/di/factory.ts
529
+ var SubscriptionHandler = class {
530
+ unsubs = [];
531
+ add(unsub) {
532
+ this.unsubs.push(unsub);
533
+ }
534
+ unsubscribe() {
535
+ this.unsubs.forEach((u) => u());
536
+ this.unsubs = [];
537
+ }
538
+ };
539
+ function defineFactory(setup, lifetime, typeIdentifier) {
540
+ const factoryCreator = (...args) => {
541
+ const subscriptions = new SubscriptionHandler();
542
+ const deactivations = /* @__PURE__ */ new Set();
543
+ let customDispose = null;
544
+ const result = setup({
545
+ onDeactivated: (fn) => deactivations.add(fn),
546
+ subscriptions,
547
+ overrideDispose: (fn) => customDispose = fn
548
+ }, ...args);
549
+ const dispose = () => {
550
+ deactivations.forEach((d) => d());
551
+ subscriptions.unsubscribe();
552
+ result.dispose?.();
553
+ };
554
+ if (customDispose) customDispose(dispose);
555
+ else try {
556
+ onCleanup(() => dispose());
557
+ } catch (e) {}
558
+ return {
559
+ ...result,
560
+ dispose
561
+ };
562
+ };
563
+ if (setup.length <= 1) return defineInjectable(() => factoryCreator());
564
+ return factoryCreator;
565
+ }
566
+
567
+ //#endregion
568
+ //#region src/stores/store.ts
569
+ function defineStore(name, setup, lifetime = InstanceLifetimes.Scoped) {
570
+ return defineFactory((ctxFactory, ...args) => {
571
+ const scope = effectScope(true);
572
+ let messages = [];
573
+ const id = `${name}_${guid()}`;
574
+ const result = setup({
575
+ ...ctxFactory,
576
+ defineState: (state) => {
577
+ return defineState(state, id, scope, messages);
578
+ },
579
+ defineActions: (actions) => {
580
+ return defineActions(actions, id, messages);
581
+ }
582
+ }, ...args);
583
+ ctxFactory.onDeactivated(() => {
584
+ scope.stop();
585
+ messages?.forEach((m) => m.destroy());
586
+ messages = null;
587
+ });
588
+ if (!result.name) result.name = id;
589
+ return result;
590
+ }, lifetime);
591
+ }
592
+ function defineActions(actions, storeInstanceName, messages) {
593
+ const events = {};
594
+ const namespace = `${storeInstanceName}.actions.${guid()}`;
595
+ const onDispatching = {};
596
+ const onDispatched = {};
597
+ const onFailure = {};
598
+ const result = {
599
+ onDispatching,
600
+ onDispatched,
601
+ onFailure
602
+ };
603
+ function getEvent(actionName, type) {
604
+ const name = `${actionName}.${type}`;
605
+ if (!events[name]) {
606
+ events[name] = createTopic({
607
+ namespace,
608
+ name
609
+ });
610
+ messages.push(events[name]);
611
+ }
612
+ return events[name];
613
+ }
614
+ Object.keys(actions).forEach((actionName) => {
615
+ onDispatching[actionName] = { subscribe: (fn) => {
616
+ return getEvent(actionName, "onDispatching").subscribe(function() {
617
+ fn.apply(this, arguments[0]);
618
+ });
619
+ } };
620
+ onDispatched[actionName] = { subscribe: (fn) => {
621
+ return getEvent(actionName, "onDispatched").subscribe(function() {
622
+ const msg = arguments[0];
623
+ const allArguments = [msg.result].concat(Array.from(msg.args));
624
+ fn.apply(this, allArguments);
625
+ });
626
+ } };
627
+ onFailure[actionName] = { subscribe: (fn) => {
628
+ return getEvent(actionName, "onFailure").subscribe(function() {
629
+ const msg = arguments[0];
630
+ const allArguments = [msg.reason].concat(Array.from(msg.args));
631
+ fn.apply(this, allArguments);
632
+ });
633
+ } };
634
+ result[actionName] = function() {
635
+ try {
636
+ const currentArguments = arguments;
637
+ getEvent(actionName, "onDispatching").publish(currentArguments);
638
+ const returnedResult = actions[actionName].apply(this, currentArguments);
639
+ if (Utils.isPromise(returnedResult)) returnedResult.then((result$1) => {
640
+ getEvent(actionName, "onDispatched").publish({
641
+ result: returnedResult,
642
+ args: currentArguments
643
+ });
644
+ });
645
+ else getEvent(actionName, "onDispatched").publish({
646
+ result: returnedResult,
647
+ args: currentArguments
648
+ });
649
+ return returnedResult;
650
+ } catch (err) {
651
+ console.error(err);
652
+ getEvent(actionName, "onFailure").publish({
653
+ reason: err,
654
+ args: arguments
655
+ });
656
+ }
657
+ };
658
+ });
659
+ return result;
660
+ }
661
+ function defineState(value, storeInstanceName, scope, messages) {
662
+ const state = signal$1(value);
663
+ const events = {};
664
+ const mutate = {};
665
+ function initProperty(key) {
666
+ scope.run(() => {
667
+ watch(() => state[key], (newValue) => {
668
+ triggerEvent(key, newValue);
669
+ }, {
670
+ deep: true,
671
+ immediate: true
672
+ });
673
+ });
674
+ mutate[key] = (val) => {
675
+ try {
676
+ let newValue;
677
+ if (typeof val === "function") newValue = val(state[key]);
678
+ else newValue = val;
679
+ state[key] = newValue;
680
+ } catch (err) {
681
+ console.error(err);
682
+ }
683
+ };
684
+ const eventKey = `onMutated${key.charAt(0).toUpperCase()}${key.slice(1)}`;
685
+ if (!events[eventKey]) {
686
+ const topic = createTopic({
687
+ namespace: `${storeInstanceName}.events`,
688
+ name: eventKey
689
+ });
690
+ events[eventKey] = topic;
691
+ messages.push(topic);
692
+ }
693
+ }
694
+ function triggerEvent(name, value$1) {
695
+ const keyString = name;
696
+ events[`onMutated${keyString.charAt(0).toUpperCase()}${keyString.slice(1)}`]?.publish(value$1);
697
+ }
698
+ if (value) Object.keys(value).forEach((key) => {
699
+ initProperty(key);
700
+ });
701
+ return {
702
+ state,
703
+ events,
704
+ mutate
705
+ };
706
+ }
707
+
708
+ //#endregion
709
+ //#region src/renderer.ts
710
+ /**
711
+ * Check if a vnode type is a component (has __setup)
712
+ */
713
+ function isComponent(type) {
714
+ return typeof type === "function" && "__setup" in type;
715
+ }
716
+ function createRenderer(options) {
717
+ const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
718
+ let isPatching = false;
719
+ let currentAppContext = null;
720
+ function render(element, container, appContext) {
721
+ if (appContext) currentAppContext = appContext;
722
+ const oldVNode = container._vnode;
723
+ let vnode = null;
724
+ if (element != null && element !== false && element !== true) if (typeof element === "string" || typeof element === "number") vnode = {
725
+ type: Text,
726
+ props: {},
727
+ key: null,
728
+ children: [],
729
+ dom: null,
730
+ text: element
731
+ };
732
+ else vnode = element;
733
+ if (vnode) {
734
+ if (oldVNode) patch(oldVNode, vnode, container);
735
+ else mount(vnode, container);
736
+ container._vnode = vnode;
737
+ } else if (oldVNode) {
738
+ unmount(oldVNode, container);
739
+ container._vnode = null;
740
+ }
741
+ }
742
+ function mount(vnode, container, before = null) {
743
+ if (vnode.type === Text) {
744
+ const node = hostCreateText(String(vnode.text));
745
+ vnode.dom = node;
746
+ node.__vnode = vnode;
747
+ hostInsert(node, container, before);
748
+ return;
749
+ }
750
+ if (vnode.type === Fragment) {
751
+ const anchor = hostCreateComment("");
752
+ vnode.dom = anchor;
753
+ hostInsert(anchor, container, before);
754
+ vnode.children.forEach((child) => mount(child, container, anchor));
755
+ return;
756
+ }
757
+ if (isComponent(vnode.type)) {
758
+ mountComponent(vnode, container, before, vnode.type.__setup);
759
+ return;
760
+ }
761
+ const element = hostCreateElement(vnode.type);
762
+ vnode.dom = element;
763
+ element.__vnode = vnode;
764
+ if (vnode.props) {
765
+ for (const key in vnode.props) if (key !== "children" && key !== "key" && key !== "ref") hostPatchProp(element, key, null, vnode.props[key]);
766
+ }
767
+ if (vnode.props.ref) {
768
+ if (typeof vnode.props.ref === "function") vnode.props.ref(element);
769
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = element;
770
+ }
771
+ vnode.children.forEach((child) => {
772
+ child.parent = vnode;
773
+ mount(child, element);
774
+ });
775
+ hostInsert(element, container, before);
776
+ }
777
+ function unmount(vnode, container) {
778
+ if (vnode._effect) vnode._effect();
779
+ if (vnode.cleanup) vnode.cleanup();
780
+ if (isComponent(vnode.type)) {
781
+ const subTree = vnode._subTree;
782
+ if (subTree) unmount(subTree, container);
783
+ if (vnode.dom) hostRemove(vnode.dom);
784
+ if (vnode.props?.ref) {
785
+ if (typeof vnode.props.ref === "function") vnode.props.ref(null);
786
+ else if (typeof vnode.props.ref === "object") vnode.props.ref.current = null;
787
+ }
788
+ return;
789
+ }
790
+ if (vnode.type === Fragment) {
791
+ vnode.children.forEach((child) => unmount(child, container));
792
+ if (vnode.dom) hostRemove(vnode.dom);
793
+ return;
794
+ }
795
+ if (vnode.props?.ref) {
796
+ if (typeof vnode.props.ref === "function") vnode.props.ref(null);
797
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = null;
798
+ }
799
+ if (vnode.children && vnode.children.length > 0) vnode.children.forEach((child) => unmount(child, vnode.dom));
800
+ if (vnode.dom) hostRemove(vnode.dom);
801
+ }
802
+ function patch(oldVNode, newVNode, container) {
803
+ if (oldVNode === newVNode) return;
804
+ if (!isSameVNode(oldVNode, newVNode)) {
805
+ const parent = hostParentNode(oldVNode.dom) || container;
806
+ const nextSibling = hostNextSibling(oldVNode.dom);
807
+ unmount(oldVNode, parent);
808
+ mount(newVNode, parent, nextSibling);
809
+ return;
810
+ }
811
+ if (oldVNode._effect) {
812
+ newVNode.dom = oldVNode.dom;
813
+ newVNode._effect = oldVNode._effect;
814
+ newVNode._subTree = oldVNode._subTree;
815
+ newVNode._slots = oldVNode._slots;
816
+ const props = oldVNode._componentProps;
817
+ newVNode._componentProps = props;
818
+ if (props) {
819
+ const newProps$1 = newVNode.props || {};
820
+ untrack(() => {
821
+ for (const key in newProps$1) if (key !== "children" && key !== "key" && key !== "ref") {
822
+ if (props[key] !== newProps$1[key]) props[key] = newProps$1[key];
823
+ }
824
+ for (const key in props) if (!(key in newProps$1) && key !== "children" && key !== "key" && key !== "ref") delete props[key];
825
+ });
826
+ }
827
+ const slotsRef = oldVNode._slots;
828
+ const newChildren = newVNode.props?.children;
829
+ const newSlotsFromProps = newVNode.props?.slots;
830
+ if (slotsRef) {
831
+ if (newChildren !== void 0) slotsRef._children = newChildren;
832
+ if (newSlotsFromProps !== void 0) slotsRef._slotsFromProps = newSlotsFromProps;
833
+ if (!isPatching) {
834
+ isPatching = true;
835
+ try {
836
+ untrack(() => {
837
+ slotsRef._version.v++;
838
+ });
839
+ } finally {
840
+ isPatching = false;
841
+ }
842
+ }
843
+ }
844
+ return;
845
+ }
846
+ if (newVNode.type === Text) {
847
+ newVNode.dom = oldVNode.dom;
848
+ if (oldVNode.text !== newVNode.text) hostSetText(newVNode.dom, String(newVNode.text));
849
+ return;
850
+ }
851
+ if (newVNode.type === Fragment) {
852
+ patchChildren(oldVNode, newVNode, container);
853
+ return;
854
+ }
855
+ const element = newVNode.dom = oldVNode.dom;
856
+ const oldProps = oldVNode.props || {};
857
+ const newProps = newVNode.props || {};
858
+ for (const key in oldProps) if (!(key in newProps) && key !== "children" && key !== "key" && key !== "ref") hostPatchProp(element, key, oldProps[key], null);
859
+ for (const key in newProps) {
860
+ const oldValue = oldProps[key];
861
+ const newValue = newProps[key];
862
+ if (key !== "children" && key !== "key" && key !== "ref" && oldValue !== newValue) hostPatchProp(element, key, oldValue, newValue);
863
+ }
864
+ patchChildren(oldVNode, newVNode, element);
865
+ }
866
+ function patchChildren(oldVNode, newVNode, container) {
867
+ const oldChildren = oldVNode.children;
868
+ const newChildren = newVNode.children;
869
+ newChildren.forEach((c) => c.parent = newVNode);
870
+ reconcileChildrenArray(container, oldChildren, newChildren);
871
+ }
872
+ function reconcileChildrenArray(parent, oldChildren, newChildren) {
873
+ let oldStartIdx = 0;
874
+ let oldEndIdx = oldChildren.length - 1;
875
+ let oldStartVNode = oldChildren[0];
876
+ let oldEndVNode = oldChildren[oldEndIdx];
877
+ let newStartIdx = 0;
878
+ let newEndIdx = newChildren.length - 1;
879
+ let newStartVNode = newChildren[0];
880
+ let newEndVNode = newChildren[newEndIdx];
881
+ let oldKeyToIdx;
882
+ while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) if (oldStartVNode == null) oldStartVNode = oldChildren[++oldStartIdx];
883
+ else if (oldEndVNode == null) oldEndVNode = oldChildren[--oldEndIdx];
884
+ else if (isSameVNode(oldStartVNode, newStartVNode)) {
885
+ patch(oldStartVNode, newStartVNode, parent);
886
+ oldStartVNode = oldChildren[++oldStartIdx];
887
+ newStartVNode = newChildren[++newStartIdx];
888
+ } else if (isSameVNode(oldEndVNode, newEndVNode)) {
889
+ patch(oldEndVNode, newEndVNode, parent);
890
+ oldEndVNode = oldChildren[--oldEndIdx];
891
+ newEndVNode = newChildren[--newEndIdx];
892
+ } else if (isSameVNode(oldStartVNode, newEndVNode)) {
893
+ patch(oldStartVNode, newEndVNode, parent);
894
+ const nodeToMove = oldStartVNode.dom;
895
+ const anchor = hostNextSibling(oldEndVNode.dom);
896
+ if (nodeToMove) hostInsert(nodeToMove, parent, anchor);
897
+ oldStartVNode = oldChildren[++oldStartIdx];
898
+ newEndVNode = newChildren[--newEndIdx];
899
+ } else if (isSameVNode(oldEndVNode, newStartVNode)) {
900
+ patch(oldEndVNode, newStartVNode, parent);
901
+ const nodeToMove = oldEndVNode.dom;
902
+ const anchor = oldStartVNode.dom;
903
+ if (nodeToMove) hostInsert(nodeToMove, parent, anchor);
904
+ oldEndVNode = oldChildren[--oldEndIdx];
905
+ newStartVNode = newChildren[++newStartIdx];
906
+ } else {
907
+ if (!oldKeyToIdx) oldKeyToIdx = createKeyToKeyIndexMap(oldChildren, oldStartIdx, oldEndIdx);
908
+ const idxInOld = newStartVNode.key != null ? oldKeyToIdx.get(String(newStartVNode.key)) : findIndexInOld(oldChildren, newStartVNode, oldStartIdx, oldEndIdx);
909
+ if (idxInOld != null) {
910
+ const vnodeToMove = oldChildren[idxInOld];
911
+ patch(vnodeToMove, newStartVNode, parent);
912
+ oldChildren[idxInOld] = void 0;
913
+ if (vnodeToMove.dom && oldStartVNode.dom) hostInsert(vnodeToMove.dom, parent, oldStartVNode.dom);
914
+ } else mount(newStartVNode, parent, oldStartVNode.dom);
915
+ newStartVNode = newChildren[++newStartIdx];
916
+ }
917
+ if (oldStartIdx > oldEndIdx) {
918
+ if (newStartIdx <= newEndIdx) {
919
+ const anchor = newChildren[newEndIdx + 1] == null ? null : newChildren[newEndIdx + 1].dom;
920
+ for (let i = newStartIdx; i <= newEndIdx; i++) mount(newChildren[i], parent, anchor);
921
+ }
922
+ } else if (newStartIdx > newEndIdx) {
923
+ for (let i = oldStartIdx; i <= oldEndIdx; i++) if (oldChildren[i]) unmount(oldChildren[i], parent);
924
+ }
925
+ }
926
+ function isSameVNode(n1, n2) {
927
+ const k1 = n1.key == null ? null : n1.key;
928
+ const k2 = n2.key == null ? null : n2.key;
929
+ if (n1.type !== n2.type) return false;
930
+ if (k1 === k2) return true;
931
+ return String(k1) === String(k2);
932
+ }
933
+ function createKeyToKeyIndexMap(children, beginIdx, endIdx) {
934
+ const map = /* @__PURE__ */ new Map();
935
+ for (let i = beginIdx; i <= endIdx; i++) {
936
+ const key = children[i]?.key;
937
+ if (key != null) map.set(String(key), i);
938
+ }
939
+ return map;
940
+ }
941
+ function findIndexInOld(children, newChild, beginIdx, endIdx) {
942
+ for (let i = beginIdx; i <= endIdx; i++) if (children[i] && isSameVNode(children[i], newChild)) return i;
943
+ return null;
944
+ }
945
+ function mountComponent(vnode, container, before, setup) {
946
+ const anchor = hostCreateComment("");
947
+ vnode.dom = anchor;
948
+ anchor.__vnode = vnode;
949
+ hostInsert(anchor, container, before);
950
+ let exposed = null;
951
+ let exposeCalled = false;
952
+ const { children, slots: slotsFromProps, ...propsData } = vnode.props || {};
953
+ const reactiveProps = signal$1(propsData);
954
+ vnode._componentProps = reactiveProps;
955
+ const slots = createSlots(children, slotsFromProps);
956
+ vnode._slots = slots;
957
+ const mountHooks = [];
958
+ const cleanupHooks = [];
959
+ const parentInstance = getCurrentInstance();
960
+ const componentName = vnode.type.__name;
961
+ const ctx = {
962
+ el: container,
963
+ signal: signal$1,
964
+ props: reactiveProps,
965
+ slots,
966
+ emit: (event, ...args) => {
967
+ const handler = reactiveProps[`on${event[0].toUpperCase() + event.slice(1)}`];
968
+ if (handler && typeof handler === "function") handler(...args);
969
+ },
970
+ parent: parentInstance,
971
+ onMount: (fn) => {
972
+ mountHooks.push(fn);
973
+ },
974
+ onCleanup: (fn) => {
975
+ cleanupHooks.push(fn);
976
+ },
977
+ expose: (exposedValue) => {
978
+ exposed = exposedValue;
979
+ exposeCalled = true;
980
+ }
981
+ };
982
+ ctx.__name = componentName;
983
+ if (currentAppContext) ctx._appContext = currentAppContext;
984
+ const componentInstance = {
985
+ name: componentName,
986
+ ctx,
987
+ vnode
988
+ };
989
+ const prev = setCurrentInstance(ctx);
990
+ let renderFn;
991
+ try {
992
+ renderFn = setup(ctx);
993
+ notifyComponentCreated(currentAppContext, componentInstance);
994
+ } catch (err) {
995
+ if (!handleComponentError(currentAppContext, err, componentInstance, "setup")) throw err;
996
+ } finally {
997
+ setCurrentInstance(prev);
998
+ }
999
+ if (vnode.props.ref) {
1000
+ const refValue = exposeCalled ? exposed : null;
1001
+ if (typeof vnode.props.ref === "function") vnode.props.ref(refValue);
1002
+ else if (vnode.props.ref && typeof vnode.props.ref === "object") vnode.props.ref.current = refValue;
1003
+ }
1004
+ if (renderFn) vnode._effect = effect(() => {
1005
+ const prevInstance = setCurrentInstance(ctx);
1006
+ try {
1007
+ const subTreeResult = renderFn();
1008
+ if (subTreeResult == null) return;
1009
+ const subTree = normalizeSubTree(subTreeResult);
1010
+ const prevSubTree = vnode._subTree;
1011
+ if (prevSubTree) {
1012
+ patch(prevSubTree, subTree, container);
1013
+ notifyComponentUpdated(currentAppContext, componentInstance);
1014
+ } else mount(subTree, container, anchor);
1015
+ vnode._subTree = subTree;
1016
+ } catch (err) {
1017
+ if (!handleComponentError(currentAppContext, err, componentInstance, "render")) throw err;
1018
+ } finally {
1019
+ setCurrentInstance(prevInstance);
1020
+ }
1021
+ });
1022
+ const mountCtx = { el: container };
1023
+ mountHooks.forEach((hook) => hook(mountCtx));
1024
+ notifyComponentMounted(currentAppContext, componentInstance);
1025
+ vnode.cleanup = () => {
1026
+ notifyComponentUnmounted(currentAppContext, componentInstance);
1027
+ cleanupHooks.forEach((hook) => hook(mountCtx));
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Create slots object from children and slots prop.
1032
+ * Uses a version signal to trigger re-renders when children change.
1033
+ * Supports named slots via:
1034
+ * - `slots` prop object (e.g., slots={{ header: () => <div>...</div> }})
1035
+ * - `slot` prop on children (e.g., <div slot="header">...</div>)
1036
+ */
1037
+ function createSlots(children, slotsFromProps) {
1038
+ const versionSignal = signal$1({ v: 0 });
1039
+ function extractNamedSlotsFromChildren(c) {
1040
+ const defaultChildren = [];
1041
+ const namedSlots = {};
1042
+ if (c == null) return {
1043
+ defaultChildren,
1044
+ namedSlots
1045
+ };
1046
+ const items = Array.isArray(c) ? c : [c];
1047
+ for (const child of items) if (child && typeof child === "object" && child.props && child.props.slot) {
1048
+ const slotName = child.props.slot;
1049
+ if (!namedSlots[slotName]) namedSlots[slotName] = [];
1050
+ namedSlots[slotName].push(child);
1051
+ } else defaultChildren.push(child);
1052
+ return {
1053
+ defaultChildren,
1054
+ namedSlots
1055
+ };
1056
+ }
1057
+ const slotsObj = {
1058
+ _children: children,
1059
+ _slotsFromProps: slotsFromProps || {},
1060
+ _version: versionSignal,
1061
+ default: function() {
1062
+ this._version.v;
1063
+ const c = this._children;
1064
+ const { defaultChildren } = extractNamedSlotsFromChildren(c);
1065
+ return defaultChildren;
1066
+ }
1067
+ };
1068
+ return new Proxy(slotsObj, { get(target, prop) {
1069
+ if (prop in target) return target[prop];
1070
+ if (typeof prop === "string") return function(scopedProps) {
1071
+ target._version.v;
1072
+ if (target._slotsFromProps && typeof target._slotsFromProps[prop] === "function") {
1073
+ const result = target._slotsFromProps[prop](scopedProps);
1074
+ if (result == null) return [];
1075
+ return Array.isArray(result) ? result : [result];
1076
+ }
1077
+ const { namedSlots } = extractNamedSlotsFromChildren(target._children);
1078
+ return namedSlots[prop] || [];
1079
+ };
1080
+ } });
1081
+ }
1082
+ /**
1083
+ * Normalize render result to a VNode (wrapping arrays in Fragment)
1084
+ */
1085
+ function normalizeSubTree(result) {
1086
+ if (Array.isArray(result)) return {
1087
+ type: Fragment,
1088
+ props: {},
1089
+ key: null,
1090
+ children: result,
1091
+ dom: null
1092
+ };
1093
+ if (typeof result === "string" || typeof result === "number") return {
1094
+ type: Text,
1095
+ props: {},
1096
+ key: null,
1097
+ children: [],
1098
+ dom: null,
1099
+ text: result
1100
+ };
1101
+ return result;
1102
+ }
1103
+ return {
1104
+ render,
1105
+ createApp: (rootComponent) => {
1106
+ return { mount(selectorOrContainer) {
1107
+ let container = null;
1108
+ if (typeof selectorOrContainer === "string") {
1109
+ if (options.querySelector) container = options.querySelector(selectorOrContainer);
1110
+ } else container = selectorOrContainer;
1111
+ if (!container) {
1112
+ console.warn(`Container not found: ${selectorOrContainer}`);
1113
+ return;
1114
+ }
1115
+ render(rootComponent, container);
1116
+ } };
1117
+ }
1118
+ };
1119
+ }
1120
+
1121
+ //#endregion
1122
+ export { AppContextKey, Fragment, InstanceLifetimes, SubscriptionHandler, Text, Utils, createPropsProxy, createRenderer, createTopic, defineApp, defineComponent, defineFactory, defineInjectable, defineProvide, defineStore, getComponentMeta, getComponentPlugins, getCurrentInstance, getDefaultMount, getPlatformSyncProcessor, guid, handleComponentError, inject, injectApp, jsx, jsxDEV, jsxs, notifyComponentCreated, notifyComponentMounted, notifyComponentUnmounted, notifyComponentUpdated, onCleanup, onMount, provide, registerComponentPlugin, setCurrentInstance, setDefaultMount, setPlatformSyncProcessor, signal, toSubscriber, valueOf };
1123
+ //# sourceMappingURL=index.js.map