@mulanjs/mulanjs 1.0.1-dev.20260227135307 → 1.0.1-dev.20260227172006

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/compiler/ast-parser.d.ts +48 -0
  2. package/dist/compiler/ast-parser.js +54 -9
  3. package/dist/compiler/compiler.d.ts +9 -0
  4. package/dist/compiler/compiler.js +45 -2
  5. package/dist/compiler/dom-compiler.d.ts +7 -0
  6. package/dist/compiler/dom-compiler.js +90 -33
  7. package/dist/compiler/script-compiler.d.ts +11 -0
  8. package/dist/compiler/script-compiler.js +108 -116
  9. package/dist/compiler/sfc-parser.d.ts +21 -0
  10. package/dist/compiler/ssr-compiler.d.ts +7 -0
  11. package/dist/compiler/ssr-compiler.js +142 -0
  12. package/dist/compiler/style-compiler.d.ts +8 -0
  13. package/dist/compiler/template-compiler.d.ts +8 -0
  14. package/dist/components/bloch-sphere.js +9 -3
  15. package/dist/components/infinity-list.js +7 -1
  16. package/dist/core/component.js +66 -15
  17. package/dist/core/hooks.js +53 -29
  18. package/dist/core/quantum.js +30 -17
  19. package/dist/core/query.js +11 -6
  20. package/dist/core/reactive.js +88 -7
  21. package/dist/core/renderer.js +9 -8
  22. package/dist/core/ssr.js +50 -0
  23. package/dist/core/surge.js +7 -2
  24. package/dist/core/vault.js +9 -5
  25. package/dist/index.js +63 -27
  26. package/dist/mulan.esm.js +1933 -1626
  27. package/dist/mulan.esm.js.map +1 -1
  28. package/dist/mulan.js +1890 -1590
  29. package/dist/mulan.js.map +1 -1
  30. package/dist/router/index.js +17 -10
  31. package/dist/security/sanitizer.js +5 -1
  32. package/dist/store/index.js +9 -5
  33. package/dist/types/ast-parser.d.ts +2 -0
  34. package/dist/types/compiler/ast-parser.d.ts +2 -0
  35. package/dist/types/compiler/compiler.d.ts +1 -0
  36. package/dist/types/compiler/ssr-compiler.d.ts +7 -0
  37. package/dist/types/compiler.d.ts +1 -0
  38. package/dist/types/components/bloch-sphere.d.ts +3 -1
  39. package/dist/types/components/infinity-list.d.ts +3 -1
  40. package/dist/types/core/component.d.ts +14 -0
  41. package/dist/types/core/reactive.d.ts +5 -1
  42. package/dist/types/core/renderer.d.ts +0 -1
  43. package/dist/types/core/ssr.d.ts +9 -0
  44. package/dist/types/index.d.ts +1 -0
  45. package/dist/types/ssr-compiler.d.ts +7 -0
  46. package/package.json +1 -1
  47. package/src/compiler/ast-parser.ts +62 -10
  48. package/src/compiler/compiler.ts +46 -1
  49. package/src/compiler/dom-compiler.ts +100 -34
  50. package/src/compiler/script-compiler.ts +117 -126
  51. package/src/compiler/ssr-compiler.ts +157 -0
  52. package/src/loader/index.js +12 -19
package/dist/mulan.js CHANGED
@@ -10,427 +10,507 @@
10
10
  })(this, () => {
11
11
  return /******/ (() => { // webpackBootstrap
12
12
  /******/ "use strict";
13
- /******/ // The require scope
14
- /******/ var __webpack_require__ = {};
15
- /******/
16
- /************************************************************************/
17
- /******/ /* webpack/runtime/define property getters */
18
- /******/ (() => {
19
- /******/ // define getter functions for harmony exports
20
- /******/ __webpack_require__.d = (exports, definition) => {
21
- /******/ for(var key in definition) {
22
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
23
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
24
- /******/ }
25
- /******/ }
26
- /******/ };
27
- /******/ })();
28
- /******/
29
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
30
- /******/ (() => {
31
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
32
- /******/ })();
33
- /******/
34
- /******/ /* webpack/runtime/make namespace object */
35
- /******/ (() => {
36
- /******/ // define __esModule on exports
37
- /******/ __webpack_require__.r = (exports) => {
38
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
39
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
40
- /******/ }
41
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
42
- /******/ };
43
- /******/ })();
44
- /******/
45
- /************************************************************************/
46
- var __webpack_exports__ = {};
47
-
48
- // EXPORTS
49
- __webpack_require__.d(__webpack_exports__, {
50
- "default": () => (/* binding */ src)
51
- });
52
-
53
- // UNUSED EXPORTS: Component, MuBlochSphereElement, MuComponent, MuInfinity, MuRouter, MuStore, Router, Security, Signal, activeControls, defineComponent, effect, getCurrentInstance, hydrate, muBurst, muControl, muDebounced, muEffect, muEntangle, muGate, muGeom, muHistory, muMeasure, muMemo, muParallel, muPulse, muQubit, muRegister, muSearch, muState, muSurge, muSuspense, muSwitch, muTeleport, muThrottled, muVault, onMuDestroy, onMuIdle, onMuInit, onMuMount, onMuPanic, onMuResume, onMuShake, onMuVisibility, onMuVoice, persistent, reactive, ref, render, renderToString, sanitize, setCurrentInstance, useMutation, useQuery
54
-
55
- // NAMESPACE OBJECT: ./src/core/hooks.ts
56
- var hooks_namespaceObject = {};
57
- __webpack_require__.r(hooks_namespaceObject);
58
- __webpack_require__.d(hooks_namespaceObject, {
59
- getCurrentInstance: () => (getCurrentInstance),
60
- muDebounced: () => (muDebounced),
61
- muEffect: () => (muEffect),
62
- muGeom: () => (muGeom),
63
- muHistory: () => (muHistory),
64
- muMemo: () => (muMemo),
65
- muPulse: () => (muPulse),
66
- muState: () => (muState),
67
- muSuspense: () => (muSuspense),
68
- muThrottled: () => (muThrottled),
69
- muVault: () => (muVault),
70
- onMuDestroy: () => (onMuDestroy),
71
- onMuIdle: () => (onMuIdle),
72
- onMuInit: () => (onMuInit),
73
- onMuMount: () => (onMuMount),
74
- onMuPanic: () => (onMuPanic),
75
- onMuResume: () => (onMuResume),
76
- onMuShake: () => (onMuShake),
77
- onMuVisibility: () => (onMuVisibility),
78
- onMuVoice: () => (onMuVoice),
79
- setCurrentInstance: () => (setCurrentInstance)
80
- });
81
-
82
- // NAMESPACE OBJECT: ./src/core/query.ts
83
- var query_namespaceObject = {};
84
- __webpack_require__.r(query_namespaceObject);
85
- __webpack_require__.d(query_namespaceObject, {
86
- useMutation: () => (useMutation),
87
- useQuery: () => (useQuery)
88
- });
89
-
90
- // NAMESPACE OBJECT: ./src/core/quantum.ts
91
- var quantum_namespaceObject = {};
92
- __webpack_require__.r(quantum_namespaceObject);
93
- __webpack_require__.d(quantum_namespaceObject, {
94
- activeControls: () => (activeControls),
95
- muControl: () => (muControl),
96
- muEntangle: () => (muEntangle),
97
- muGate: () => (muGate),
98
- muMeasure: () => (muMeasure),
99
- muParallel: () => (muParallel),
100
- muQubit: () => (muQubit),
101
- muRegister: () => (muRegister),
102
- muSearch: () => (muSearch),
103
- muSwitch: () => (muSwitch),
104
- muTeleport: () => (muTeleport)
105
- });
13
+ /******/ var __webpack_modules__ = ({
106
14
 
107
- // NAMESPACE OBJECT: ./src/components/infinity-list.ts
108
- var infinity_list_namespaceObject = {};
109
- __webpack_require__.r(infinity_list_namespaceObject);
110
- __webpack_require__.d(infinity_list_namespaceObject, {
111
- MuInfinity: () => (MuInfinity)
112
- });
15
+ /***/ 37
16
+ (__unused_webpack_module, exports, __webpack_require__) {
113
17
 
114
- // NAMESPACE OBJECT: ./src/core/surge.ts
115
- var surge_namespaceObject = {};
116
- __webpack_require__.r(surge_namespaceObject);
117
- __webpack_require__.d(surge_namespaceObject, {
118
- muBurst: () => (muBurst),
119
- muSurge: () => (muSurge)
120
- });
121
18
 
122
- ;// ./src/core/reactive.ts
123
- // MulanJS 2.0: Signal-Powered Reactivity Engine
124
- // "Compatible Surface, World-Class Engine"
125
- let activeEffect = null;
126
- let activeEffectRunner = null;
127
- const targetMap = new WeakMap();
128
- // --- Signal Core (The Engine) ---
129
- class Signal {
130
- constructor(initialValue) {
131
- this._subscribers = new Set();
132
- this._value = initialValue;
133
- }
134
- get value() {
135
- if (activeEffectRunner) {
136
- this._subscribers.add(activeEffectRunner.run);
19
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
20
+ exports.defineComponent = exports.MuComponent = void 0;
21
+ const renderer_1 = __webpack_require__(619);
22
+ const hooks_1 = __webpack_require__(166);
23
+ const reactive_1 = __webpack_require__(359);
24
+ // Or a simple component that returns an object of state/methods used by template?
25
+ // For Mulan 2.0, let's say functional component returns a template string render function explicitly.
26
+ class MuComponent {
27
+ constructor(container) {
28
+ this._hooks = {};
29
+ this._effects = [];
30
+ this._domEffects = [];
31
+ this._isDestroyed = false;
32
+ this._isResuming = false; // Quantum Resumability Flag
33
+ this._resumeRoot = null;
34
+ this._propsQueue = [];
35
+ this._eventQueue = [];
36
+ // --- MulanJS List Reconciliation Engine (No-VDOM) ---
37
+ // Cache to store generated DOM rows by mu-key
38
+ this._listCaches = new Map();
39
+ // --- MulanJS Conditional Engine (No-VDOM) ---
40
+ // Cache to store conditionally toggled blocks
41
+ this._ifCaches = new Map();
42
+ this.container = container;
43
+ this.state = {};
44
+ this.$uid = 'mu_' + Math.random().toString(36).substr(2, 9);
45
+ // MULAN INSIGHT: Quantum Resumability Detection
46
+ if (typeof window !== 'undefined' && container) {
47
+ const rootAttr = container.getAttribute('data-mu-root');
48
+ const stateScript = container.querySelector('script[type="mulan/state"]');
49
+ if (rootAttr || stateScript) {
50
+ console.log(`%c[Mulan Quantum]%c Resuming component from server state...`, "color: #00ffcc; font-weight: bold;", "");
51
+ this._isResuming = true;
52
+ this.$uid = rootAttr || this.$uid;
53
+ if (stateScript) {
54
+ try {
55
+ const serverState = JSON.parse(stateScript.textContent || '{}');
56
+ // Inject server state into this instance
57
+ Object.assign(this, serverState);
58
+ }
59
+ catch (e) {
60
+ console.error("[Mulan Quantum] Failed to parse server state:", e);
61
+ }
62
+ }
63
+ }
137
64
  }
138
- return this._value;
139
- }
140
- set value(newValue) {
141
- if (newValue !== this._value) {
142
- this._value = newValue;
143
- this.notify();
65
+ // MULAN INSIGHT: Global Registry for Debugging
66
+ if (typeof window !== 'undefined') {
67
+ const global = window;
68
+ global.__MULAN_INSIGHT__ = global.__MULAN_INSIGHT__ || { components: new Map() };
69
+ global.__MULAN_INSIGHT__.components.set(this.$uid, this);
144
70
  }
71
+ // Setup context for hooks
72
+ (0, hooks_1.setCurrentInstance)(this);
73
+ this.setup();
74
+ (0, hooks_1.setCurrentInstance)(null);
145
75
  }
146
- notify() {
147
- this._subscribers.forEach(fn => fn());
76
+ // Optional setup method for class components wanting to use hooks
77
+ setup() { }
78
+ onMount() {
79
+ var _a, _c;
80
+ // Mulan Cycle: Init
81
+ (_a = this._hooks.onMuInit) === null || _a === void 0 ? void 0 : _a.forEach(fn => fn());
82
+ // Mulan Cycle: Mount (Simulated immediately after init for now in this version)
83
+ (_c = this._hooks.onMuMount) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
148
84
  }
149
- }
150
- // --- Compatibility Layer (The Surface) ---
151
- function effect(fn, targetNode) {
152
- let stopped = false;
153
- const run = () => {
154
- if (stopped)
85
+ onUpdate() { }
86
+ onDestroy() {
87
+ var _a, _c;
88
+ if (this._isDestroyed)
155
89
  return;
156
- const prevRunner = activeEffectRunner;
157
- activeEffectRunner = { run, node: targetNode };
158
- try {
159
- fn();
160
- }
161
- finally {
162
- activeEffectRunner = prevRunner;
90
+ this._isDestroyed = true;
91
+ console.log(`[Mulan Cycle] Destroying component ${this.$uid} (${this.constructor.name})`);
92
+ // MULAN INSIGHT: Cleanup
93
+ if (typeof window !== 'undefined') {
94
+ const global = window;
95
+ (_a = global.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components.delete(this.$uid);
163
96
  }
164
- };
165
- run();
166
- return () => {
167
- stopped = true;
168
- };
169
- }
170
- function track(target, key) {
171
- if (activeEffectRunner) {
172
- let depsMap = targetMap.get(target);
173
- if (!depsMap) {
174
- targetMap.set(target, (depsMap = new Map()));
97
+ // Mulan Cycle: Stop all effects to prevent leaks
98
+ console.log(`[Mulan Cycle] Stopping ${this._effects.length} effects for ${this.$uid}`);
99
+ this._effects.forEach(stop => stop());
100
+ this._effects = [];
101
+ console.log(`[Mulan Cycle] Stopping ${this._domEffects.length} DOM effects for ${this.$uid}`);
102
+ this._domEffects.forEach(stop => stop());
103
+ this._domEffects = [];
104
+ // Mulan Cycle: Destroy hooks
105
+ (_c = this._hooks.onMuDestroy) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
106
+ }
107
+ // Helper for compiler to register property bindings
108
+ _b(id, prop, value) {
109
+ this._propsQueue.push([id, prop, value]);
110
+ return "";
111
+ }
112
+ // Helper for compiler to register event bindings
113
+ _e(id, type, handler) {
114
+ this._eventQueue.push([id, type, handler]);
115
+ return "";
116
+ }
117
+ // Manual binding helper for template literals
118
+ bind(handler, type = 'click') {
119
+ const id = 'ev_' + Math.random().toString(36).substr(2, 9);
120
+ this._e(id, type, handler);
121
+ return `data-mu-id="${id}"`;
122
+ }
123
+ mount() {
124
+ console.log(`[Mulan Cycle] Mounting component ${this.$uid}`);
125
+ if (this._isResuming) {
126
+ // Quantum Resumability: Skip initial render, just attach effects to existing DOM
127
+ console.log(`[Mulan Quantum] Skipping initial render, recovering DOM nodes...`);
128
+ this._resume();
175
129
  }
176
- let dep = depsMap.get(key);
177
- if (!dep) {
178
- depsMap.set(key, (dep = new Set()));
130
+ else {
131
+ // Standard Hydration/Mount
132
+ const stop = (0, reactive_1.effect)(() => {
133
+ console.log(`[Mulan Reactivity] Triggering macro-update for ${this.$uid}`);
134
+ this.update();
135
+ });
136
+ this._effects.push(stop);
179
137
  }
180
- dep.add(activeEffectRunner.run);
138
+ this.onMount();
181
139
  }
182
- }
183
- function trigger(target, key) {
184
- const depsMap = targetMap.get(target);
185
- if (!depsMap)
186
- return;
187
- const dep = depsMap.get(key);
188
- if (dep) {
189
- dep.forEach((fn) => fn());
140
+ /**
141
+ * Internal method to execute the resumability pass.
142
+ * Overridden by compiler-generated code.
143
+ */
144
+ _resume() {
145
+ // Clear queues
146
+ this._propsQueue = [];
147
+ this._eventQueue = [];
148
+ // Call the template with resumption context
149
+ // In a real implementation, the compiler will inject 'recovery' instructions
150
+ this._recoveryMode = true;
151
+ this.template();
152
+ this._recoveryMode = false;
153
+ // Flush bindings (events/props) to existing nodes
154
+ this.flushProps();
155
+ this.flushEvents();
190
156
  }
191
- }
192
- /**
193
- * Creates a reactive proxy object (Vue-compatible).
194
- * Now optimized to respect Mulan Cycle.
195
- */
196
- function reactive(target) {
197
- return new Proxy(target, {
198
- get(obj, prop, receiver) {
199
- // IRON FORTRESS: Prototype Pollution Protection (Read)
200
- if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
201
- return undefined;
202
- }
203
- track(obj, prop);
204
- const val = Reflect.get(obj, prop, receiver);
205
- if (val !== null && typeof val === 'object') {
206
- return reactive(val);
207
- }
208
- return val;
209
- },
210
- set(obj, prop, value, receiver) {
211
- // IRON FORTRESS: Prototype Pollution Protection
212
- if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
213
- console.warn(`[Iron Fortress] Blocked attempt to modify dangerous property: ${String(prop)}`);
214
- return false;
215
- }
216
- const result = Reflect.set(obj, prop, value, receiver);
217
- trigger(obj, prop);
218
- return result;
219
- },
220
- });
221
- }
222
- /**
223
- * Creates a standalone reactive reference.
224
- * Backed by the Mulan Signal Engine.
225
- */
226
- function ref(value) {
227
- return new Signal(value);
228
- }
229
-
230
- ;// ./src/core/renderer.ts
231
- function render(template, container) {
232
- // Focus Preservation (The "Mulan Glance" Technique)
233
- let focusedId = null;
234
- let selectionStart = null;
235
- let selectionEnd = null;
236
- let preservedValue = null;
237
- if (document.activeElement && container.contains(document.activeElement)) {
238
- const el = document.activeElement;
239
- if (el.hasAttribute('data-mu-id')) {
240
- focusedId = el.getAttribute('data-mu-id');
241
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
242
- selectionStart = el.selectionStart;
243
- selectionEnd = el.selectionEnd;
244
- preservedValue = el.value;
245
- }
157
+ // New helper for the compiler to register a fine-grained DOM property effect
158
+ _bindEffect(fn, targetNode) {
159
+ const stop = (0, reactive_1.effect)(fn, targetNode);
160
+ this._domEffects.push(stop);
161
+ return stop;
162
+ }
163
+ update() {
164
+ if (this._isDestroyed) {
165
+ console.warn(`[Mulan Warning] Update called on destroyed component ${this.$uid}. Blocking render.`);
166
+ return;
246
167
  }
168
+ // Clear queues before render
169
+ this._propsQueue = [];
170
+ this._eventQueue = [];
171
+ const template = this.template();
172
+ // Render HTML
173
+ (0, renderer_1.render)(template, this.container);
174
+ // Flush Side Effects
175
+ this.flushProps();
176
+ this.flushEvents();
177
+ this.onUpdate();
247
178
  }
248
- // [Anima] 1. Pre-Update: Snapshot positions of animated elements
249
- const animationSnapshots = new Map();
250
- // Only query if we might have animations to save perf
251
- if (typeof template === 'string' && template.includes('mu-animate')) {
252
- const animatedEls = container.querySelectorAll('[mu-animate]');
253
- animatedEls.forEach(el => {
254
- const key = el.getAttribute('mu-key') || el.id;
255
- if (key) {
256
- animationSnapshots.set(key, el.getBoundingClientRect());
179
+ flushProps() {
180
+ for (const [id, prop, value] of this._propsQueue) {
181
+ const el = this.container.querySelector(`[data-mu-id="${id}"]`);
182
+ if (el) {
183
+ // @ts-ignore
184
+ el[prop] = value;
257
185
  }
258
- });
259
- }
260
- if (typeof template === 'string') {
261
- container.innerHTML = template;
262
- }
263
- else {
264
- container.innerHTML = '';
265
- container.appendChild(template);
186
+ }
187
+ this._propsQueue = [];
266
188
  }
267
- // Restore Focus and Value
268
- if (focusedId) {
269
- const el = container.querySelector(`[data-mu-id="${focusedId}"]`);
270
- if (el) {
271
- // Restore value first to ensure cursor positioning works correctly
272
- if (preservedValue !== null && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
273
- el.value = preservedValue;
274
- }
275
- el.focus();
276
- if ((el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && selectionStart !== null) {
277
- try {
278
- el.setSelectionRange(selectionStart, selectionEnd);
279
- }
280
- catch (e) {
281
- // input types that don't support selection (e.g. number/email) might throw
282
- }
189
+ flushEvents() {
190
+ for (const [id, type, handler] of this._eventQueue) {
191
+ const el = this.container.querySelector(`[data-mu-id="${id}"]`);
192
+ if (el) {
193
+ // Bind handler to this component instance to ensure 'this' works in methods
194
+ el.addEventListener(type, handler.bind(this));
283
195
  }
284
196
  }
197
+ this._eventQueue = [];
285
198
  }
286
- // [Anima] 2. Post-Update: FLIP (First, Last, Invert, Play)
287
- if (animationSnapshots.size > 0) {
288
- const newAnimatedEls = container.querySelectorAll('[mu-animate]');
289
- newAnimatedEls.forEach(el => {
290
- const key = el.getAttribute('mu-key') || el.id;
291
- if (key && animationSnapshots.has(key)) {
292
- const oldRect = animationSnapshots.get(key);
293
- const newRect = el.getBoundingClientRect();
294
- const dx = oldRect.left - newRect.left;
295
- const dy = oldRect.top - newRect.top;
296
- // Only animate if moved
297
- if (dx !== 0 || dy !== 0) {
298
- const htmlEl = el;
299
- // INVERT: Move it back to where it was instantly
300
- htmlEl.style.transform = `translate(${dx}px, ${dy}px)`;
301
- htmlEl.style.transition = 'none';
302
- // PLAY: Animate to zero (new position)
303
- requestAnimationFrame(() => {
304
- // Force reflow
305
- // void htmlEl.offsetWidth;
306
- htmlEl.style.transition = 'transform 500ms cubic-bezier(0.25, 0.8, 0.25, 1)';
307
- htmlEl.style.transform = '';
308
- });
199
+ /**
200
+ * Reconciles a list of bound data to an existing DOM parent segment.
201
+ * @param listId Unique ID for this specific mu-for directive Block
202
+ * @param container The DOM Element or Fragment where children are attached
203
+ * @param array The current state array
204
+ * @param keyProp The property to extract from each item to use as a unique key (e.g. 'id')
205
+ * @param renderRow A function that takes an item and returns a new { fragment, effects }
206
+ */
207
+ _reconcileList(listId, anchorToken, array, keyProp, renderRow) {
208
+ if (!this._listCaches.has(listId)) {
209
+ this._listCaches.set(listId, new Map());
210
+ }
211
+ const cache = this._listCaches.get(listId);
212
+ const newKeys = new Set();
213
+ const parent = anchorToken.parentNode;
214
+ if (!parent)
215
+ return;
216
+ // 1. Array Iteration: Match against cache or Create
217
+ // Use a DocumentFragment to batch new node insertions natively
218
+ const collectorFrag = document.createDocumentFragment();
219
+ const newOrderNodes = [];
220
+ const newOrderKeys = [];
221
+ let requiresSwap = false;
222
+ let lastCachedIndex = -1;
223
+ for (let i = 0; i < array.length; i++) {
224
+ const item = array[i];
225
+ const key = keyProp ? item[keyProp] : i; // fallback to index if no key
226
+ newKeys.add(key);
227
+ newOrderKeys.push(key);
228
+ let cached = cache.get(key);
229
+ if (!cached) {
230
+ // Not in cache, Render a brand new row structure
231
+ const { fragment, effects } = renderRow(item, i);
232
+ // Track actual DOM nodes
233
+ const createdNodes = Array.from(fragment.childNodes);
234
+ cached = { nodes: createdNodes, effects, index: i }; // Store index for fast swap detection
235
+ cache.set(key, cached);
236
+ // Batch append to our in-memory fragment!
237
+ // This eliminates thousands of live DOM reflows on creation.
238
+ collectorFrag.appendChild(fragment);
239
+ newOrderNodes.push(...createdNodes);
240
+ }
241
+ else {
242
+ // Exists in cache
243
+ // Batch append to the in-memory array for index tracking
244
+ newOrderNodes.push(...cached.nodes);
245
+ // Fast-Path Swap Detection: If the cached index is physically out of numerical sequence,
246
+ // we know the array order was unsynchronized and needs reconciliation.
247
+ if (cached.index < lastCachedIndex) {
248
+ requiresSwap = true;
309
249
  }
250
+ cached.index = i;
251
+ lastCachedIndex = i;
310
252
  }
311
- });
312
- }
313
- }
314
- function hydrate(template, container) {
315
- // In a string-based framework, hydration is often just "take over".
316
- // For now, we'll verify if the server content matches (simple check)
317
- // and then assume control. In a more advanced version, we'd attach listeners without re-rendering.
318
- if (typeof template === 'string') {
319
- if (container.innerHTML.trim() !== template.trim()) {
320
- console.warn('Hydration Mismatch: Server rendered content differs from Client.');
321
- container.innerHTML = template; // Fallback to full render
322
253
  }
323
- else {
324
- // console.log('Hydration Successful.');
254
+ // 2. Fragment Batch Insertion (O(1) Live DOM Reflow for Creations)
255
+ if (collectorFrag.childNodes.length > 0) {
256
+ parent.insertBefore(collectorFrag, anchorToken.nextSibling);
325
257
  }
326
- }
327
- else {
328
- container.innerHTML = '';
329
- container.appendChild(template);
330
- }
331
- // Future: Attach event listeners here if we had a mechanism for it.
332
- }
333
- function renderToString(template) {
334
- // SSR Function: returns the HTML string for the server to send.
335
- // Can include additional sanitization or metadata injection here.
336
- return template;
337
- }
338
- function sanitize(str) {
339
- // Check if we are in a browser environment
340
- if (typeof document !== 'undefined') {
341
- const temp = document.createElement('div');
342
- temp.textContent = str;
343
- return temp.innerHTML;
344
- }
345
- // Simple SSR fallback sanitizer (rudimentary)
346
- return str.replace(/&/g, "&amp;")
347
- .replace(/</g, "&lt;")
348
- .replace(/>/g, "&gt;")
349
- .replace(/"/g, "&quot;")
350
- .replace(/'/g, "&#039;");
351
- }
352
-
353
- ;// ./src/core/vault.ts
354
-
355
-
356
- /**
357
- * Mulan Vault: The World's First Native Persistent State Primitive.
358
- */
359
- function persistent(key, initialValue, options = {}) {
360
- const storage = options.storage || window.localStorage;
361
- // 1. Load from Storage
362
- const stored = storage.getItem(key);
363
- let startVal = initialValue;
364
- if (stored) {
365
- try {
366
- startVal = JSON.parse(stored);
258
+ // 3. Bidirectional Swap Sync (O(K) isolated shifts instead of O(N) cascades)
259
+ if (requiresSwap) {
260
+ let currentSibling = anchorToken.nextSibling;
261
+ // We iterate through our guaranteed physical newOrderNodes list
262
+ for (let j = 0; j < newOrderNodes.length; j++) {
263
+ const targetNode = newOrderNodes[j];
264
+ if (targetNode !== currentSibling) {
265
+ // The physical live DOM is out of sync. Move targetNode to where it belongs immediately.
266
+ parent.insertBefore(targetNode, currentSibling);
267
+ }
268
+ else {
269
+ // Node is correctly positioned, simply advance the sliding logical pointer
270
+ currentSibling = currentSibling.nextSibling;
271
+ }
272
+ }
367
273
  }
368
- catch (e) {
369
- console.warn(`[Mulan Vault] Corrupt persistent data for key "${key}", resetting.`);
274
+ // 4. Cleanup Phase: Rapidly detach unmounted nodes
275
+ if (cache.size > newKeys.size) {
276
+ for (const [key, cached] of cache.entries()) {
277
+ if (!newKeys.has(key)) {
278
+ // Remove from DOM
279
+ cached.nodes.forEach((node) => {
280
+ if (node.parentNode === parent) {
281
+ parent.removeChild(node);
282
+ }
283
+ });
284
+ // Stop any targeted effects tied to these nodes
285
+ cached.effects.forEach((stop) => stop());
286
+ // Delete from cache tracking
287
+ cache.delete(key);
288
+ }
289
+ }
370
290
  }
371
291
  }
372
- // 2. Create Reactive State (Follow muState pattern for consistency)
373
- const isObject = typeof startVal === 'object' && startVal !== null;
374
- const state = isObject ? reactive(startVal) : reactive({ value: startVal });
375
- // 3. Auto-Save on Change
376
- muEffect(() => {
377
- try {
378
- const payload = isObject ? state : state.value;
379
- const toSave = JSON.stringify(payload);
380
- // Non-obfuscated persistence to satisfy security audits
381
- storage.setItem(key, toSave);
382
- }
383
- catch (e) {
384
- console.error(`[Mulan Vault] Failed to save key "${key}"`);
292
+ /**
293
+ * Reconciles a conditional block (mu-if) to an existing DOM parent segment.
294
+ */
295
+ _reconcileIf(ifId, anchorToken, condition, renderBlock) {
296
+ if (!this._ifCaches.has(ifId)) {
297
+ this._ifCaches.set(ifId, { isMounted: false, nodes: [], effects: [] });
385
298
  }
386
- });
387
- // 4. Sync across Tabs
388
- const sync = (e) => {
389
- if (e.key === key && e.newValue) {
390
- try {
391
- const newVal = JSON.parse(e.newValue);
392
- if (isObject) {
393
- Object.assign(state, newVal);
299
+ let cached = this._ifCaches.get(ifId);
300
+ if (condition) {
301
+ // Should be mounted
302
+ if (!cached.isMounted) {
303
+ // We need to render and mount it
304
+ let nodesToMount;
305
+ if (cached.nodes.length === 0) {
306
+ // First time render
307
+ const { fragment, effects } = renderBlock();
308
+ nodesToMount = Array.from(fragment.childNodes);
309
+ cached.nodes = nodesToMount;
310
+ cached.effects = effects;
394
311
  }
395
312
  else {
396
- state.value = newVal;
313
+ // Re-mounting previously cached nodes
314
+ nodesToMount = cached.nodes;
397
315
  }
316
+ cached.isMounted = true;
317
+ const parent = anchorToken.parentNode;
318
+ if (!parent)
319
+ return;
320
+ const targetSibling = anchorToken.nextSibling;
321
+ nodesToMount.forEach(node => {
322
+ parent.insertBefore(node, targetSibling);
323
+ });
324
+ }
325
+ }
326
+ else {
327
+ // Should NOT be mounted
328
+ if (cached.isMounted) {
329
+ // Unmount nodes but keep them in cache
330
+ cached.nodes.forEach(node => {
331
+ if (node.parentNode) {
332
+ node.parentNode.removeChild(node);
333
+ }
334
+ });
335
+ cached.isMounted = false;
336
+ // Note: We deliberately do NOT destroy the effects here, they stay active in memory!
398
337
  }
399
- catch (e) { }
400
338
  }
401
- };
402
- window.addEventListener('storage', sync);
403
- // Explicit cleanup if provided by the environment (e.g. Mulan Hooks)
404
- if (options.onCleanup) {
405
- options.onCleanup(() => {
406
- window.removeEventListener('storage', sync);
407
- });
408
339
  }
409
- return state;
410
340
  }
411
-
412
- ;// ./src/core/hooks.ts
413
-
414
-
341
+ exports.MuComponent = MuComponent;
342
+ // Helper to create functional components wrapped in the class system
343
+ // Helper to create functional components wrapped in the class system
344
+ // Supports both () => render and { setup() } signatures
345
+ function defineComponent(optionsOrSetup) {
346
+ return class UniversalComponent extends MuComponent {
347
+ constructor(container) {
348
+ super(container);
349
+ // setup() is called by super constructor
350
+ }
351
+ setup() {
352
+ let setupResult;
353
+ if (typeof optionsOrSetup === 'function') {
354
+ // It's a setup function returning render fn
355
+ setupResult = optionsOrSetup.call(this);
356
+ }
357
+ else if (typeof optionsOrSetup === 'object' && optionsOrSetup.setup) {
358
+ // It's an options object with setup()
359
+ setupResult = optionsOrSetup.setup.call(this);
360
+ }
361
+ // Handle result
362
+ if (typeof setupResult === 'function') {
363
+ // It's a render function
364
+ this.template = setupResult;
365
+ }
366
+ else if (setupResult && typeof setupResult === 'object') {
367
+ // It's bindings
368
+ Object.assign(this, setupResult);
369
+ // We assume template is assigned to prototype by compiler
370
+ }
371
+ }
372
+ template() {
373
+ return '';
374
+ }
375
+ };
376
+ }
377
+ exports.defineComponent = defineComponent;
378
+
379
+
380
+ /***/ },
381
+
382
+ /***/ 156
383
+ (__unused_webpack_module, exports, __webpack_require__) {
384
+
385
+
386
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
387
+ if (k2 === undefined) k2 = k;
388
+ var desc = Object.getOwnPropertyDescriptor(m, k);
389
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
390
+ desc = { enumerable: true, get: function() { return m[k]; } };
391
+ }
392
+ Object.defineProperty(o, k2, desc);
393
+ }) : (function(o, m, k, k2) {
394
+ if (k2 === undefined) k2 = k;
395
+ o[k2] = m[k];
396
+ }));
397
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
398
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
399
+ }) : function(o, v) {
400
+ o["default"] = v;
401
+ });
402
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
403
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
404
+ };
405
+ var __importStar = (this && this.__importStar) || function (mod) {
406
+ if (mod && mod.__esModule) return mod;
407
+ var result = {};
408
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
409
+ __setModuleDefault(result, mod);
410
+ return result;
411
+ };
412
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
413
+ exports.MuStore = exports.Router = exports.MuRouter = exports.defineComponent = exports.Component = exports.MuComponent = void 0;
414
+ __exportStar(__webpack_require__(359), exports);
415
+ var component_1 = __webpack_require__(37);
416
+ Object.defineProperty(exports, "MuComponent", ({ enumerable: true, get: function () { return component_1.MuComponent; } }));
417
+ Object.defineProperty(exports, "Component", ({ enumerable: true, get: function () { return component_1.MuComponent; } }));
418
+ Object.defineProperty(exports, "defineComponent", ({ enumerable: true, get: function () { return component_1.defineComponent; } }));
419
+ __exportStar(__webpack_require__(619), exports);
420
+ var index_1 = __webpack_require__(580);
421
+ Object.defineProperty(exports, "MuRouter", ({ enumerable: true, get: function () { return index_1.MuRouter; } }));
422
+ Object.defineProperty(exports, "Router", ({ enumerable: true, get: function () { return index_1.MuRouter; } }));
423
+ var index_2 = __webpack_require__(482);
424
+ Object.defineProperty(exports, "MuStore", ({ enumerable: true, get: function () { return index_2.MuStore; } }));
425
+ __exportStar(__webpack_require__(500), exports);
426
+ __exportStar(__webpack_require__(166), exports);
427
+ __exportStar(__webpack_require__(598), exports);
428
+ __exportStar(__webpack_require__(234), exports);
429
+ __exportStar(__webpack_require__(679), exports);
430
+ __exportStar(__webpack_require__(172), exports);
431
+ __exportStar(__webpack_require__(615), exports);
432
+ __exportStar(__webpack_require__(382), exports);
433
+ __exportStar(__webpack_require__(678), exports);
434
+ // Global Mulan Object for non-module usage
435
+ const reactive_1 = __webpack_require__(359);
436
+ const component_2 = __webpack_require__(37);
437
+ const index_3 = __webpack_require__(580);
438
+ const index_4 = __webpack_require__(482);
439
+ const sanitizer_1 = __webpack_require__(500);
440
+ const Hooks = __importStar(__webpack_require__(166));
441
+ const Query = __importStar(__webpack_require__(598));
442
+ const renderer_1 = __webpack_require__(619);
443
+ const Quantum = __importStar(__webpack_require__(679));
444
+ const Surge = __importStar(__webpack_require__(172));
445
+ const InfinityList = __importStar(__webpack_require__(382));
446
+ const Mulan = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ reactive: reactive_1.reactive,
447
+ effect: reactive_1.effect, Component: component_2.MuComponent, defineComponent: component_2.defineComponent, Router: index_3.MuRouter, createRouter: index_3.createRouter, Store: index_4.MuStore, Security: sanitizer_1.Security }, Hooks), Query), Quantum), Surge), InfinityList), { render: renderer_1.render,
448
+ // MULAN INSIGHT: Branded Logging
449
+ log: (msg, ...args) => {
450
+ console.log(`%c[MulanJS]%c ${msg}`, "color: #ff3e00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
451
+ }, warn: (msg, ...args) => {
452
+ console.warn(`%c[MulanJS]%c ${msg}`, "color: #ffcc00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
453
+ }, error: (msg, ...args) => {
454
+ console.error(`%c[MulanJS]%c ${msg}`, "color: #ff0000; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
455
+ } });
456
+ // Security: Freeze the object to prevent runtime tampering
457
+ Object.freeze(Mulan);
458
+ Object.freeze(Mulan.Security);
459
+ // MULAN INSIGHT: Initialize Global Registry
460
+ if (typeof window !== 'undefined') {
461
+ window.__MULAN_INSIGHT__ = window.__MULAN_INSIGHT__ || { components: new Map() };
462
+ // MULAN INSIGHT: HMR Support
463
+ window.__MULAN_REFRESH__ = () => {
464
+ var _a;
465
+ const components = (_a = window.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components;
466
+ if (components) {
467
+ components.forEach((comp) => {
468
+ if (comp && typeof comp.update === 'function') {
469
+ // Force refresh
470
+ comp.update();
471
+ }
472
+ });
473
+ }
474
+ };
475
+ }
476
+ if (typeof window !== 'undefined') {
477
+ window.Mulan = Mulan;
478
+ }
479
+ exports["default"] = Mulan;
480
+
481
+
482
+ /***/ },
483
+
484
+ /***/ 166
485
+ (__unused_webpack_module, exports, __webpack_require__) {
486
+
487
+
488
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
489
+ exports.muHistory = exports.onMuPanic = exports.muThrottled = exports.muDebounced = exports.onMuVisibility = exports.muSuspense = exports.muVault = exports.muPulse = exports.muGeom = exports.onMuVoice = exports.onMuShake = exports.onMuResume = exports.onMuIdle = exports.onMuDestroy = exports.onMuMount = exports.onMuInit = exports.muEffect = exports.muMemo = exports.muState = exports.getCurrentInstance = exports.setCurrentInstance = void 0;
490
+ const reactive_1 = __webpack_require__(359);
491
+ const vault_1 = __webpack_require__(234);
415
492
  // Global context to track the current component instance
416
493
  let currentInstance = null;
417
494
  function setCurrentInstance(instance) {
418
495
  currentInstance = instance;
419
496
  }
497
+ exports.setCurrentInstance = setCurrentInstance;
420
498
  function getCurrentInstance() {
421
499
  return currentInstance;
422
500
  }
501
+ exports.getCurrentInstance = getCurrentInstance;
423
502
  // --- Mulan Unique Reactivity Hooks ---
424
503
  function muState(initialValue) {
425
504
  if (typeof initialValue === 'object' && initialValue !== null) {
426
- return reactive(initialValue);
505
+ return (0, reactive_1.reactive)(initialValue);
427
506
  }
428
507
  // Core reactive state container for primitives
429
- return reactive({ value: initialValue });
508
+ return (0, reactive_1.reactive)({ value: initialValue });
430
509
  }
510
+ exports.muState = muState;
431
511
  function muMemo(computeFn) {
432
- const signal = reactive({ value: undefined });
433
- const stop = effect(() => {
512
+ const signal = (0, reactive_1.reactive)({ value: undefined });
513
+ const stop = (0, reactive_1.effect)(() => {
434
514
  signal.value = computeFn();
435
515
  });
436
516
  const instance = getCurrentInstance();
@@ -441,8 +521,9 @@ function muMemo(computeFn) {
441
521
  }
442
522
  return signal;
443
523
  }
524
+ exports.muMemo = muMemo;
444
525
  function muEffect(fn) {
445
- const stop = effect(fn);
526
+ const stop = (0, reactive_1.effect)(fn);
446
527
  const instance = getCurrentInstance();
447
528
  if (instance) {
448
529
  if (!instance._effects)
@@ -450,6 +531,7 @@ function muEffect(fn) {
450
531
  instance._effects.push(stop);
451
532
  }
452
533
  }
534
+ exports.muEffect = muEffect;
453
535
  // --- The "Mulan Cycle" (Lifecycle) ---
454
536
  function onMuInit(fn) {
455
537
  const instance = getCurrentInstance();
@@ -464,6 +546,7 @@ function onMuInit(fn) {
464
546
  console.warn('onMuInit called outside of component setup context.');
465
547
  }
466
548
  }
549
+ exports.onMuInit = onMuInit;
467
550
  function onMuMount(fn) {
468
551
  // New hook for when component is actually in DOM (simulated for now via update)
469
552
  const instance = getCurrentInstance();
@@ -475,6 +558,7 @@ function onMuMount(fn) {
475
558
  instance._hooks.onMuMount.push(fn);
476
559
  }
477
560
  }
561
+ exports.onMuMount = onMuMount;
478
562
  function onMuDestroy(fn) {
479
563
  const instance = getCurrentInstance();
480
564
  if (instance) {
@@ -485,6 +569,7 @@ function onMuDestroy(fn) {
485
569
  instance._hooks.onMuDestroy.push(fn);
486
570
  }
487
571
  }
572
+ exports.onMuDestroy = onMuDestroy;
488
573
  /**
489
574
  * onMuIdle - The "Environment Life" Hook.
490
575
  * Executes heavy logic ONLY when the browser is taking a nap (idle).
@@ -513,6 +598,7 @@ function onMuIdle(fn) {
513
598
  });
514
599
  }
515
600
  }
601
+ exports.onMuIdle = onMuIdle;
516
602
  /**
517
603
  * onMuResume - The "Tab Life" Hook.
518
604
  * Executes when the user switches BACK to this tab.
@@ -527,6 +613,7 @@ function onMuResume(fn) {
527
613
  document.addEventListener('visibilitychange', handler);
528
614
  onMuDestroy(() => document.removeEventListener('visibilitychange', handler));
529
615
  }
616
+ exports.onMuResume = onMuResume;
530
617
  /**
531
618
  * onMuShake - The "Physical Life" Hook.
532
619
  * Executes when the device is shaken.
@@ -565,6 +652,7 @@ function onMuShake(fn) {
565
652
  console.warn("[MulanJS] Device Motion not supported on this device.");
566
653
  }
567
654
  }
655
+ exports.onMuShake = onMuShake;
568
656
  /**
569
657
  * onMuVoice - The "Sound Life" Hook.
570
658
  * Executes when a specific word is spoken.
@@ -600,6 +688,7 @@ function onMuVoice(command, fn) {
600
688
  recognition.stop();
601
689
  });
602
690
  }
691
+ exports.onMuVoice = onMuVoice;
603
692
  // --- "Outside The Box" Hooks (Mulan Exclusives) ---
604
693
  /**
605
694
  * muGeom - Tracks window or element dimensions reactively.
@@ -617,6 +706,7 @@ function muGeom() {
617
706
  });
618
707
  return dims;
619
708
  }
709
+ exports.muGeom = muGeom;
620
710
  /**
621
711
  * muPulse - Reactive network status.
622
712
  */
@@ -632,13 +722,15 @@ function muPulse() {
632
722
  });
633
723
  return status;
634
724
  }
725
+ exports.muPulse = muPulse;
635
726
  /**
636
727
  * muVault - Secure reactive LocalStorage wrapper.
637
728
  * Powered by the Iron Fortress persistent primitive.
638
729
  */
639
730
  function muVault(key, initial, options = {}) {
640
- return persistent(key, initial, Object.assign(Object.assign({}, options), { onCleanup: (fn) => onMuDestroy(fn) }));
731
+ return (0, vault_1.persistent)(key, initial, Object.assign(Object.assign({}, options), { onCleanup: (fn) => onMuDestroy(fn) }));
641
732
  }
733
+ exports.muVault = muVault;
642
734
  // --- Next-Gen MulanJS Hooks ---
643
735
  /**
644
736
  * muSuspense - The Asynchronous Barrier.
@@ -662,6 +754,7 @@ function muSuspense(promiseFn) {
662
754
  });
663
755
  return state;
664
756
  }
757
+ exports.muSuspense = muSuspense;
665
758
  /**
666
759
  * onMuVisibility - The Intersection Observer Hook.
667
760
  * Triggers when the component enters/leaves the viewport.
@@ -683,6 +776,7 @@ function onMuVisibility(callback, options = { threshold: 0.1 }) {
683
776
  });
684
777
  });
685
778
  }
779
+ exports.onMuVisibility = onMuVisibility;
686
780
  /**
687
781
  * muDebounced - High-performance debouncing built directly into a reactive signal.
688
782
  */
@@ -701,6 +795,7 @@ function muDebounced(initialValue, delayMs) {
701
795
  }
702
796
  };
703
797
  }
798
+ exports.muDebounced = muDebounced;
704
799
  /**
705
800
  * muThrottled - High-performance throttling built directly into a reactive signal.
706
801
  */
@@ -720,6 +815,7 @@ function muThrottled(initialValue, delayMs) {
720
815
  }
721
816
  };
722
817
  }
818
+ exports.muThrottled = muThrottled;
723
819
  /**
724
820
  * onMuPanic - The Iron Fortress Error Boundary.
725
821
  * Catches unhandled exceptions within the component scope.
@@ -743,6 +839,7 @@ function onMuPanic(fallbackFn) {
743
839
  window.removeEventListener('unhandledrejection', handler);
744
840
  });
745
841
  }
842
+ exports.onMuPanic = onMuPanic;
746
843
  /**
747
844
  * muHistory - State with built-in Undo/Redo tracking.
748
845
  */
@@ -781,638 +878,502 @@ function muHistory(initialValue) {
781
878
  get future() { return historyTracker.log.slice(pointer.value + 1); }
782
879
  };
783
880
  }
881
+ exports.muHistory = muHistory;
784
882
 
785
- ;// ./src/core/component.ts
786
883
 
884
+ /***/ },
787
885
 
886
+ /***/ 172
887
+ (__unused_webpack_module, exports) {
788
888
 
789
- // Or a simple component that returns an object of state/methods used by template?
790
- // For Mulan 2.0, let's say functional component returns a template string render function explicitly.
791
- class MuComponent {
792
- constructor(container) {
793
- this._hooks = {};
794
- this._effects = [];
795
- this._domEffects = [];
796
- this._isDestroyed = false;
797
- this._propsQueue = [];
798
- this._eventQueue = [];
799
- // --- MulanJS List Reconciliation Engine (No-VDOM) ---
800
- // Cache to store generated DOM rows by mu-key
801
- this._listCaches = new Map();
802
- // --- MulanJS Conditional Engine (No-VDOM) ---
803
- // Cache to store conditionally toggled blocks
804
- this._ifCaches = new Map();
805
- this.container = container;
806
- this.state = {};
807
- this.$uid = 'mu_' + Math.random().toString(36).substr(2, 9);
808
- // MULAN INSIGHT: Global Registry for Debugging
809
- if (typeof window !== 'undefined') {
810
- const global = window;
811
- global.__MULAN_INSIGHT__ = global.__MULAN_INSIGHT__ || { components: new Map() };
812
- global.__MULAN_INSIGHT__.components.set(this.$uid, this);
813
- }
814
- // Setup context for hooks
815
- setCurrentInstance(this);
816
- this.setup();
817
- setCurrentInstance(null);
818
- }
819
- // Optional setup method for class components wanting to use hooks
820
- setup() { }
821
- onMount() {
822
- var _a, _c;
823
- // Mulan Cycle: Init
824
- (_a = this._hooks.onMuInit) === null || _a === void 0 ? void 0 : _a.forEach(fn => fn());
825
- // Mulan Cycle: Mount (Simulated immediately after init for now in this version)
826
- (_c = this._hooks.onMuMount) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
827
- }
828
- onUpdate() { }
829
- onDestroy() {
830
- var _a, _c;
831
- if (this._isDestroyed)
832
- return;
833
- this._isDestroyed = true;
834
- console.log(`[Mulan Cycle] Destroying component ${this.$uid} (${this.constructor.name})`);
835
- // MULAN INSIGHT: Cleanup
836
- if (typeof window !== 'undefined') {
837
- const global = window;
838
- (_a = global.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components.delete(this.$uid);
839
- }
840
- // Mulan Cycle: Stop all effects to prevent leaks
841
- console.log(`[Mulan Cycle] Stopping ${this._effects.length} effects for ${this.$uid}`);
842
- this._effects.forEach(stop => stop());
843
- this._effects = [];
844
- console.log(`[Mulan Cycle] Stopping ${this._domEffects.length} DOM effects for ${this.$uid}`);
845
- this._domEffects.forEach(stop => stop());
846
- this._domEffects = [];
847
- // Mulan Cycle: Destroy hooks
848
- (_c = this._hooks.onMuDestroy) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
849
- }
850
- // Helper for compiler to register property bindings
851
- _b(id, prop, value) {
852
- this._propsQueue.push([id, prop, value]);
853
- return "";
854
- }
855
- // Helper for compiler to register event bindings
856
- _e(id, type, handler) {
857
- this._eventQueue.push([id, type, handler]);
858
- return "";
859
- }
860
- // Manual binding helper for template literals
861
- bind(handler, type = 'click') {
862
- const id = 'ev_' + Math.random().toString(36).substr(2, 9);
863
- this._e(id, type, handler);
864
- return `data-mu-id="${id}"`;
865
- }
866
- mount() {
867
- console.log(`[Mulan Cycle] Mounting component ${this.$uid}`);
868
- // The main render effect (legacy strings fallback / macro structure)
869
- const stop = effect(() => {
870
- console.log(`[Mulan Reactivity] Triggering macro-update for ${this.$uid}`);
871
- this.update();
872
- });
873
- this._effects.push(stop);
874
- this.onMount();
875
- }
876
- // New helper for the compiler to register a fine-grained DOM property effect
877
- _bindEffect(fn, targetNode) {
878
- const stop = effect(fn, targetNode);
879
- this._domEffects.push(stop);
880
- return stop;
881
- }
882
- update() {
883
- if (this._isDestroyed) {
884
- console.warn(`[Mulan Warning] Update called on destroyed component ${this.$uid}. Blocking render.`);
885
- return;
886
- }
887
- // Clear queues before render
888
- this._propsQueue = [];
889
- this._eventQueue = [];
890
- const template = this.template();
891
- // Render HTML
892
- render(template, this.container);
893
- // Flush Side Effects
894
- this.flushProps();
895
- this.flushEvents();
896
- this.onUpdate();
897
- }
898
- flushProps() {
899
- for (const [id, prop, value] of this._propsQueue) {
900
- const el = this.container.querySelector(`[data-mu-id="${id}"]`);
901
- if (el) {
902
- // @ts-ignore
903
- el[prop] = value;
889
+
890
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
891
+ exports.muSurge = exports.muBurst = void 0;
892
+ /**
893
+ * muBurst - Adaptive Non-blocking Iterator
894
+ * Processes large arrays in batches within a frame budget (typically 8-16ms)
895
+ * to keep the UI responsive while executing at near-native loop speeds.
896
+ */
897
+ function muBurst(array, callback, options = {}) {
898
+ const { chunkSize = 1000, timeout = 8, onProgress } = options;
899
+ return new Promise((resolve) => {
900
+ let index = 0;
901
+ const total = array.length;
902
+ function process() {
903
+ const start = performance.now();
904
+ // Tight loop for high-speed processing
905
+ while (index < total && (performance.now() - start) < timeout) {
906
+ // Process in smaller bursts to allow more frequent time checks if needed
907
+ const endBurst = Math.min(index + chunkSize, total);
908
+ for (; index < endBurst; index++) {
909
+ callback(array[index], index);
910
+ }
904
911
  }
905
- }
906
- this._propsQueue = [];
907
- }
908
- flushEvents() {
909
- for (const [id, type, handler] of this._eventQueue) {
910
- const el = this.container.querySelector(`[data-mu-id="${id}"]`);
911
- if (el) {
912
- // Bind handler to this component instance to ensure 'this' works in methods
913
- el.addEventListener(type, handler.bind(this));
912
+ if (onProgress) {
913
+ onProgress((index / total) * 100);
914
+ }
915
+ if (index < total) {
916
+ requestAnimationFrame(process);
917
+ }
918
+ else {
919
+ resolve();
914
920
  }
915
921
  }
916
- this._eventQueue = [];
917
- }
918
- /**
919
- * Reconciles a list of bound data to an existing DOM parent segment.
920
- * @param listId Unique ID for this specific mu-for directive Block
921
- * @param container The DOM Element or Fragment where children are attached
922
- * @param array The current state array
923
- * @param keyProp The property to extract from each item to use as a unique key (e.g. 'id')
924
- * @param renderRow A function that takes an item and returns a new { fragment, effects }
925
- */
926
- _reconcileList(listId, anchorToken, array, keyProp, renderRow) {
927
- if (!this._listCaches.has(listId)) {
928
- this._listCaches.set(listId, new Map());
929
- }
930
- const cache = this._listCaches.get(listId);
931
- const newKeys = new Set();
932
- const parent = anchorToken.parentNode;
933
- if (!parent)
934
- return;
935
- // 1. Array Iteration: Match against cache or Create
936
- // Use a DocumentFragment to batch new node insertions natively
937
- const collectorFrag = document.createDocumentFragment();
938
- const newOrderNodes = [];
939
- const newOrderKeys = [];
940
- let requiresSwap = false;
941
- let lastCachedIndex = -1;
942
- for (let i = 0; i < array.length; i++) {
943
- const item = array[i];
944
- const key = keyProp ? item[keyProp] : i; // fallback to index if no key
945
- newKeys.add(key);
946
- newOrderKeys.push(key);
947
- let cached = cache.get(key);
948
- if (!cached) {
949
- // Not in cache, Render a brand new row structure
950
- const { fragment, effects } = renderRow(item, i);
951
- // Track actual DOM nodes
952
- const createdNodes = Array.from(fragment.childNodes);
953
- cached = { nodes: createdNodes, effects, index: i }; // Store index for fast swap detection
954
- cache.set(key, cached);
955
- // Batch append to our in-memory fragment!
956
- // This eliminates thousands of live DOM reflows on creation.
957
- collectorFrag.appendChild(fragment);
958
- newOrderNodes.push(...createdNodes);
959
- }
960
- else {
961
- // Exists in cache
962
- // Batch append to the in-memory array for index tracking
963
- newOrderNodes.push(...cached.nodes);
964
- // Fast-Path Swap Detection: If the cached index is physically out of numerical sequence,
965
- // we know the array order was unsynchronized and needs reconciliation.
966
- if (cached.index < lastCachedIndex) {
967
- requiresSwap = true;
968
- }
969
- cached.index = i;
970
- lastCachedIndex = i;
922
+ process();
923
+ });
924
+ }
925
+ exports.muBurst = muBurst;
926
+ /**
927
+ * muSurge - Truly Parallel Execution
928
+ * Distributes work across CPU cores using Web Workers.
929
+ * Logic must be serializable.
930
+ */
931
+ function muSurge(array, taskFn, onProgress) {
932
+ const n = navigator.hardwareConcurrency || 4;
933
+ const chunkSize = Math.ceil(array.length / n);
934
+ const results = new Array(array.length);
935
+ let completedChunks = 0;
936
+ let completedItems = 0;
937
+ // Convert function to string if it isn't already
938
+ const fnStr = typeof taskFn === 'function' ? taskFn.toString() : taskFn;
939
+ const workerPart1 = `const taskFn = ${fnStr};`;
940
+ const workerPart2 = `self.onmessage = function(e) {`;
941
+ const workerPart3 = ` const { chunk, startIndex } = e.data;`;
942
+ const workerPart4 = ` try { const results = chunk.map(taskFn); self.postMessage({ results, startIndex }); }`;
943
+ const workerPart5 = ` catch (err) { self.postMessage({ error: err.message, startIndex }); }`;
944
+ const workerPart6 = `};`;
945
+ const workerCode = [workerPart1, workerPart2, workerPart3, workerPart4, workerPart5, workerPart6].join('\n');
946
+ const blob = new Blob([workerCode], { type: 'application/javascript' });
947
+ const workerUrl = URL.createObjectURL(blob);
948
+ return new Promise((resolve) => {
949
+ if (array.length === 0)
950
+ return resolve([]);
951
+ for (let i = 0; i < n; i++) {
952
+ const start = i * chunkSize;
953
+ const end = Math.min(start + chunkSize, array.length);
954
+ if (start >= end) {
955
+ completedChunks++;
956
+ continue;
971
957
  }
972
- }
973
- // 2. Fragment Batch Insertion (O(1) Live DOM Reflow for Creations)
974
- if (collectorFrag.childNodes.length > 0) {
975
- parent.insertBefore(collectorFrag, anchorToken.nextSibling);
976
- }
977
- // 3. Bidirectional Swap Sync (O(K) isolated shifts instead of O(N) cascades)
978
- if (requiresSwap) {
979
- let currentSibling = anchorToken.nextSibling;
980
- // We iterate through our guaranteed physical newOrderNodes list
981
- for (let j = 0; j < newOrderNodes.length; j++) {
982
- const targetNode = newOrderNodes[j];
983
- if (targetNode !== currentSibling) {
984
- // The physical live DOM is out of sync. Move targetNode to where it belongs immediately.
985
- parent.insertBefore(targetNode, currentSibling);
958
+ const chunk = array.slice(start, end);
959
+ const worker = new Worker(workerUrl);
960
+ worker.onmessage = (e) => {
961
+ const { results: chunkResults, startIndex } = e.data;
962
+ // Merge results back into main array
963
+ for (let j = 0; j < chunkResults.length; j++) {
964
+ results[startIndex + j] = chunkResults[j];
986
965
  }
987
- else {
988
- // Node is correctly positioned, simply advance the sliding logical pointer
989
- currentSibling = currentSibling.nextSibling;
966
+ completedChunks++;
967
+ completedItems += chunkResults.length;
968
+ if (onProgress)
969
+ onProgress((completedItems / array.length) * 100);
970
+ worker.terminate();
971
+ if (completedChunks === n) {
972
+ URL.revokeObjectURL(workerUrl);
973
+ resolve(results);
990
974
  }
991
- }
975
+ };
976
+ worker.postMessage({ chunk, startIndex: start, fnStr });
992
977
  }
993
- // 4. Cleanup Phase: Rapidly detach unmounted nodes
994
- if (cache.size > newKeys.size) {
995
- for (const [key, cached] of cache.entries()) {
996
- if (!newKeys.has(key)) {
997
- // Remove from DOM
998
- cached.nodes.forEach((node) => {
999
- if (node.parentNode === parent) {
1000
- parent.removeChild(node);
1001
- }
1002
- });
1003
- // Stop any targeted effects tied to these nodes
1004
- cached.effects.forEach((stop) => stop());
1005
- // Delete from cache tracking
1006
- cache.delete(key);
1007
- }
1008
- }
978
+ });
979
+ }
980
+ exports.muSurge = muSurge;
981
+
982
+
983
+ /***/ },
984
+
985
+ /***/ 234
986
+ (__unused_webpack_module, exports, __webpack_require__) {
987
+
988
+
989
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
990
+ exports.persistent = void 0;
991
+ const hooks_1 = __webpack_require__(166);
992
+ const reactive_1 = __webpack_require__(359);
993
+ /**
994
+ * Mulan Vault: The World's First Native Persistent State Primitive.
995
+ */
996
+ function persistent(key, initialValue, options = {}) {
997
+ const storage = options.storage || window.localStorage;
998
+ // 1. Load from Storage
999
+ const stored = storage.getItem(key);
1000
+ let startVal = initialValue;
1001
+ if (stored) {
1002
+ try {
1003
+ startVal = JSON.parse(stored);
1004
+ }
1005
+ catch (e) {
1006
+ console.warn(`[Mulan Vault] Corrupt persistent data for key "${key}", resetting.`);
1009
1007
  }
1010
1008
  }
1011
- /**
1012
- * Reconciles a conditional block (mu-if) to an existing DOM parent segment.
1013
- */
1014
- _reconcileIf(ifId, anchorToken, condition, renderBlock) {
1015
- if (!this._ifCaches.has(ifId)) {
1016
- this._ifCaches.set(ifId, { isMounted: false, nodes: [], effects: [] });
1009
+ // 2. Create Reactive State (Follow muState pattern for consistency)
1010
+ const isObject = typeof startVal === 'object' && startVal !== null;
1011
+ const state = isObject ? (0, reactive_1.reactive)(startVal) : (0, reactive_1.reactive)({ value: startVal });
1012
+ // 3. Auto-Save on Change
1013
+ (0, hooks_1.muEffect)(() => {
1014
+ try {
1015
+ const payload = isObject ? state : state.value;
1016
+ const toSave = JSON.stringify(payload);
1017
+ // Non-obfuscated persistence to satisfy security audits
1018
+ storage.setItem(key, toSave);
1017
1019
  }
1018
- let cached = this._ifCaches.get(ifId);
1019
- if (condition) {
1020
- // Should be mounted
1021
- if (!cached.isMounted) {
1022
- // We need to render and mount it
1023
- let nodesToMount;
1024
- if (cached.nodes.length === 0) {
1025
- // First time render
1026
- const { fragment, effects } = renderBlock();
1027
- nodesToMount = Array.from(fragment.childNodes);
1028
- cached.nodes = nodesToMount;
1029
- cached.effects = effects;
1020
+ catch (e) {
1021
+ console.error(`[Mulan Vault] Failed to save key "${key}"`);
1022
+ }
1023
+ });
1024
+ // 4. Sync across Tabs
1025
+ const sync = (e) => {
1026
+ if (e.key === key && e.newValue) {
1027
+ try {
1028
+ const newVal = JSON.parse(e.newValue);
1029
+ if (isObject) {
1030
+ Object.assign(state, newVal);
1030
1031
  }
1031
1032
  else {
1032
- // Re-mounting previously cached nodes
1033
- nodesToMount = cached.nodes;
1033
+ state.value = newVal;
1034
1034
  }
1035
- cached.isMounted = true;
1036
- const parent = anchorToken.parentNode;
1037
- if (!parent)
1038
- return;
1039
- const targetSibling = anchorToken.nextSibling;
1040
- nodesToMount.forEach(node => {
1041
- parent.insertBefore(node, targetSibling);
1042
- });
1043
1035
  }
1036
+ catch (e) { }
1037
+ }
1038
+ };
1039
+ window.addEventListener('storage', sync);
1040
+ // Explicit cleanup if provided by the environment (e.g. Mulan Hooks)
1041
+ if (options.onCleanup) {
1042
+ options.onCleanup(() => {
1043
+ window.removeEventListener('storage', sync);
1044
+ });
1045
+ }
1046
+ return state;
1047
+ }
1048
+ exports.persistent = persistent;
1049
+
1050
+
1051
+ /***/ },
1052
+
1053
+ /***/ 359
1054
+ (__unused_webpack_module, exports) {
1055
+
1056
+
1057
+ // MulanJS 2.0: Signal-Powered Reactivity Engine
1058
+ // "Compatible Surface, World-Class Engine"
1059
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1060
+ exports.ref = exports.reactive = exports.effect = exports.Signal = exports.nextTick = exports.queueEffect = void 0;
1061
+ let activeEffect = null;
1062
+ let activeEffectRunner = null;
1063
+ const targetMap = new WeakMap();
1064
+ // --- Mulan Quantum Scheduler (Time-Slicing) ---
1065
+ // Assign unique IDs to effects for basic topological sorting (lower IDs run first)
1066
+ let effectIdCounter = 0;
1067
+ const pendingEffects = new Set();
1068
+ let isScheduling = false;
1069
+ const TIME_BUDGET = 8; // 8ms frame budget for 60FPS lock
1070
+ function runScheduler() {
1071
+ if (pendingEffects.size === 0) {
1072
+ isScheduling = false;
1073
+ return;
1074
+ }
1075
+ const start = typeof performance !== 'undefined' ? performance.now() : Date.now();
1076
+ // Convert to array and sort to ensure parent effects run before children (Topological Push-Pull approximation)
1077
+ const sortedEffects = Array.from(pendingEffects).sort((a, b) => {
1078
+ return (a._id || 0) - (b._id || 0);
1079
+ });
1080
+ for (const fn of sortedEffects) {
1081
+ pendingEffects.delete(fn);
1082
+ fn();
1083
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
1084
+ if (now - start > TIME_BUDGET) {
1085
+ break; // Yield to browser
1086
+ }
1087
+ }
1088
+ if (pendingEffects.size > 0) {
1089
+ if (typeof MessageChannel !== 'undefined') {
1090
+ const channel = new MessageChannel();
1091
+ channel.port1.onmessage = runScheduler;
1092
+ channel.port2.postMessage(null);
1044
1093
  }
1045
1094
  else {
1046
- // Should NOT be mounted
1047
- if (cached.isMounted) {
1048
- // Unmount nodes but keep them in cache
1049
- cached.nodes.forEach(node => {
1050
- if (node.parentNode) {
1051
- node.parentNode.removeChild(node);
1052
- }
1053
- });
1054
- cached.isMounted = false;
1055
- // Note: We deliberately do NOT destroy the effects here, they stay active in memory!
1056
- }
1095
+ setTimeout(runScheduler, 0);
1057
1096
  }
1058
1097
  }
1098
+ else {
1099
+ isScheduling = false;
1100
+ }
1059
1101
  }
1060
- // Helper to create functional components wrapped in the class system
1061
- // Helper to create functional components wrapped in the class system
1062
- // Supports both () => render and { setup() } signatures
1063
- function defineComponent(optionsOrSetup) {
1064
- return class UniversalComponent extends MuComponent {
1065
- constructor(container) {
1066
- super(container);
1067
- // setup() is called by super constructor
1068
- }
1069
- setup() {
1070
- let setupResult;
1071
- if (typeof optionsOrSetup === 'function') {
1072
- // It's a setup function returning render fn
1073
- setupResult = optionsOrSetup.call(this);
1074
- }
1075
- else if (typeof optionsOrSetup === 'object' && optionsOrSetup.setup) {
1076
- // It's an options object with setup()
1077
- setupResult = optionsOrSetup.setup.call(this);
1078
- }
1079
- // Handle result
1080
- if (typeof setupResult === 'function') {
1081
- // It's a render function
1082
- this.template = setupResult;
1083
- }
1084
- else if (setupResult && typeof setupResult === 'object') {
1085
- // It's bindings
1086
- Object.assign(this, setupResult);
1087
- // We assume template is assigned to prototype by compiler
1088
- }
1102
+ function queueEffect(fn) {
1103
+ pendingEffects.add(fn);
1104
+ if (!isScheduling) {
1105
+ isScheduling = true;
1106
+ if (typeof Promise !== 'undefined') {
1107
+ Promise.resolve().then(runScheduler);
1089
1108
  }
1090
- template() {
1091
- return '';
1109
+ else {
1110
+ setTimeout(runScheduler, 0);
1092
1111
  }
1093
- };
1112
+ }
1094
1113
  }
1095
-
1096
- ;// ./src/security/sanitizer.ts
1097
- class Security {
1098
- /**
1099
- * IRON FORTRESS PROTOCOL
1100
- * Strictly escapes all HTML entities to prevent XSS.
1101
- * Use `mu-raw` attribute in templates to bypass this for trusted content.
1102
- */
1103
- static sanitize(input) {
1104
- // 1. Basic entity encoding
1105
- let secure = input
1106
- .replace(/&/g, "&amp;")
1107
- .replace(/</g, "&lt;")
1108
- .replace(/>/g, "&gt;")
1109
- .replace(/"/g, "&quot;")
1110
- .replace(/'/g, "&#039;");
1111
- // 2. Remove dangerous events (extra layer if encoding fails)
1112
- const dangerousEvents = ['onload', 'onclick', 'onerror', 'onmouseover', 'onfocus'];
1113
- dangerousEvents.forEach(event => {
1114
- const regex = new RegExp(event, 'gi');
1115
- secure = secure.replace(regex, 'data-blocked-' + event);
1116
- });
1117
- return secure;
1114
+ exports.queueEffect = queueEffect;
1115
+ function nextTick() {
1116
+ return Promise.resolve();
1117
+ }
1118
+ exports.nextTick = nextTick;
1119
+ // --- Signal Core (The Engine) ---
1120
+ class Signal {
1121
+ constructor(initialValue) {
1122
+ this._subscribers = new Set();
1123
+ this._value = initialValue;
1118
1124
  }
1119
- /**
1120
- * Generates a strict Content Security Policy header value.
1121
- * @param options Configuration for allowed sources
1122
- */
1123
- static generateCSP(options = {}) {
1124
- const scriptSrc = ["'self'", ...(options.scriptSrc || [])].join(" ");
1125
- const styleSrc = ["'self'", "'unsafe-inline'", ...(options.styleSrc || [])].join(" ");
1126
- return `default-src 'self'; script-src ${scriptSrc}; style-src ${styleSrc}; object-src 'none'; base-uri 'self';`;
1125
+ get value() {
1126
+ if (activeEffectRunner) {
1127
+ this._subscribers.add(activeEffectRunner.run);
1128
+ }
1129
+ return this._value;
1127
1130
  }
1128
- static validateUrl(url) {
1129
- // Basic URL validation
1130
- const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
1131
- '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
1132
- '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
1133
- '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
1134
- '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
1135
- '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
1136
- return !!pattern.test(url);
1131
+ set value(newValue) {
1132
+ if (newValue !== this._value) {
1133
+ this._value = newValue;
1134
+ this.notify();
1135
+ }
1137
1136
  }
1138
- /**
1139
- * Prevents XSS by sanitizing common input fields on blur.
1140
- * Can be used as a utility in forms.
1141
- */
1142
- static preventXSS(inputElement) {
1143
- inputElement.addEventListener('blur', (e) => {
1144
- const target = e.target;
1145
- target.value = Security.sanitize(target.value);
1137
+ notify() {
1138
+ this._subscribers.forEach(fn => {
1139
+ if (fn._sync) {
1140
+ fn();
1141
+ }
1142
+ else {
1143
+ queueEffect(fn);
1144
+ }
1146
1145
  });
1147
1146
  }
1148
1147
  }
1149
-
1150
- ;// ./src/router/index.ts
1151
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1152
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1153
- return new (P || (P = Promise))(function (resolve, reject) {
1154
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1155
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1156
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1157
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1158
- });
1159
- };
1160
-
1161
-
1162
- class MuRouter {
1163
- constructor(routes, rootContainer = null) {
1164
- this.currentPath = '';
1165
- this.currentComponent = null;
1166
- this.lastRouteId = 0;
1167
- this.routes = routes;
1168
- this.rootContainer = rootContainer;
1169
- this.isServer = rootContainer === null; // If no container, assume server/headless mode
1170
- if (!this.isServer) {
1171
- window.addEventListener('hashchange', this.handleRoute.bind(this));
1172
- this.handleRoute(); // Initial load
1148
+ exports.Signal = Signal;
1149
+ // --- Compatibility Layer (The Surface) ---
1150
+ function effect(fn, targetNode, options = {}) {
1151
+ let stopped = false;
1152
+ const id = ++effectIdCounter;
1153
+ const run = () => {
1154
+ if (stopped)
1155
+ return;
1156
+ const prevRunner = activeEffectRunner;
1157
+ activeEffectRunner = { run, node: targetNode, id };
1158
+ try {
1159
+ fn();
1160
+ }
1161
+ finally {
1162
+ activeEffectRunner = prevRunner;
1163
+ }
1164
+ };
1165
+ // Attach ID for topological sorting
1166
+ run._id = id;
1167
+ run._sync = options.sync;
1168
+ run();
1169
+ return () => {
1170
+ stopped = true;
1171
+ pendingEffects.delete(run);
1172
+ };
1173
+ }
1174
+ exports.effect = effect;
1175
+ function track(target, key) {
1176
+ if (activeEffectRunner) {
1177
+ let depsMap = targetMap.get(target);
1178
+ if (!depsMap) {
1179
+ targetMap.set(target, (depsMap = new Map()));
1180
+ }
1181
+ let dep = depsMap.get(key);
1182
+ if (!dep) {
1183
+ depsMap.set(key, (dep = new Set()));
1173
1184
  }
1185
+ dep.add(activeEffectRunner.run);
1174
1186
  }
1175
- // SSR Method: Simulate a route visit on the server
1176
- serverLookup(path) {
1177
- return __awaiter(this, void 0, void 0, function* () {
1178
- this.currentPath = path;
1179
- const { route, params } = this.matchRoute(path);
1180
- if (route) {
1181
- // Run guards/resolvers here if needed
1182
- let componentToRender = route.component;
1183
- // Support Lazy Loading
1184
- if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1185
- const module = yield componentToRender();
1186
- componentToRender = module.default || module;
1187
- }
1188
- if (typeof componentToRender === 'function') {
1189
- // Class component SSR
1190
- // We need a dummy container for the component to "render" into its own buffer
1191
- // For simplicity in this string-based framework, we mock the container
1192
- const mockContainer = { innerHTML: '' };
1193
- const instance = new componentToRender(mockContainer);
1194
- if (instance.setParams)
1195
- instance.setParams(params);
1196
- // Manually trigger mount logic without DOM effects if possible, or just template()
1197
- // Ideally, we just want the template string.
1198
- return instance.template();
1199
- }
1200
- else {
1201
- return componentToRender;
1202
- }
1187
+ }
1188
+ function trigger(target, key) {
1189
+ const depsMap = targetMap.get(target);
1190
+ if (!depsMap)
1191
+ return;
1192
+ const dep = depsMap.get(key);
1193
+ if (dep) {
1194
+ dep.forEach((fn) => {
1195
+ if (fn._sync) {
1196
+ fn(); // Run synchronously if explicitly requested (e.g. for muMemo)
1197
+ }
1198
+ else {
1199
+ queueEffect(fn); // Push to Quantum Scheduler
1203
1200
  }
1204
- return '<!-- 404 -->';
1205
1201
  });
1206
1202
  }
1207
- matchRoute(hash) {
1208
- // Simple exact match first
1209
- let route = this.routes.find((r) => r.path === hash);
1210
- if (route)
1211
- return { route, params: {} };
1212
- // Regex match for params e.g. /user/:id
1213
- for (const r of this.routes) {
1214
- const paramNames = [];
1215
- const regexPath = r.path.replace(/:([^/]+)/g, (_, key) => {
1216
- paramNames.push(key);
1217
- return '([^/]+)';
1218
- });
1219
- const match = new RegExp(`^${regexPath}$`).exec(hash);
1220
- if (match) {
1221
- const params = {};
1222
- paramNames.forEach((name, i) => {
1223
- // SECURE: Automatically sanitize all route parameters
1224
- params[name] = Security.sanitize(match[i + 1]);
1225
- });
1226
- return { route: r, params };
1203
+ }
1204
+ /**
1205
+ * Creates a reactive proxy object (Vue-compatible).
1206
+ * Now optimized to respect Mulan Cycle.
1207
+ */
1208
+ function reactive(target) {
1209
+ return new Proxy(target, {
1210
+ get(obj, prop, receiver) {
1211
+ // IRON FORTRESS: Prototype Pollution Protection (Read)
1212
+ if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
1213
+ return undefined;
1227
1214
  }
1228
- }
1229
- return { route: undefined, params: {} };
1230
- }
1231
- handleRoute() {
1232
- return __awaiter(this, void 0, void 0, function* () {
1233
- if (this.isServer)
1234
- return;
1235
- const currentRouteId = ++this.lastRouteId;
1236
- const hash = window.location.hash.slice(1) || '/';
1237
- const { route, params } = this.matchRoute(hash);
1238
- // Security Check: Validate URL to prevent malicious hash injection
1239
- if (hash !== '/' && !Security.validateUrl('http://dummy.com' + hash)) {
1240
- console.error("Security Alert: Malformed URL detected.");
1241
- return;
1215
+ track(obj, prop);
1216
+ const val = Reflect.get(obj, prop, receiver);
1217
+ if (val !== null && typeof val === 'object') {
1218
+ return reactive(val);
1242
1219
  }
1243
- // Navigation Guard (Middleware)
1244
- if (route === null || route === void 0 ? void 0 : route.beforeEnter) {
1245
- yield new Promise((resolve) => {
1246
- route.beforeEnter(hash, this.currentPath, (allow) => {
1247
- if (allow)
1248
- resolve();
1249
- else {
1250
- console.warn(`Navigation to ${hash} blocked by guard.`);
1251
- // Ideally redirect or stay, here we just stop processing
1252
- throw new Error('Navigation Blocked');
1253
- }
1254
- });
1255
- }).catch(() => { return; }); // Stop execution if blocked
1220
+ return val;
1221
+ },
1222
+ set(obj, prop, value, receiver) {
1223
+ // IRON FORTRESS: Prototype Pollution Protection
1224
+ if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
1225
+ console.warn(`[Iron Fortress] Blocked attempt to modify dangerous property: ${String(prop)}`);
1226
+ return false;
1256
1227
  }
1257
- this.currentPath = hash;
1258
- if (route) {
1259
- if (route.title) {
1260
- document.title = route.title;
1261
- }
1262
- else if (route.meta && route.meta.title) {
1263
- // Fallback to meta.title if used
1264
- document.title = route.meta.title;
1265
- }
1266
- if (this.rootContainer) {
1267
- // Mulan Cycle: Destroy previous component before rendering new one
1268
- if (this.currentComponent) {
1269
- console.log(`[Router] Navigation from ${this.currentPath} to ${hash}. Destroying previous component.`);
1270
- if (this.currentComponent.onDestroy) {
1271
- this.currentComponent.onDestroy();
1272
- }
1273
- }
1274
- this.rootContainer.innerHTML = ''; // Clear previous content
1275
- }
1276
- let componentToRender = route.component;
1277
- // Support Lazy Loading
1278
- if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1279
- try {
1280
- const module = yield componentToRender();
1281
- if (currentRouteId !== this.lastRouteId) {
1282
- console.log(`[Router] Navigation to ${hash} interrupted by newer navigation. Abandoning.`);
1283
- return;
1284
- }
1285
- componentToRender = module.default || module;
1286
- }
1287
- catch (e) {
1288
- console.error("Failed to lazy load component", e);
1289
- return;
1290
- }
1291
- }
1292
- if (typeof componentToRender === 'function') {
1293
- // It's a class component
1294
- if (this.rootContainer) {
1295
- const instance = new componentToRender(this.rootContainer);
1296
- this.currentComponent = instance;
1297
- // Inject params if the component accepts them
1298
- if (instance.setParams) {
1299
- instance.setParams(params);
1300
- }
1301
- instance.mount();
1302
- }
1303
- }
1304
- else if (typeof componentToRender === 'object' && componentToRender.template) {
1305
- // Object Component (Simple SFC without script or Options API)
1306
- const html = componentToRender.template();
1307
- if (this.rootContainer)
1308
- render(html, this.rootContainer);
1309
- this.currentComponent = null;
1310
- }
1311
- else {
1312
- // Simple HTML string/template
1313
- if (this.rootContainer)
1314
- render(componentToRender, this.rootContainer);
1315
- this.currentComponent = null; // String templates don't have lifecycle instances
1316
- }
1317
- }
1318
- else {
1319
- if (this.rootContainer)
1320
- render('<div style="text-align:center; padding:50px;"><h1>404</h1><p>Page Not Found</p></div>', this.rootContainer);
1321
- }
1322
- });
1228
+ const result = Reflect.set(obj, prop, value, receiver);
1229
+ trigger(obj, prop);
1230
+ return result;
1231
+ },
1232
+ });
1233
+ }
1234
+ exports.reactive = reactive;
1235
+ /**
1236
+ * Creates a standalone reactive reference.
1237
+ * Backed by the Mulan Signal Engine.
1238
+ */
1239
+ function ref(value) {
1240
+ return new Signal(value);
1241
+ }
1242
+ exports.ref = ref;
1243
+
1244
+
1245
+ /***/ },
1246
+
1247
+ /***/ 382
1248
+ (__unused_webpack_module, exports) {
1249
+
1250
+
1251
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1252
+ exports.MuInfinity = void 0;
1253
+ const MuInfinityBase = typeof HTMLElement !== 'undefined' ? HTMLElement : class {
1254
+ };
1255
+ class MuInfinity extends MuInfinityBase {
1256
+ constructor() {
1257
+ super();
1258
+ this._items = [];
1259
+ this._itemHeight = 50; // Default height
1260
+ this._template = '';
1261
+ this.attachShadow({ mode: 'open' });
1262
+ // Structure:
1263
+ // :host { overflow-y: auto; display: block; height: 100%; }
1264
+ // .spacer { height: totalHeight; position: relative; }
1265
+ // .content { position: absolute; top: padding; width: 100%; }
1266
+ this.shadowRoot.innerHTML = `
1267
+ <style>
1268
+ :host {
1269
+ display: block;
1270
+ overflow-y: auto;
1271
+ height: 100%;
1272
+ position: relative;
1273
+ }
1274
+ .spacer {
1275
+ position: relative;
1276
+ width: 100%;
1277
+ }
1278
+ .content {
1279
+ position: absolute;
1280
+ top: 0;
1281
+ left: 0;
1282
+ width: 100%;
1283
+ }
1284
+ </style>
1285
+ <div class="spacer">
1286
+ <div class="content"></div>
1287
+ </div>
1288
+ `;
1289
+ this.container = this.shadowRoot.host; // The host itself scrolls
1290
+ this.spacer = this.shadowRoot.querySelector('.spacer');
1291
+ this.content = this.shadowRoot.querySelector('.content');
1292
+ this.onScroll = this.onScroll.bind(this);
1323
1293
  }
1324
- // [Chronos] Prefetch a route's component code in the background
1325
- prefetch(path) {
1326
- return __awaiter(this, void 0, void 0, function* () {
1327
- if (this.isServer)
1328
- return;
1329
- const { route } = this.matchRoute(path);
1330
- if (route) {
1331
- let componentToRender = route.component;
1332
- // Check if it's a lazy-loaded function that hasn't been resolved yet
1333
- if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1334
- // If it's already a resolved module (from previous prefetch), componentToRender might be the result.
1335
- // But typically in our simple implementation, route.component stays as the function until we replace it.
1336
- // To avoid double-fetching, we can check if it has a specific flag or property.
1337
- // For this implementation, we'll just run it and let the browser cache the module request (standard ES Module behavior).
1338
- try {
1339
- // console.log(`[Chronos] Prefetching ${path}...`);
1340
- yield componentToRender();
1341
- // We don't need to do anything with the result here.
1342
- // The browser's module cache will handle the speedup when the user actually navigates.
1343
- }
1344
- catch (e) {
1345
- console.warn(`[Chronos] Failed to prefetch ${path}`, e);
1346
- }
1347
- }
1348
- }
1349
- });
1294
+ static get observedAttributes() {
1295
+ return ['item-height'];
1350
1296
  }
1351
- navigate(path) {
1352
- if (this.isServer) {
1353
- this.currentPath = path;
1297
+ attributeChangedCallback(name, oldValue, newValue) {
1298
+ if (name === 'item-height') {
1299
+ this._itemHeight = parseInt(newValue, 10) || 50;
1300
+ this.renderVisible();
1354
1301
  }
1355
- else {
1356
- window.location.hash = path;
1302
+ }
1303
+ connectedCallback() {
1304
+ // Find the template provided by the user (Support both standard and branded tags)
1305
+ const templateTag = this.querySelector('template') || this.querySelector('mu-template');
1306
+ if (templateTag) {
1307
+ this._template = templateTag.innerHTML;
1357
1308
  }
1309
+ this.addEventListener('scroll', this.onScroll);
1310
+ // Wait for next frame to get initial height if not set
1311
+ requestAnimationFrame(() => this.renderVisible());
1358
1312
  }
1359
- }
1360
- // --- Factory for Easy Usage ---
1361
- const createRouter = (options) => {
1362
- // Expose the router instance globally for <mu-link> to access
1363
- const router = new MuRouter(options.routes, options.rootContainer);
1364
- if (typeof window !== 'undefined') {
1365
- window.__MULAN_ROUTER__ = router;
1313
+ disconnectedCallback() {
1314
+ this.removeEventListener('scroll', this.onScroll);
1366
1315
  }
1367
- return router;
1368
- };
1369
- // --- Web Component: <mu-link> ---
1370
- // Usage: <mu-link to="/about">About Us</mu-link>
1371
- if (typeof window !== 'undefined' && !customElements.get('mu-link')) {
1372
- class MuLink extends HTMLElement {
1373
- constructor() {
1374
- super();
1375
- this.addEventListener('click', (e) => {
1376
- e.preventDefault();
1377
- const to = this.getAttribute('to');
1378
- if (to) {
1379
- // Update Hash for SPA Navigation
1380
- window.location.hash = to;
1381
- }
1382
- });
1383
- // [Chronos] Intelligent Pre-fetching
1384
- this.addEventListener('mouseenter', () => {
1385
- const to = this.getAttribute('to');
1386
- if (to) {
1387
- const router = window.__MULAN_ROUTER__;
1388
- if (router && typeof router.prefetch === 'function') {
1389
- router.prefetch(to);
1390
- }
1391
- }
1392
- });
1393
- // [Chronos] Also prefetch on focus for keyboard users
1394
- this.addEventListener('focus', () => {
1395
- const to = this.getAttribute('to');
1396
- if (to) {
1397
- const router = window.__MULAN_ROUTER__;
1398
- if (router && typeof router.prefetch === 'function') {
1399
- router.prefetch(to);
1400
- }
1401
- }
1402
- });
1403
- }
1404
- connectedCallback() {
1405
- this.style.cursor = 'pointer';
1406
- this.style.color = 'var(--primary, #9C27B0)'; // Default to brand color if available
1407
- this.style.textDecoration = 'none';
1408
- }
1409
- static get observedAttributes() { return ['to']; }
1316
+ set items(value) {
1317
+ this._items = value;
1318
+ this.renderVisible();
1410
1319
  }
1411
- customElements.define('mu-link', MuLink);
1320
+ get items() { return this._items; }
1321
+ onScroll() {
1322
+ requestAnimationFrame(() => this.renderVisible());
1323
+ }
1324
+ renderVisible() {
1325
+ if (!this._items.length)
1326
+ return;
1327
+ const scrollTop = this.scrollTop;
1328
+ const hostHeight = this.clientHeight || 400; // Default fallback if not sized
1329
+ const totalHeight = this._items.length * this._itemHeight;
1330
+ this.spacer.style.height = `${totalHeight}px`;
1331
+ // Windowing Math
1332
+ const startIndex = Math.floor(scrollTop / this._itemHeight);
1333
+ const buffer = 5;
1334
+ const visibleCount = Math.ceil(hostHeight / this._itemHeight);
1335
+ const renderStart = Math.max(0, startIndex - buffer);
1336
+ const renderEnd = Math.min(this._items.length, startIndex + visibleCount + buffer);
1337
+ const startOffset = renderStart * this._itemHeight;
1338
+ this.content.style.transform = `translateY(${startOffset}px)`;
1339
+ // Render specific slice
1340
+ const visibleItems = this._items.slice(renderStart, renderEnd);
1341
+ // Simple string replacement template engine for the demo
1342
+ // In a real Mulan compilation, this would be an optimized ASTR render
1343
+ let html = '';
1344
+ visibleItems.forEach((item, index) => {
1345
+ const absoluteIndex = renderStart + index;
1346
+ // Basic mustache replacement {{ item.prop }}
1347
+ let rowHtml = this._template
1348
+ .replace(/{{\s*item\s*}}/g, String(item)) // {{ item }}
1349
+ .replace(/{{\s*index\s*}}/g, String(absoluteIndex)); // {{ index }}
1350
+ // Handle object properties: {{ item.name }}
1351
+ if (typeof item === 'object' && item !== null) {
1352
+ rowHtml = rowHtml.replace(/{{\s*item\.(\w+)\s*}}/g, (_, prop) => {
1353
+ return String(item[prop] || '');
1354
+ });
1355
+ }
1356
+ html += `<div style="height: ${this._itemHeight}px; overflow: hidden;">${rowHtml}</div>`;
1357
+ });
1358
+ this.content.innerHTML = html;
1359
+ }
1360
+ }
1361
+ exports.MuInfinity = MuInfinity;
1362
+ // Register
1363
+ if (typeof customElements !== 'undefined' && !customElements.get('mu-infinity')) {
1364
+ customElements.define('mu-infinity', MuInfinity);
1412
1365
  }
1413
1366
 
1414
- ;// ./src/store/index.ts
1415
1367
 
1368
+ /***/ },
1369
+
1370
+ /***/ 482
1371
+ (__unused_webpack_module, exports, __webpack_require__) {
1372
+
1373
+
1374
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1375
+ exports.MuStore = void 0;
1376
+ const reactive_1 = __webpack_require__(359);
1416
1377
  class MuStore {
1417
1378
  constructor(initialState, options) {
1418
1379
  this.subscribers = [];
@@ -1430,16 +1391,16 @@ class MuStore {
1430
1391
  console.error("Failed to load state", e);
1431
1392
  }
1432
1393
  // Auto-save effect
1433
- effect(() => {
1394
+ (0, reactive_1.effect)(() => {
1434
1395
  localStorage.setItem(key, JSON.stringify(this.state));
1435
1396
  });
1436
1397
  }
1437
- this.state = reactive(loadedState);
1398
+ this.state = (0, reactive_1.reactive)(loadedState);
1438
1399
  }
1439
1400
  // Subscribe to changes
1440
1401
  subscribe(fn) {
1441
1402
  this.subscribers.push(fn);
1442
- effect(() => {
1403
+ (0, reactive_1.effect)(() => {
1443
1404
  fn(this.state);
1444
1405
  });
1445
1406
  }
@@ -1454,436 +1415,445 @@ class MuStore {
1454
1415
  }
1455
1416
  }
1456
1417
  }
1418
+ exports.MuStore = MuStore;
1457
1419
 
1458
- ;// ./src/core/query.ts
1459
- var query_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1460
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1461
- return new (P || (P = Promise))(function (resolve, reject) {
1462
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1463
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1464
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1465
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1466
- });
1467
- };
1468
1420
 
1469
- function useQuery(queryFn, options = { enabled: true }) {
1470
- const state = reactive({
1471
- data: null,
1472
- isLoading: false,
1473
- error: null
1474
- });
1475
- const execute = () => query_awaiter(this, void 0, void 0, function* () {
1476
- state.isLoading = true;
1477
- state.error = null;
1478
- try {
1479
- const result = yield queryFn();
1480
- state.data = result;
1481
- }
1482
- catch (err) {
1483
- state.error = err;
1484
- }
1485
- finally {
1486
- state.isLoading = false;
1487
- }
1488
- });
1489
- if (options.enabled) {
1490
- // Run automatically
1491
- effect(() => {
1492
- // Basic effect wrapper to allow reactivity if queryFn relies on signals
1493
- execute();
1421
+ /***/ },
1422
+
1423
+ /***/ 500
1424
+ (__unused_webpack_module, exports) {
1425
+
1426
+
1427
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1428
+ exports.Security = void 0;
1429
+ class Security {
1430
+ /**
1431
+ * IRON FORTRESS PROTOCOL
1432
+ * Strictly escapes all HTML entities to prevent XSS.
1433
+ * Use `mu-raw` attribute in templates to bypass this for trusted content.
1434
+ */
1435
+ static sanitize(input) {
1436
+ // 1. Basic entity encoding
1437
+ let secure = input
1438
+ .replace(/&/g, "&amp;")
1439
+ .replace(/</g, "&lt;")
1440
+ .replace(/>/g, "&gt;")
1441
+ .replace(/"/g, "&quot;")
1442
+ .replace(/'/g, "&#039;");
1443
+ // 2. Remove dangerous events (extra layer if encoding fails)
1444
+ const dangerousEvents = ['onload', 'onclick', 'onerror', 'onmouseover', 'onfocus'];
1445
+ dangerousEvents.forEach(event => {
1446
+ const regex = new RegExp(event, 'gi');
1447
+ secure = secure.replace(regex, 'data-blocked-' + event);
1448
+ });
1449
+ return secure;
1450
+ }
1451
+ /**
1452
+ * Generates a strict Content Security Policy header value.
1453
+ * @param options Configuration for allowed sources
1454
+ */
1455
+ static generateCSP(options = {}) {
1456
+ const scriptSrc = ["'self'", ...(options.scriptSrc || [])].join(" ");
1457
+ const styleSrc = ["'self'", "'unsafe-inline'", ...(options.styleSrc || [])].join(" ");
1458
+ return `default-src 'self'; script-src ${scriptSrc}; style-src ${styleSrc}; object-src 'none'; base-uri 'self';`;
1459
+ }
1460
+ static validateUrl(url) {
1461
+ // Basic URL validation
1462
+ const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
1463
+ '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
1464
+ '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
1465
+ '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
1466
+ '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
1467
+ '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
1468
+ return !!pattern.test(url);
1469
+ }
1470
+ /**
1471
+ * Prevents XSS by sanitizing common input fields on blur.
1472
+ * Can be used as a utility in forms.
1473
+ */
1474
+ static preventXSS(inputElement) {
1475
+ inputElement.addEventListener('blur', (e) => {
1476
+ const target = e.target;
1477
+ target.value = Security.sanitize(target.value);
1494
1478
  });
1495
1479
  }
1496
- return {
1497
- get data() { return state.data; },
1498
- get isLoading() { return state.isLoading; },
1499
- get error() { return state.error; },
1500
- refetch: execute
1501
- };
1502
- }
1503
- function useMutation(mutationFn) {
1504
- const state = reactive({
1505
- data: null,
1506
- isLoading: false,
1507
- error: null
1508
- });
1509
- const mutate = (args) => query_awaiter(this, void 0, void 0, function* () {
1510
- state.isLoading = true;
1511
- state.error = null;
1512
- try {
1513
- const result = yield mutationFn(args);
1514
- state.data = result;
1515
- return result;
1516
- }
1517
- catch (err) {
1518
- state.error = err;
1519
- throw err;
1520
- }
1521
- finally {
1522
- state.isLoading = false;
1523
- }
1524
- });
1525
- return {
1526
- get data() { return state.data; },
1527
- get isLoading() { return state.isLoading; },
1528
- get error() { return state.error; },
1529
- mutate
1530
- };
1531
1480
  }
1481
+ exports.Security = Security;
1532
1482
 
1533
- ;// ./src/core/quantum.ts
1534
1483
 
1535
- /**
1536
- * Mulan Quantum (ASTR-Q+) Core
1537
- * Advanced Simulation Engine for multi-qubit registers and entanglement.
1538
- */
1539
- // -- GLOBAL CONTEXT FOR QUANTUM CONTROL --
1540
- // Defined at top to ensure visibility for muGate
1541
- let activeControls = [];
1542
- /**
1543
- * Creates a quantum register of size n.
1544
- * State vector will have 2^n amplitudes.
1545
- */
1546
- function muRegister(n) {
1547
- const numStates = Math.pow(2, n);
1548
- const amplitudes = new Array(numStates).fill(0).map((_, i) => ({
1549
- re: i === 0 ? 1 : 0,
1550
- im: 0
1551
- }));
1552
- return muState({
1553
- value: {
1554
- size: n,
1555
- amplitudes
1556
- }
1484
+ /***/ },
1485
+
1486
+ /***/ 580
1487
+ (__unused_webpack_module, exports, __webpack_require__) {
1488
+
1489
+
1490
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
1491
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1492
+ return new (P || (P = Promise))(function (resolve, reject) {
1493
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1494
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1495
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1496
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1557
1497
  });
1558
- }
1559
- /**
1560
- * Backward compatible muQubit (Single Qubit Register)
1561
- */
1562
- function muQubit(initial = 0) {
1563
- const q = muRegister(1);
1564
- if (initial === 1) {
1565
- muGate(q, 'X', 0);
1498
+ };
1499
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1500
+ exports.createRouter = exports.MuRouter = void 0;
1501
+ const renderer_1 = __webpack_require__(619);
1502
+ const sanitizer_1 = __webpack_require__(500);
1503
+ class MuRouter {
1504
+ constructor(routes, rootContainer = null) {
1505
+ this.currentPath = '';
1506
+ this.currentComponent = null;
1507
+ this.lastRouteId = 0;
1508
+ this.routes = routes;
1509
+ this.rootContainer = rootContainer;
1510
+ this.isServer = rootContainer === null; // If no container, assume server/headless mode
1511
+ if (!this.isServer) {
1512
+ window.addEventListener('hashchange', this.handleRoute.bind(this));
1513
+ this.handleRoute(); // Initial load
1514
+ }
1566
1515
  }
1567
- // Add compatibility properties for Phase 1 components
1568
- // These properties are getters that dynamically access the amplitudes array
1569
- Object.defineProperty(q.value, 'alpha', { get: () => q.value.amplitudes[0] });
1570
- Object.defineProperty(q.value, 'beta', { get: () => q.value.amplitudes[1] });
1571
- return q;
1572
- }
1573
- /**
1574
- * Internal helper to update register state while maintaining compatibility
1575
- */
1576
- function updateState(reg, newState) {
1577
- if (newState.size === 1) {
1578
- // Re-inject compatibility getters for muQubit users
1579
- Object.defineProperty(newState, 'alpha', {
1580
- get: () => newState.amplitudes[0],
1581
- configurable: true,
1582
- enumerable: true
1583
- });
1584
- Object.defineProperty(newState, 'beta', {
1585
- get: () => newState.amplitudes[1],
1586
- configurable: true,
1587
- enumerable: true
1516
+ // SSR Method: Simulate a route visit on the server
1517
+ serverLookup(path) {
1518
+ return __awaiter(this, void 0, void 0, function* () {
1519
+ this.currentPath = path;
1520
+ const { route, params } = this.matchRoute(path);
1521
+ if (route) {
1522
+ // Run guards/resolvers here if needed
1523
+ let componentToRender = route.component;
1524
+ // Support Lazy Loading
1525
+ if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1526
+ const module = yield componentToRender();
1527
+ componentToRender = module.default || module;
1528
+ }
1529
+ if (typeof componentToRender === 'function') {
1530
+ // Class component SSR
1531
+ // We need a dummy container for the component to "render" into its own buffer
1532
+ // For simplicity in this string-based framework, we mock the container
1533
+ const mockContainer = { innerHTML: '' };
1534
+ const instance = new componentToRender(mockContainer);
1535
+ if (instance.setParams)
1536
+ instance.setParams(params);
1537
+ // Manually trigger mount logic without DOM effects if possible, or just template()
1538
+ // Ideally, we just want the template string.
1539
+ return instance.template();
1540
+ }
1541
+ else {
1542
+ return componentToRender;
1543
+ }
1544
+ }
1545
+ return '<!-- 404 -->';
1588
1546
  });
1589
1547
  }
1590
- reg.value = newState;
1591
- }
1592
- function muGate(reg, type, target = 0, control) {
1593
- const state = reg.value;
1594
- const n = state.size;
1595
- const amplitudes = state.amplitudes;
1596
- const newAmps = amplitudes.map(a => (Object.assign({}, a)));
1597
- // Prepare Effective Control (Explicit Arguments + Global Context)
1598
- const effectiveControl = [...(control === undefined ? [] : (Array.isArray(control) ? control : [control])), ...activeControls];
1599
- // Helper: Check if all control bits are 1
1600
- const checkControl = (index, ctrl) => {
1601
- if (ctrl === undefined || (Array.isArray(ctrl) && ctrl.length === 0))
1602
- return true;
1603
- const ctrls = Array.isArray(ctrl) ? ctrl : [ctrl];
1604
- return ctrls.every(c => ((index >> c) & 1) === 1);
1605
- };
1606
- // SWAP Gate (Unique case: affects 2 targets)
1607
- if (type === 'SWAP') {
1608
- const t1 = target;
1609
- const t2 = control; // SWAP uses control arg as second target
1610
- // Iterate only half to avoid double swapping
1611
- for (let i = 0; i < amplitudes.length; i++) {
1612
- // Check active controls for SWAP too
1613
- if (activeControls.length > 0 && !checkControl(i, activeControls))
1614
- continue;
1615
- const bit1 = (i >> t1) & 1;
1616
- const bit2 = (i >> t2) & 1;
1617
- if (bit1 !== bit2) {
1618
- // Determine the swap partner index
1619
- // If i has (0,1), partner has (1,0) at those positions
1620
- const partner = i ^ (1 << t1) ^ (1 << t2);
1621
- if (i < partner) {
1622
- const temp = newAmps[i];
1623
- newAmps[i] = newAmps[partner];
1624
- newAmps[partner] = temp;
1625
- }
1548
+ matchRoute(hash) {
1549
+ // Simple exact match first
1550
+ let route = this.routes.find((r) => r.path === hash);
1551
+ if (route)
1552
+ return { route, params: {} };
1553
+ // Regex match for params e.g. /user/:id
1554
+ for (const r of this.routes) {
1555
+ const paramNames = [];
1556
+ const regexPath = r.path.replace(/:([^/]+)/g, (_, key) => {
1557
+ paramNames.push(key);
1558
+ return '([^/]+)';
1559
+ });
1560
+ const match = new RegExp(`^${regexPath}$`).exec(hash);
1561
+ if (match) {
1562
+ const params = {};
1563
+ paramNames.forEach((name, i) => {
1564
+ // SECURE: Automatically sanitize all route parameters
1565
+ params[name] = sanitizer_1.Security.sanitize(match[i + 1]);
1566
+ });
1567
+ return { route: r, params };
1626
1568
  }
1627
1569
  }
1628
- updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
1629
- return;
1570
+ return { route: undefined, params: {} };
1630
1571
  }
1631
- // Standard Single-Qubit & Controlled Gates
1632
- if (type === 'H') {
1633
- const s = 1 / Math.sqrt(2);
1634
- const processed = new Set();
1635
- for (let i = 0; i < state.amplitudes.length; i++) {
1636
- if (processed.has(i))
1637
- continue;
1638
- // Check Controls first
1639
- if (!checkControl(i, effectiveControl))
1640
- continue;
1641
- const targetBit = (i >> target) & 1;
1642
- const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
1643
- const a = state.amplitudes[i];
1644
- const b = state.amplitudes[pairedIndex];
1645
- if (targetBit === 0) {
1646
- newAmps[i] = { re: s * (a.re + b.re), im: s * (a.im + b.im) };
1647
- newAmps[pairedIndex] = { re: s * (a.re - b.re), im: s * (a.im - b.im) };
1572
+ handleRoute() {
1573
+ return __awaiter(this, void 0, void 0, function* () {
1574
+ if (this.isServer)
1575
+ return;
1576
+ const currentRouteId = ++this.lastRouteId;
1577
+ const hash = window.location.hash.slice(1) || '/';
1578
+ const { route, params } = this.matchRoute(hash);
1579
+ // Security Check: Validate URL to prevent malicious hash injection
1580
+ if (hash !== '/' && !sanitizer_1.Security.validateUrl('http://dummy.com' + hash)) {
1581
+ console.error("Security Alert: Malformed URL detected.");
1582
+ return;
1583
+ }
1584
+ // Navigation Guard (Middleware)
1585
+ if (route === null || route === void 0 ? void 0 : route.beforeEnter) {
1586
+ yield new Promise((resolve) => {
1587
+ route.beforeEnter(hash, this.currentPath, (allow) => {
1588
+ if (allow)
1589
+ resolve();
1590
+ else {
1591
+ console.warn(`Navigation to ${hash} blocked by guard.`);
1592
+ // Ideally redirect or stay, here we just stop processing
1593
+ throw new Error('Navigation Blocked');
1594
+ }
1595
+ });
1596
+ }).catch(() => { return; }); // Stop execution if blocked
1597
+ }
1598
+ this.currentPath = hash;
1599
+ if (route) {
1600
+ if (route.title) {
1601
+ document.title = route.title;
1602
+ }
1603
+ else if (route.meta && route.meta.title) {
1604
+ // Fallback to meta.title if used
1605
+ document.title = route.meta.title;
1606
+ }
1607
+ if (this.rootContainer) {
1608
+ // Mulan Cycle: Destroy previous component before rendering new one
1609
+ if (this.currentComponent) {
1610
+ console.log(`[Router] Navigation from ${this.currentPath} to ${hash}. Destroying previous component.`);
1611
+ if (this.currentComponent.onDestroy) {
1612
+ this.currentComponent.onDestroy();
1613
+ }
1614
+ }
1615
+ this.rootContainer.innerHTML = ''; // Clear previous content
1616
+ }
1617
+ let componentToRender = route.component;
1618
+ // Support Lazy Loading
1619
+ if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1620
+ try {
1621
+ const module = yield componentToRender();
1622
+ if (currentRouteId !== this.lastRouteId) {
1623
+ console.log(`[Router] Navigation to ${hash} interrupted by newer navigation. Abandoning.`);
1624
+ return;
1625
+ }
1626
+ componentToRender = module.default || module;
1627
+ }
1628
+ catch (e) {
1629
+ console.error("Failed to lazy load component", e);
1630
+ return;
1631
+ }
1632
+ }
1633
+ if (typeof componentToRender === 'function') {
1634
+ // It's a class component
1635
+ if (this.rootContainer) {
1636
+ const instance = new componentToRender(this.rootContainer);
1637
+ this.currentComponent = instance;
1638
+ // Inject params if the component accepts them
1639
+ if (instance.setParams) {
1640
+ instance.setParams(params);
1641
+ }
1642
+ instance.mount();
1643
+ }
1644
+ }
1645
+ else if (typeof componentToRender === 'object' && componentToRender.template) {
1646
+ // Object Component (Simple SFC without script or Options API)
1647
+ const html = componentToRender.template();
1648
+ if (this.rootContainer)
1649
+ (0, renderer_1.render)(html, this.rootContainer);
1650
+ this.currentComponent = null;
1651
+ }
1652
+ else {
1653
+ // Simple HTML string/template
1654
+ if (this.rootContainer)
1655
+ (0, renderer_1.render)(componentToRender, this.rootContainer);
1656
+ this.currentComponent = null; // String templates don't have lifecycle instances
1657
+ }
1648
1658
  }
1649
1659
  else {
1650
- newAmps[pairedIndex] = { re: s * (b.re + a.re), im: s * (b.im + a.im) };
1651
- newAmps[i] = { re: s * (b.re - a.re), im: s * (b.im - a.im) };
1660
+ if (this.rootContainer)
1661
+ (0, renderer_1.render)('<div style="text-align:center; padding:50px;"><h1>404</h1><p>Page Not Found</p></div>', this.rootContainer);
1652
1662
  }
1653
- processed.add(i);
1654
- processed.add(pairedIndex);
1655
- }
1663
+ });
1656
1664
  }
1657
- else if (type === 'X' || type === 'CNOT') {
1658
- // CNOT is just Controlled-X
1659
- for (let i = 0; i < amplitudes.length; i++) {
1660
- if (!checkControl(i, effectiveControl))
1661
- continue;
1662
- const targetBit = (i >> target) & 1;
1663
- const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
1664
- if (i < pairedIndex) {
1665
- const temp = newAmps[i];
1666
- newAmps[i] = newAmps[pairedIndex];
1667
- newAmps[pairedIndex] = temp;
1665
+ // [Chronos] Prefetch a route's component code in the background
1666
+ prefetch(path) {
1667
+ return __awaiter(this, void 0, void 0, function* () {
1668
+ if (this.isServer)
1669
+ return;
1670
+ const { route } = this.matchRoute(path);
1671
+ if (route) {
1672
+ let componentToRender = route.component;
1673
+ // Check if it's a lazy-loaded function that hasn't been resolved yet
1674
+ if (typeof componentToRender === 'function' && !componentToRender.prototype) {
1675
+ // If it's already a resolved module (from previous prefetch), componentToRender might be the result.
1676
+ // But typically in our simple implementation, route.component stays as the function until we replace it.
1677
+ // To avoid double-fetching, we can check if it has a specific flag or property.
1678
+ // For this implementation, we'll just run it and let the browser cache the module request (standard ES Module behavior).
1679
+ try {
1680
+ // console.log(`[Chronos] Prefetching ${path}...`);
1681
+ yield componentToRender();
1682
+ // We don't need to do anything with the result here.
1683
+ // The browser's module cache will handle the speedup when the user actually navigates.
1684
+ }
1685
+ catch (e) {
1686
+ console.warn(`[Chronos] Failed to prefetch ${path}`, e);
1687
+ }
1688
+ }
1668
1689
  }
1669
- }
1690
+ });
1670
1691
  }
1671
- else if (type === 'Z' || type === 'CZ') {
1672
- // Z and CZ are Phase Flips
1673
- for (let i = 0; i < amplitudes.length; i++) {
1674
- if (!checkControl(i, effectiveControl))
1675
- continue;
1676
- const targetBit = (i >> target) & 1;
1677
- // Z Gate acts on |1>
1678
- if (targetBit === 1) {
1679
- newAmps[i] = { re: -amplitudes[i].re, im: -amplitudes[i].im };
1680
- }
1692
+ navigate(path) {
1693
+ if (this.isServer) {
1694
+ this.currentPath = path;
1681
1695
  }
1682
- }
1683
- else if (type === 'Y') {
1684
- // Y: |0> -> i|1>, |1> -> -i|0>
1685
- for (let i = 0; i < amplitudes.length; i++) {
1686
- if (!checkControl(i, effectiveControl))
1687
- continue;
1688
- const targetBit = (i >> target) & 1;
1689
- const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
1690
- if (i < pairedIndex) {
1691
- // We process pairs (i, pairedIndex) where i has 0 at target, paired has 1
1692
- const a = newAmps[i]; // Coeff of |0>
1693
- const b = newAmps[pairedIndex]; // Coeff of |1>
1694
- // New |0> = -i * Old |1>
1695
- newAmps[i] = { re: b.im, im: -b.re };
1696
- // New |1> = i * Old |0>
1697
- newAmps[pairedIndex] = { re: -a.im, im: a.re };
1698
- }
1696
+ else {
1697
+ window.location.hash = path;
1699
1698
  }
1700
1699
  }
1701
- updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
1702
1700
  }
1703
- /**
1704
- * Mulan Search Logic (Grover's Operator)
1705
- * Automatically constructs a multi-controlled Phase Flip (Z) for a specific target state.
1706
- * This is the core of the "Quantum Switch" or "Quantum Search" capability.
1707
- * @param reg Quantum Register
1708
- * @param targetState The integer state to "search" and mark (e.g. 2 for |10>)
1709
- */
1710
- function muSearch(reg, targetState) {
1711
- const n = reg.value.size;
1712
- const controls = [];
1713
- // 1. Identify which bits are 0 and need wrapping with X gates
1714
- // Logic: To mark |010>, we want C-C-Z to trigger on 111.
1715
- // So we apply X to bits that are 0, then C-C-Z, then X again.
1716
- // We treat the last bit as the 'target' for the Z gate, rest as controls
1717
- const targetQubit = n - 1;
1718
- for (let i = 0; i < n; i++) {
1719
- const bit = (targetState >> i) & 1;
1720
- if (i === targetQubit) {
1721
- // If target bit logic requires 0, we flip it to 1 for the Z gate to work
1722
- if (bit === 0)
1723
- muGate(reg, 'X', i);
1701
+ exports.MuRouter = MuRouter;
1702
+ // --- Factory for Easy Usage ---
1703
+ const createRouter = (options) => {
1704
+ // Expose the router instance globally for <mu-link> to access
1705
+ const router = new MuRouter(options.routes, options.rootContainer);
1706
+ if (typeof window !== 'undefined') {
1707
+ window.__MULAN_ROUTER__ = router;
1708
+ }
1709
+ return router;
1710
+ };
1711
+ exports.createRouter = createRouter;
1712
+ // --- Web Component: <mu-link> ---
1713
+ // Usage: <mu-link to="/about">About Us</mu-link>
1714
+ const MuLinkBase = typeof HTMLElement !== 'undefined' ? HTMLElement : class {
1715
+ };
1716
+ if (typeof window !== 'undefined' && !customElements.get('mu-link')) {
1717
+ class MuLink extends MuLinkBase {
1718
+ constructor() {
1719
+ super();
1720
+ this.addEventListener('click', (e) => {
1721
+ e.preventDefault();
1722
+ const to = this.getAttribute('to');
1723
+ if (to) {
1724
+ // Update Hash for SPA Navigation
1725
+ window.location.hash = to;
1726
+ }
1727
+ });
1728
+ // [Chronos] Intelligent Pre-fetching
1729
+ this.addEventListener('mouseenter', () => {
1730
+ const to = this.getAttribute('to');
1731
+ if (to) {
1732
+ const router = window.__MULAN_ROUTER__;
1733
+ if (router && typeof router.prefetch === 'function') {
1734
+ router.prefetch(to);
1735
+ }
1736
+ }
1737
+ });
1738
+ // [Chronos] Also prefetch on focus for keyboard users
1739
+ this.addEventListener('focus', () => {
1740
+ const to = this.getAttribute('to');
1741
+ if (to) {
1742
+ const router = window.__MULAN_ROUTER__;
1743
+ if (router && typeof router.prefetch === 'function') {
1744
+ router.prefetch(to);
1745
+ }
1746
+ }
1747
+ });
1724
1748
  }
1725
- else {
1726
- controls.push(i);
1727
- if (bit === 0)
1728
- muGate(reg, 'X', i);
1749
+ connectedCallback() {
1750
+ this.style.cursor = 'pointer';
1751
+ this.style.color = 'var(--primary, #9C27B0)'; // Default to brand color if available
1752
+ this.style.textDecoration = 'none';
1729
1753
  }
1754
+ static get observedAttributes() { return ['to']; }
1730
1755
  }
1731
- // 2. Apply Multi-Controlled Z
1732
- muGate(reg, 'Z', targetQubit, controls);
1733
- // 3. Uncompute (Restore 0s)
1734
- for (let i = 0; i < n; i++) {
1735
- const bit = (targetState >> i) & 1;
1736
- if (bit === 0)
1737
- muGate(reg, 'X', i);
1738
- }
1739
- // --- GROVER DIFFUSER (Amplification) ---
1740
- // This flips the probability amplitudes around the mean, boosting the target state.
1741
- // 1. Apply H to all
1742
- for (let i = 0; i < n; i++)
1743
- muGate(reg, 'H', i);
1744
- // 2. Apply X to all
1745
- for (let i = 0; i < n; i++)
1746
- muGate(reg, 'X', i);
1747
- // 3. Multi-Controlled Z (Reflection about |0...0>)
1748
- // We want to flip phase of |11...1> state after X transformation (which corresponds to |00...0> original)
1749
- // Target is last qubit, controls are 0 to n-2
1750
- const diffControls = [];
1751
- for (let i = 0; i < n - 1; i++)
1752
- diffControls.push(i);
1753
- muGate(reg, 'Z', n - 1, diffControls);
1754
- // 4. Uncompute X
1755
- for (let i = 0; i < n; i++)
1756
- muGate(reg, 'X', i);
1757
- // 5. Uncompute H
1758
- for (let i = 0; i < n; i++)
1759
- muGate(reg, 'H', i);
1760
- }
1761
- function muEntangle(reg, i, j) {
1762
- muGate(reg, 'H', i);
1763
- muGate(reg, 'CNOT', j, i);
1764
- }
1765
- /**
1766
- * Quantum Teleportation Protocol
1767
- * Transfers the state of `msgIdx` to `targetIdx` using `ancillaIdx` as a resource.
1768
- * @param reg Register
1769
- * @param msgIdx The qubit containing the state to teleport (Alice)
1770
- * @param ancillaIdx The helper qubit (Alice's half of entanglement)
1771
- * @param targetIdx The destination qubit (Bob)
1772
- */
1773
- function muTeleport(reg, msgIdx, ancillaIdx, targetIdx) {
1774
- // 1. Create Bell Pair (Entanglement) between Ancilla and Target
1775
- // Represents the shared link between Alice and Bob
1776
- muEntangle(reg, ancillaIdx, targetIdx);
1777
- // 2. Bell Measurement on Message + Ancilla (Alice's side)
1778
- muGate(reg, 'CNOT', ancillaIdx, msgIdx); // Control: msg, Target: ancilla
1779
- muGate(reg, 'H', msgIdx);
1780
- // 3. Measure Alice's qubits (This collapses them)
1781
- const m1 = muMeasure(reg, msgIdx); // Measures "Z" component
1782
- const m2 = muMeasure(reg, ancillaIdx); // Measures "X" component
1783
- // 4. Classical Communication & Correction (Bob's side)
1784
- // Apply corrections to Target based on measurements
1785
- if (m2 === 1)
1786
- muGate(reg, 'X', targetIdx);
1787
- if (m1 === 1)
1788
- muGate(reg, 'Z', targetIdx);
1756
+ customElements.define('mu-link', MuLink);
1789
1757
  }
1790
- /**
1791
- * Measures a specific qubit in the register, collapsing the superposition.
1792
- * @param reg Quantum Register
1793
- * @param target Index of qubit to measure
1794
- * @returns 0 or 1
1795
- */
1796
- function muMeasure(reg, target = 0) {
1797
- const state = reg.value;
1798
- const amplitudes = state.amplitudes;
1799
- let prob0 = 0;
1800
- // 1. Calculate Probability of |0>
1801
- for (let i = 0; i < amplitudes.length; i++) {
1802
- if (((i >> target) & 1) === 0) {
1803
- const a = amplitudes[i];
1804
- prob0 += (a.re * a.re) + (a.im * a.im);
1758
+
1759
+
1760
+ /***/ },
1761
+
1762
+ /***/ 598
1763
+ (__unused_webpack_module, exports, __webpack_require__) {
1764
+
1765
+
1766
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
1767
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1768
+ return new (P || (P = Promise))(function (resolve, reject) {
1769
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1770
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1771
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1772
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1773
+ });
1774
+ };
1775
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1776
+ exports.useMutation = exports.useQuery = void 0;
1777
+ const reactive_1 = __webpack_require__(359);
1778
+ function useQuery(queryFn, options = { enabled: true }) {
1779
+ const state = (0, reactive_1.reactive)({
1780
+ data: null,
1781
+ isLoading: false,
1782
+ error: null
1783
+ });
1784
+ const execute = () => __awaiter(this, void 0, void 0, function* () {
1785
+ state.isLoading = true;
1786
+ state.error = null;
1787
+ try {
1788
+ const result = yield queryFn();
1789
+ state.data = result;
1805
1790
  }
1806
- }
1807
- // 2. Determine Outcome
1808
- const result = Math.random() < prob0 ? 0 : 1;
1809
- const resultProb = result === 0 ? prob0 : (1 - prob0);
1810
- const normFactor = resultProb > 0 ? (1 / Math.sqrt(resultProb)) : 0;
1811
- // 3. Collapse the State (Wavefunction Collapse)
1812
- const newAmps = amplitudes.map((a, i) => {
1813
- const bit = (i >> target) & 1;
1814
- if (bit !== result) {
1815
- return { re: 0, im: 0 };
1791
+ catch (err) {
1792
+ state.error = err;
1816
1793
  }
1817
- else {
1818
- return { re: a.re * normFactor, im: a.im * normFactor };
1794
+ finally {
1795
+ state.isLoading = false;
1819
1796
  }
1820
1797
  });
1821
- // We need to call updateState to ensure reactivity if specialized getters exist
1822
- // But since this file has updateState internal, we can just call it.
1823
- // However, the internal updateState function needs to be in scope.
1824
- // It is defined at line 60. So we are good.
1825
- updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
1826
- return result;
1827
- }
1828
- /**
1829
- * Quantum Loop: Parallel Execution
1830
- * Applies a gate to multiple qubits "simultaneously" (in simulation steps).
1831
- * Ideal for initialization (Hadamard Transform) or global operations.
1832
- * @param reg Quantum Register
1833
- * @param qubits Array of qubit indices
1834
- * @param gate Gate type to apply (e.g. 'H', 'X')
1835
- */
1836
- function muParallel(reg, qubits, gate) {
1837
- if (gate === 'SWAP') {
1838
- throw new Error("SWAP cannot be applied in parallel (requires pairs).");
1798
+ if (options.enabled) {
1799
+ // Run automatically
1800
+ (0, reactive_1.effect)(() => {
1801
+ // Basic effect wrapper to allow reactivity if queryFn relies on signals
1802
+ execute();
1803
+ });
1839
1804
  }
1840
- // In a real quantum computer, these happen at t=0.
1841
- // Here, we loop, but logical time is constant.
1842
- qubits.forEach(q => muGate(reg, gate, q));
1805
+ return {
1806
+ get data() { return state.data; },
1807
+ get isLoading() { return state.isLoading; },
1808
+ get error() { return state.error; },
1809
+ refetch: execute
1810
+ };
1843
1811
  }
1844
- /**
1845
- * Applies a block of operations controlled by specific qubits.
1846
- * Enables "Quantum If/Else".
1847
- */
1848
- function muControl(reg, controlQubit, inverse, block) {
1849
- // 1. Setup Context
1850
- if (inverse) {
1851
- muGate(reg, 'X', controlQubit); // Flip 0 to 1 to activate
1852
- }
1853
- activeControls.push(controlQubit);
1854
- try {
1855
- block();
1856
- }
1857
- finally {
1858
- activeControls.pop();
1859
- // Uncompute (Restore 0)
1860
- if (inverse) {
1861
- muGate(reg, 'X', controlQubit);
1812
+ exports.useQuery = useQuery;
1813
+ function useMutation(mutationFn) {
1814
+ const state = (0, reactive_1.reactive)({
1815
+ data: null,
1816
+ isLoading: false,
1817
+ error: null
1818
+ });
1819
+ const mutate = (args) => __awaiter(this, void 0, void 0, function* () {
1820
+ state.isLoading = true;
1821
+ state.error = null;
1822
+ try {
1823
+ const result = yield mutationFn(args);
1824
+ state.data = result;
1825
+ return result;
1862
1826
  }
1863
- }
1864
- }
1865
- /**
1866
- * Quantum Switch: conditional Logic on Superposition
1867
- * Executes different logic branches based on the state of control qubits.
1868
- * Because the register can be in a superposition of states (e.g. |0> + |1>),
1869
- * MULTIPLE branches can execute effectively simultaneously on different subspaces.
1870
- *
1871
- * @param reg Quantum Register
1872
- * @param controlQubit The qubit controlling the switch (Single control for v1)
1873
- * @param cases Object mapping state (0 or 1) to a function executing quantum operations
1874
- */
1875
- function muSwitch(reg, controlQubit, cases) {
1876
- if (cases[0]) {
1877
- muControl(reg, controlQubit, true, cases[0]);
1878
- }
1879
- if (cases[1]) {
1880
- muControl(reg, controlQubit, false, cases[1]);
1881
- }
1827
+ catch (err) {
1828
+ state.error = err;
1829
+ throw err;
1830
+ }
1831
+ finally {
1832
+ state.isLoading = false;
1833
+ }
1834
+ });
1835
+ return {
1836
+ get data() { return state.data; },
1837
+ get isLoading() { return state.isLoading; },
1838
+ get error() { return state.error; },
1839
+ mutate
1840
+ };
1882
1841
  }
1842
+ exports.useMutation = useMutation;
1843
+
1844
+
1845
+ /***/ },
1846
+
1847
+ /***/ 615
1848
+ (__unused_webpack_module, exports, __webpack_require__) {
1883
1849
 
1884
- ;// ./src/components/bloch-sphere.ts
1885
1850
 
1886
- class MuBlochSphereElement extends HTMLElement {
1851
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
1852
+ exports.MuBlochSphereElement = void 0;
1853
+ const reactive_1 = __webpack_require__(359);
1854
+ const MuBlochBase = typeof HTMLElement !== 'undefined' ? HTMLElement : class {
1855
+ };
1856
+ class MuBlochSphereElement extends MuBlochBase {
1887
1857
  static get observedAttributes() {
1888
1858
  return ['size'];
1889
1859
  }
@@ -1923,7 +1893,7 @@ class MuBlochSphereElement extends HTMLElement {
1923
1893
  if (!this._qubit)
1924
1894
  return;
1925
1895
  // MulanJS Effect: Run whenever the qubit state changes
1926
- this._disposeEffect = effect(() => {
1896
+ this._disposeEffect = (0, reactive_1.effect)(() => {
1927
1897
  const state = this._qubit.value; // Access reactive proxy
1928
1898
  if (!state || !state.amplitudes)
1929
1899
  return;
@@ -2130,274 +2100,604 @@ class MuBlochSphereElement extends HTMLElement {
2130
2100
  this.initReactivity();
2131
2101
  }
2132
2102
  }
2103
+ exports.MuBlochSphereElement = MuBlochSphereElement;
2133
2104
  // Register the custom element
2134
2105
  if (typeof customElements !== 'undefined') {
2135
2106
  customElements.define('mu-bloch-sphere', MuBlochSphereElement);
2136
2107
  }
2137
2108
 
2138
- ;// ./src/components/infinity-list.ts
2139
- class MuInfinity extends HTMLElement {
2140
- constructor() {
2141
- super();
2142
- this._items = [];
2143
- this._itemHeight = 50; // Default height
2144
- this._template = '';
2145
- this.attachShadow({ mode: 'open' });
2146
- // Structure:
2147
- // :host { overflow-y: auto; display: block; height: 100%; }
2148
- // .spacer { height: totalHeight; position: relative; }
2149
- // .content { position: absolute; top: padding; width: 100%; }
2150
- this.shadowRoot.innerHTML = `
2151
- <style>
2152
- :host {
2153
- display: block;
2154
- overflow-y: auto;
2155
- height: 100%;
2156
- position: relative;
2157
- }
2158
- .spacer {
2159
- position: relative;
2160
- width: 100%;
2161
- }
2162
- .content {
2163
- position: absolute;
2164
- top: 0;
2165
- left: 0;
2166
- width: 100%;
2167
- }
2168
- </style>
2169
- <div class="spacer">
2170
- <div class="content"></div>
2171
- </div>
2172
- `;
2173
- this.container = this.shadowRoot.host; // The host itself scrolls
2174
- this.spacer = this.shadowRoot.querySelector('.spacer');
2175
- this.content = this.shadowRoot.querySelector('.content');
2176
- this.onScroll = this.onScroll.bind(this);
2177
- }
2178
- static get observedAttributes() {
2179
- return ['item-height'];
2109
+
2110
+ /***/ },
2111
+
2112
+ /***/ 619
2113
+ (__unused_webpack_module, exports) {
2114
+
2115
+
2116
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
2117
+ exports.sanitize = exports.hydrate = exports.render = void 0;
2118
+ function render(template, container) {
2119
+ // Focus Preservation (The "Mulan Glance" Technique)
2120
+ let focusedId = null;
2121
+ let selectionStart = null;
2122
+ let selectionEnd = null;
2123
+ let preservedValue = null;
2124
+ if (document.activeElement && container.contains(document.activeElement)) {
2125
+ const el = document.activeElement;
2126
+ if (el.hasAttribute('data-mu-id')) {
2127
+ focusedId = el.getAttribute('data-mu-id');
2128
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
2129
+ selectionStart = el.selectionStart;
2130
+ selectionEnd = el.selectionEnd;
2131
+ preservedValue = el.value;
2132
+ }
2133
+ }
2180
2134
  }
2181
- attributeChangedCallback(name, oldValue, newValue) {
2182
- if (name === 'item-height') {
2183
- this._itemHeight = parseInt(newValue, 10) || 50;
2184
- this.renderVisible();
2135
+ // [Anima] 1. Pre-Update: Snapshot positions of animated elements
2136
+ const animationSnapshots = new Map();
2137
+ // Only query if we might have animations to save perf
2138
+ if (typeof template === 'string' && template.includes('mu-animate')) {
2139
+ const animatedEls = container.querySelectorAll('[mu-animate]');
2140
+ animatedEls.forEach(el => {
2141
+ const key = el.getAttribute('mu-key') || el.id;
2142
+ if (key) {
2143
+ animationSnapshots.set(key, el.getBoundingClientRect());
2144
+ }
2145
+ });
2146
+ }
2147
+ if (typeof template === 'string') {
2148
+ container.innerHTML = template;
2149
+ }
2150
+ else {
2151
+ container.innerHTML = '';
2152
+ container.appendChild(template);
2153
+ }
2154
+ // Restore Focus and Value
2155
+ if (focusedId) {
2156
+ const el = container.querySelector(`[data-mu-id="${focusedId}"]`);
2157
+ if (el) {
2158
+ // Restore value first to ensure cursor positioning works correctly
2159
+ if (preservedValue !== null && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
2160
+ el.value = preservedValue;
2161
+ }
2162
+ el.focus();
2163
+ if ((el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && selectionStart !== null) {
2164
+ try {
2165
+ el.setSelectionRange(selectionStart, selectionEnd);
2166
+ }
2167
+ catch (e) {
2168
+ // input types that don't support selection (e.g. number/email) might throw
2169
+ }
2170
+ }
2185
2171
  }
2186
2172
  }
2187
- connectedCallback() {
2188
- // Find the template provided by the user (Support both standard and branded tags)
2189
- const templateTag = this.querySelector('template') || this.querySelector('mu-template');
2190
- if (templateTag) {
2191
- this._template = templateTag.innerHTML;
2173
+ // [Anima] 2. Post-Update: FLIP (First, Last, Invert, Play)
2174
+ if (animationSnapshots.size > 0) {
2175
+ const newAnimatedEls = container.querySelectorAll('[mu-animate]');
2176
+ newAnimatedEls.forEach(el => {
2177
+ const key = el.getAttribute('mu-key') || el.id;
2178
+ if (key && animationSnapshots.has(key)) {
2179
+ const oldRect = animationSnapshots.get(key);
2180
+ const newRect = el.getBoundingClientRect();
2181
+ const dx = oldRect.left - newRect.left;
2182
+ const dy = oldRect.top - newRect.top;
2183
+ // Only animate if moved
2184
+ if (dx !== 0 || dy !== 0) {
2185
+ const htmlEl = el;
2186
+ // INVERT: Move it back to where it was instantly
2187
+ htmlEl.style.transform = `translate(${dx}px, ${dy}px)`;
2188
+ htmlEl.style.transition = 'none';
2189
+ // PLAY: Animate to zero (new position)
2190
+ requestAnimationFrame(() => {
2191
+ // Force reflow
2192
+ // void htmlEl.offsetWidth;
2193
+ htmlEl.style.transition = 'transform 500ms cubic-bezier(0.25, 0.8, 0.25, 1)';
2194
+ htmlEl.style.transform = '';
2195
+ });
2196
+ }
2197
+ }
2198
+ });
2199
+ }
2200
+ }
2201
+ exports.render = render;
2202
+ function hydrate(template, container) {
2203
+ // In a string-based framework, hydration is often just "take over".
2204
+ // For now, we'll verify if the server content matches (simple check)
2205
+ // and then assume control. In a more advanced version, we'd attach listeners without re-rendering.
2206
+ if (typeof template === 'string') {
2207
+ if (container.innerHTML.trim() !== template.trim()) {
2208
+ console.warn('Hydration Mismatch: Server rendered content differs from Client.');
2209
+ container.innerHTML = template; // Fallback to full render
2210
+ }
2211
+ else {
2212
+ // console.log('Hydration Successful.');
2192
2213
  }
2193
- this.addEventListener('scroll', this.onScroll);
2194
- // Wait for next frame to get initial height if not set
2195
- requestAnimationFrame(() => this.renderVisible());
2196
2214
  }
2197
- disconnectedCallback() {
2198
- this.removeEventListener('scroll', this.onScroll);
2215
+ else {
2216
+ container.innerHTML = '';
2217
+ container.appendChild(template);
2199
2218
  }
2200
- set items(value) {
2201
- this._items = value;
2202
- this.renderVisible();
2219
+ // Future: Attach event listeners here if we had a mechanism for it.
2220
+ }
2221
+ exports.hydrate = hydrate;
2222
+ function sanitize(str) {
2223
+ // Check if we are in a browser environment
2224
+ if (typeof document !== 'undefined') {
2225
+ const temp = document.createElement('div');
2226
+ temp.textContent = str;
2227
+ return temp.innerHTML;
2203
2228
  }
2204
- get items() { return this._items; }
2205
- onScroll() {
2206
- requestAnimationFrame(() => this.renderVisible());
2229
+ // Simple SSR fallback sanitizer (rudimentary)
2230
+ return str.replace(/&/g, "&amp;")
2231
+ .replace(/</g, "&lt;")
2232
+ .replace(/>/g, "&gt;")
2233
+ .replace(/"/g, "&quot;")
2234
+ .replace(/'/g, "&#039;");
2235
+ }
2236
+ exports.sanitize = sanitize;
2237
+
2238
+
2239
+ /***/ },
2240
+
2241
+ /***/ 678
2242
+ (__unused_webpack_module, exports) {
2243
+
2244
+
2245
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
2246
+ exports.renderToString = void 0;
2247
+ /**
2248
+ * Renders a Mulan component to a static HTML string with a resumability envelope.
2249
+ */
2250
+ function renderToString(ComponentClass, props = {}) {
2251
+ // 1. Initialize component in a virtual container (not used for DOM)
2252
+ // On server, we mock the container or just pass a dummy object
2253
+ const dummyContainer = {
2254
+ querySelector: () => null,
2255
+ querySelectorAll: () => [],
2256
+ appendChild: () => { },
2257
+ removeChild: () => { },
2258
+ getAttribute: () => null
2259
+ };
2260
+ const instance = new ComponentClass(dummyContainer);
2261
+ // Pass props
2262
+ Object.assign(instance, props);
2263
+ // 2. Render to HTML
2264
+ if (typeof instance.renderToString !== 'function') {
2265
+ throw new Error(`Component ${ComponentClass.name} was not compiled for SSR.`);
2266
+ }
2267
+ const html = instance.renderToString();
2268
+ // 3. Extract State for Resumability
2269
+ // We only want to serialize data that was exposed in setup()
2270
+ // For now, we'll serialize any property on the instance that isn't internal
2271
+ const state = {};
2272
+ for (const key in instance) {
2273
+ if (key.startsWith('_') || key === 'container' || key === 'state' || typeof instance[key] === 'function')
2274
+ continue;
2275
+ const value = instance[key];
2276
+ // Handle signals specifically
2277
+ if (value && typeof value === 'object' && 'value' in value) {
2278
+ state[key] = value.value;
2279
+ }
2280
+ else {
2281
+ state[key] = value;
2282
+ }
2207
2283
  }
2208
- renderVisible() {
2209
- if (!this._items.length)
2210
- return;
2211
- const scrollTop = this.scrollTop;
2212
- const hostHeight = this.clientHeight || 400; // Default fallback if not sized
2213
- const totalHeight = this._items.length * this._itemHeight;
2214
- this.spacer.style.height = `${totalHeight}px`;
2215
- // Windowing Math
2216
- const startIndex = Math.floor(scrollTop / this._itemHeight);
2217
- const buffer = 5;
2218
- const visibleCount = Math.ceil(hostHeight / this._itemHeight);
2219
- const renderStart = Math.max(0, startIndex - buffer);
2220
- const renderEnd = Math.min(this._items.length, startIndex + visibleCount + buffer);
2221
- const startOffset = renderStart * this._itemHeight;
2222
- this.content.style.transform = `translateY(${startOffset}px)`;
2223
- // Render specific slice
2224
- const visibleItems = this._items.slice(renderStart, renderEnd);
2225
- // Simple string replacement template engine for the demo
2226
- // In a real Mulan compilation, this would be an optimized ASTR render
2227
- let html = '';
2228
- visibleItems.forEach((item, index) => {
2229
- const absoluteIndex = renderStart + index;
2230
- // Basic mustache replacement {{ item.prop }}
2231
- let rowHtml = this._template
2232
- .replace(/{{\s*item\s*}}/g, String(item)) // {{ item }}
2233
- .replace(/{{\s*index\s*}}/g, String(absoluteIndex)); // {{ index }}
2234
- // Handle object properties: {{ item.name }}
2235
- if (typeof item === 'object' && item !== null) {
2236
- rowHtml = rowHtml.replace(/{{\s*item\.(\w+)\s*}}/g, (_, prop) => {
2237
- return String(item[prop] || '');
2238
- });
2239
- }
2240
- html += `<div style="height: ${this._itemHeight}px; overflow: hidden;">${rowHtml}</div>`;
2284
+ // 4. Construct Resumability Envelope
2285
+ const stateScript = `<script type="mulan/state" data-mu-uid="${instance.$uid}">${JSON.stringify(state)}</script>`;
2286
+ const envelope = `<div data-mu-root="${instance.$uid}">${html}${stateScript}</div>`;
2287
+ return {
2288
+ html,
2289
+ state,
2290
+ envelope
2291
+ };
2292
+ }
2293
+ exports.renderToString = renderToString;
2294
+
2295
+
2296
+ /***/ },
2297
+
2298
+ /***/ 679
2299
+ (__unused_webpack_module, exports, __webpack_require__) {
2300
+
2301
+
2302
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
2303
+ exports.muSwitch = exports.muControl = exports.muParallel = exports.muMeasure = exports.muTeleport = exports.muEntangle = exports.muSearch = exports.muGate = exports.muQubit = exports.muRegister = exports.activeControls = void 0;
2304
+ const hooks_1 = __webpack_require__(166);
2305
+ /**
2306
+ * Mulan Quantum (ASTR-Q+) Core
2307
+ * Advanced Simulation Engine for multi-qubit registers and entanglement.
2308
+ */
2309
+ // -- GLOBAL CONTEXT FOR QUANTUM CONTROL --
2310
+ // Defined at top to ensure visibility for muGate
2311
+ exports.activeControls = [];
2312
+ /**
2313
+ * Creates a quantum register of size n.
2314
+ * State vector will have 2^n amplitudes.
2315
+ */
2316
+ function muRegister(n) {
2317
+ const numStates = Math.pow(2, n);
2318
+ const amplitudes = new Array(numStates).fill(0).map((_, i) => ({
2319
+ re: i === 0 ? 1 : 0,
2320
+ im: 0
2321
+ }));
2322
+ return (0, hooks_1.muState)({
2323
+ value: {
2324
+ size: n,
2325
+ amplitudes
2326
+ }
2327
+ });
2328
+ }
2329
+ exports.muRegister = muRegister;
2330
+ /**
2331
+ * Backward compatible muQubit (Single Qubit Register)
2332
+ */
2333
+ function muQubit(initial = 0) {
2334
+ const q = muRegister(1);
2335
+ if (initial === 1) {
2336
+ muGate(q, 'X', 0);
2337
+ }
2338
+ // Add compatibility properties for Phase 1 components
2339
+ // These properties are getters that dynamically access the amplitudes array
2340
+ Object.defineProperty(q.value, 'alpha', { get: () => q.value.amplitudes[0] });
2341
+ Object.defineProperty(q.value, 'beta', { get: () => q.value.amplitudes[1] });
2342
+ return q;
2343
+ }
2344
+ exports.muQubit = muQubit;
2345
+ /**
2346
+ * Internal helper to update register state while maintaining compatibility
2347
+ */
2348
+ function updateState(reg, newState) {
2349
+ if (newState.size === 1) {
2350
+ // Re-inject compatibility getters for muQubit users
2351
+ Object.defineProperty(newState, 'alpha', {
2352
+ get: () => newState.amplitudes[0],
2353
+ configurable: true,
2354
+ enumerable: true
2241
2355
  });
2242
- this.content.innerHTML = html;
2356
+ Object.defineProperty(newState, 'beta', {
2357
+ get: () => newState.amplitudes[1],
2358
+ configurable: true,
2359
+ enumerable: true
2360
+ });
2361
+ }
2362
+ reg.value = newState;
2363
+ }
2364
+ function muGate(reg, type, target = 0, control) {
2365
+ const state = reg.value;
2366
+ const n = state.size;
2367
+ const amplitudes = state.amplitudes;
2368
+ const newAmps = amplitudes.map(a => (Object.assign({}, a)));
2369
+ // Prepare Effective Control (Explicit Arguments + Global Context)
2370
+ const effectiveControl = [...(control === undefined ? [] : (Array.isArray(control) ? control : [control])), ...exports.activeControls];
2371
+ // Helper: Check if all control bits are 1
2372
+ const checkControl = (index, ctrl) => {
2373
+ if (ctrl === undefined || (Array.isArray(ctrl) && ctrl.length === 0))
2374
+ return true;
2375
+ const ctrls = Array.isArray(ctrl) ? ctrl : [ctrl];
2376
+ return ctrls.every(c => ((index >> c) & 1) === 1);
2377
+ };
2378
+ // SWAP Gate (Unique case: affects 2 targets)
2379
+ if (type === 'SWAP') {
2380
+ const t1 = target;
2381
+ const t2 = control; // SWAP uses control arg as second target
2382
+ // Iterate only half to avoid double swapping
2383
+ for (let i = 0; i < amplitudes.length; i++) {
2384
+ // Check active controls for SWAP too
2385
+ if (exports.activeControls.length > 0 && !checkControl(i, exports.activeControls))
2386
+ continue;
2387
+ const bit1 = (i >> t1) & 1;
2388
+ const bit2 = (i >> t2) & 1;
2389
+ if (bit1 !== bit2) {
2390
+ // Determine the swap partner index
2391
+ // If i has (0,1), partner has (1,0) at those positions
2392
+ const partner = i ^ (1 << t1) ^ (1 << t2);
2393
+ if (i < partner) {
2394
+ const temp = newAmps[i];
2395
+ newAmps[i] = newAmps[partner];
2396
+ newAmps[partner] = temp;
2397
+ }
2398
+ }
2399
+ }
2400
+ updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
2401
+ return;
2402
+ }
2403
+ // Standard Single-Qubit & Controlled Gates
2404
+ if (type === 'H') {
2405
+ const s = 1 / Math.sqrt(2);
2406
+ const processed = new Set();
2407
+ for (let i = 0; i < state.amplitudes.length; i++) {
2408
+ if (processed.has(i))
2409
+ continue;
2410
+ // Check Controls first
2411
+ if (!checkControl(i, effectiveControl))
2412
+ continue;
2413
+ const targetBit = (i >> target) & 1;
2414
+ const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
2415
+ const a = state.amplitudes[i];
2416
+ const b = state.amplitudes[pairedIndex];
2417
+ if (targetBit === 0) {
2418
+ newAmps[i] = { re: s * (a.re + b.re), im: s * (a.im + b.im) };
2419
+ newAmps[pairedIndex] = { re: s * (a.re - b.re), im: s * (a.im - b.im) };
2420
+ }
2421
+ else {
2422
+ newAmps[pairedIndex] = { re: s * (b.re + a.re), im: s * (b.im + a.im) };
2423
+ newAmps[i] = { re: s * (b.re - a.re), im: s * (b.im - a.im) };
2424
+ }
2425
+ processed.add(i);
2426
+ processed.add(pairedIndex);
2427
+ }
2243
2428
  }
2429
+ else if (type === 'X' || type === 'CNOT') {
2430
+ // CNOT is just Controlled-X
2431
+ for (let i = 0; i < amplitudes.length; i++) {
2432
+ if (!checkControl(i, effectiveControl))
2433
+ continue;
2434
+ const targetBit = (i >> target) & 1;
2435
+ const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
2436
+ if (i < pairedIndex) {
2437
+ const temp = newAmps[i];
2438
+ newAmps[i] = newAmps[pairedIndex];
2439
+ newAmps[pairedIndex] = temp;
2440
+ }
2441
+ }
2442
+ }
2443
+ else if (type === 'Z' || type === 'CZ') {
2444
+ // Z and CZ are Phase Flips
2445
+ for (let i = 0; i < amplitudes.length; i++) {
2446
+ if (!checkControl(i, effectiveControl))
2447
+ continue;
2448
+ const targetBit = (i >> target) & 1;
2449
+ // Z Gate acts on |1>
2450
+ if (targetBit === 1) {
2451
+ newAmps[i] = { re: -amplitudes[i].re, im: -amplitudes[i].im };
2452
+ }
2453
+ }
2454
+ }
2455
+ else if (type === 'Y') {
2456
+ // Y: |0> -> i|1>, |1> -> -i|0>
2457
+ for (let i = 0; i < amplitudes.length; i++) {
2458
+ if (!checkControl(i, effectiveControl))
2459
+ continue;
2460
+ const targetBit = (i >> target) & 1;
2461
+ const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
2462
+ if (i < pairedIndex) {
2463
+ // We process pairs (i, pairedIndex) where i has 0 at target, paired has 1
2464
+ const a = newAmps[i]; // Coeff of |0>
2465
+ const b = newAmps[pairedIndex]; // Coeff of |1>
2466
+ // New |0> = -i * Old |1>
2467
+ newAmps[i] = { re: b.im, im: -b.re };
2468
+ // New |1> = i * Old |0>
2469
+ newAmps[pairedIndex] = { re: -a.im, im: a.re };
2470
+ }
2471
+ }
2472
+ }
2473
+ updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
2474
+ }
2475
+ exports.muGate = muGate;
2476
+ /**
2477
+ * Mulan Search Logic (Grover's Operator)
2478
+ * Automatically constructs a multi-controlled Phase Flip (Z) for a specific target state.
2479
+ * This is the core of the "Quantum Switch" or "Quantum Search" capability.
2480
+ * @param reg Quantum Register
2481
+ * @param targetState The integer state to "search" and mark (e.g. 2 for |10>)
2482
+ */
2483
+ function muSearch(reg, targetState) {
2484
+ const n = reg.value.size;
2485
+ const controls = [];
2486
+ // 1. Identify which bits are 0 and need wrapping with X gates
2487
+ // Logic: To mark |010>, we want C-C-Z to trigger on 111.
2488
+ // So we apply X to bits that are 0, then C-C-Z, then X again.
2489
+ // We treat the last bit as the 'target' for the Z gate, rest as controls
2490
+ const targetQubit = n - 1;
2491
+ for (let i = 0; i < n; i++) {
2492
+ const bit = (targetState >> i) & 1;
2493
+ if (i === targetQubit) {
2494
+ // If target bit logic requires 0, we flip it to 1 for the Z gate to work
2495
+ if (bit === 0)
2496
+ muGate(reg, 'X', i);
2497
+ }
2498
+ else {
2499
+ controls.push(i);
2500
+ if (bit === 0)
2501
+ muGate(reg, 'X', i);
2502
+ }
2503
+ }
2504
+ // 2. Apply Multi-Controlled Z
2505
+ muGate(reg, 'Z', targetQubit, controls);
2506
+ // 3. Uncompute (Restore 0s)
2507
+ for (let i = 0; i < n; i++) {
2508
+ const bit = (targetState >> i) & 1;
2509
+ if (bit === 0)
2510
+ muGate(reg, 'X', i);
2511
+ }
2512
+ // --- GROVER DIFFUSER (Amplification) ---
2513
+ // This flips the probability amplitudes around the mean, boosting the target state.
2514
+ // 1. Apply H to all
2515
+ for (let i = 0; i < n; i++)
2516
+ muGate(reg, 'H', i);
2517
+ // 2. Apply X to all
2518
+ for (let i = 0; i < n; i++)
2519
+ muGate(reg, 'X', i);
2520
+ // 3. Multi-Controlled Z (Reflection about |0...0>)
2521
+ // We want to flip phase of |11...1> state after X transformation (which corresponds to |00...0> original)
2522
+ // Target is last qubit, controls are 0 to n-2
2523
+ const diffControls = [];
2524
+ for (let i = 0; i < n - 1; i++)
2525
+ diffControls.push(i);
2526
+ muGate(reg, 'Z', n - 1, diffControls);
2527
+ // 4. Uncompute X
2528
+ for (let i = 0; i < n; i++)
2529
+ muGate(reg, 'X', i);
2530
+ // 5. Uncompute H
2531
+ for (let i = 0; i < n; i++)
2532
+ muGate(reg, 'H', i);
2244
2533
  }
2245
- // Register
2246
- if (typeof customElements !== 'undefined' && !customElements.get('mu-infinity')) {
2247
- customElements.define('mu-infinity', MuInfinity);
2534
+ exports.muSearch = muSearch;
2535
+ function muEntangle(reg, i, j) {
2536
+ muGate(reg, 'H', i);
2537
+ muGate(reg, 'CNOT', j, i);
2248
2538
  }
2249
-
2250
- ;// ./src/core/surge.ts
2539
+ exports.muEntangle = muEntangle;
2251
2540
  /**
2252
- * muBurst - Adaptive Non-blocking Iterator
2253
- * Processes large arrays in batches within a frame budget (typically 8-16ms)
2254
- * to keep the UI responsive while executing at near-native loop speeds.
2541
+ * Quantum Teleportation Protocol
2542
+ * Transfers the state of `msgIdx` to `targetIdx` using `ancillaIdx` as a resource.
2543
+ * @param reg Register
2544
+ * @param msgIdx The qubit containing the state to teleport (Alice)
2545
+ * @param ancillaIdx The helper qubit (Alice's half of entanglement)
2546
+ * @param targetIdx The destination qubit (Bob)
2255
2547
  */
2256
- function muBurst(array, callback, options = {}) {
2257
- const { chunkSize = 1000, timeout = 8, onProgress } = options;
2258
- return new Promise((resolve) => {
2259
- let index = 0;
2260
- const total = array.length;
2261
- function process() {
2262
- const start = performance.now();
2263
- // Tight loop for high-speed processing
2264
- while (index < total && (performance.now() - start) < timeout) {
2265
- // Process in smaller bursts to allow more frequent time checks if needed
2266
- const endBurst = Math.min(index + chunkSize, total);
2267
- for (; index < endBurst; index++) {
2268
- callback(array[index], index);
2269
- }
2270
- }
2271
- if (onProgress) {
2272
- onProgress((index / total) * 100);
2273
- }
2274
- if (index < total) {
2275
- requestAnimationFrame(process);
2276
- }
2277
- else {
2278
- resolve();
2279
- }
2280
- }
2281
- process();
2282
- });
2548
+ function muTeleport(reg, msgIdx, ancillaIdx, targetIdx) {
2549
+ // 1. Create Bell Pair (Entanglement) between Ancilla and Target
2550
+ // Represents the shared link between Alice and Bob
2551
+ muEntangle(reg, ancillaIdx, targetIdx);
2552
+ // 2. Bell Measurement on Message + Ancilla (Alice's side)
2553
+ muGate(reg, 'CNOT', ancillaIdx, msgIdx); // Control: msg, Target: ancilla
2554
+ muGate(reg, 'H', msgIdx);
2555
+ // 3. Measure Alice's qubits (This collapses them)
2556
+ const m1 = muMeasure(reg, msgIdx); // Measures "Z" component
2557
+ const m2 = muMeasure(reg, ancillaIdx); // Measures "X" component
2558
+ // 4. Classical Communication & Correction (Bob's side)
2559
+ // Apply corrections to Target based on measurements
2560
+ if (m2 === 1)
2561
+ muGate(reg, 'X', targetIdx);
2562
+ if (m1 === 1)
2563
+ muGate(reg, 'Z', targetIdx);
2283
2564
  }
2565
+ exports.muTeleport = muTeleport;
2284
2566
  /**
2285
- * muSurge - Truly Parallel Execution
2286
- * Distributes work across CPU cores using Web Workers.
2287
- * Logic must be serializable.
2567
+ * Measures a specific qubit in the register, collapsing the superposition.
2568
+ * @param reg Quantum Register
2569
+ * @param target Index of qubit to measure
2570
+ * @returns 0 or 1
2288
2571
  */
2289
- function muSurge(array, taskFn, onProgress) {
2290
- const n = navigator.hardwareConcurrency || 4;
2291
- const chunkSize = Math.ceil(array.length / n);
2292
- const results = new Array(array.length);
2293
- let completedChunks = 0;
2294
- let completedItems = 0;
2295
- // Convert function to string if it isn't already
2296
- const fnStr = typeof taskFn === 'function' ? taskFn.toString() : taskFn;
2297
- const workerPart1 = `const taskFn = ${fnStr};`;
2298
- const workerPart2 = `self.onmessage = function(e) {`;
2299
- const workerPart3 = ` const { chunk, startIndex } = e.data;`;
2300
- const workerPart4 = ` try { const results = chunk.map(taskFn); self.postMessage({ results, startIndex }); }`;
2301
- const workerPart5 = ` catch (err) { self.postMessage({ error: err.message, startIndex }); }`;
2302
- const workerPart6 = `};`;
2303
- const workerCode = [workerPart1, workerPart2, workerPart3, workerPart4, workerPart5, workerPart6].join('\n');
2304
- const blob = new Blob([workerCode], { type: 'application/javascript' });
2305
- const workerUrl = URL.createObjectURL(blob);
2306
- return new Promise((resolve) => {
2307
- if (array.length === 0)
2308
- return resolve([]);
2309
- for (let i = 0; i < n; i++) {
2310
- const start = i * chunkSize;
2311
- const end = Math.min(start + chunkSize, array.length);
2312
- if (start >= end) {
2313
- completedChunks++;
2314
- continue;
2315
- }
2316
- const chunk = array.slice(start, end);
2317
- const worker = new Worker(workerUrl);
2318
- worker.onmessage = (e) => {
2319
- const { results: chunkResults, startIndex } = e.data;
2320
- // Merge results back into main array
2321
- for (let j = 0; j < chunkResults.length; j++) {
2322
- results[startIndex + j] = chunkResults[j];
2323
- }
2324
- completedChunks++;
2325
- completedItems += chunkResults.length;
2326
- if (onProgress)
2327
- onProgress((completedItems / array.length) * 100);
2328
- worker.terminate();
2329
- if (completedChunks === n) {
2330
- URL.revokeObjectURL(workerUrl);
2331
- resolve(results);
2332
- }
2333
- };
2334
- worker.postMessage({ chunk, startIndex: start, fnStr });
2572
+ function muMeasure(reg, target = 0) {
2573
+ const state = reg.value;
2574
+ const amplitudes = state.amplitudes;
2575
+ let prob0 = 0;
2576
+ // 1. Calculate Probability of |0>
2577
+ for (let i = 0; i < amplitudes.length; i++) {
2578
+ if (((i >> target) & 1) === 0) {
2579
+ const a = amplitudes[i];
2580
+ prob0 += (a.re * a.re) + (a.im * a.im);
2581
+ }
2582
+ }
2583
+ // 2. Determine Outcome
2584
+ const result = Math.random() < prob0 ? 0 : 1;
2585
+ const resultProb = result === 0 ? prob0 : (1 - prob0);
2586
+ const normFactor = resultProb > 0 ? (1 / Math.sqrt(resultProb)) : 0;
2587
+ // 3. Collapse the State (Wavefunction Collapse)
2588
+ const newAmps = amplitudes.map((a, i) => {
2589
+ const bit = (i >> target) & 1;
2590
+ if (bit !== result) {
2591
+ return { re: 0, im: 0 };
2592
+ }
2593
+ else {
2594
+ return { re: a.re * normFactor, im: a.im * normFactor };
2335
2595
  }
2336
2596
  });
2597
+ // We need to call updateState to ensure reactivity if specialized getters exist
2598
+ // But since this file has updateState internal, we can just call it.
2599
+ // However, the internal updateState function needs to be in scope.
2600
+ // It is defined at line 60. So we are good.
2601
+ updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
2602
+ return result;
2337
2603
  }
2338
-
2339
- ;// ./src/index.ts
2340
-
2341
-
2342
-
2343
-
2344
-
2345
-
2346
-
2347
-
2348
-
2349
-
2350
-
2351
-
2352
-
2353
- // Global Mulan Object for non-module usage
2354
-
2355
-
2356
-
2357
-
2358
-
2359
-
2360
-
2361
-
2362
-
2363
-
2364
-
2365
- const Mulan = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ reactive: reactive,
2366
- effect: effect, Component: MuComponent, defineComponent: defineComponent, Router: MuRouter, createRouter: createRouter, Store: MuStore, Security: Security }, hooks_namespaceObject), query_namespaceObject), quantum_namespaceObject), surge_namespaceObject), infinity_list_namespaceObject), { render: render,
2367
- // MULAN INSIGHT: Branded Logging
2368
- log: (msg, ...args) => {
2369
- console.log(`%c[MulanJS]%c ${msg}`, "color: #ff3e00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
2370
- }, warn: (msg, ...args) => {
2371
- console.warn(`%c[MulanJS]%c ${msg}`, "color: #ffcc00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
2372
- }, error: (msg, ...args) => {
2373
- console.error(`%c[MulanJS]%c ${msg}`, "color: #ff0000; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
2374
- } });
2375
- // Security: Freeze the object to prevent runtime tampering
2376
- Object.freeze(Mulan);
2377
- Object.freeze(Mulan.Security);
2378
- // MULAN INSIGHT: Initialize Global Registry
2379
- if (typeof window !== 'undefined') {
2380
- window.__MULAN_INSIGHT__ = window.__MULAN_INSIGHT__ || { components: new Map() };
2381
- // MULAN INSIGHT: HMR Support
2382
- window.__MULAN_REFRESH__ = () => {
2383
- var _a;
2384
- const components = (_a = window.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components;
2385
- if (components) {
2386
- components.forEach((comp) => {
2387
- if (comp && typeof comp.update === 'function') {
2388
- // Force refresh
2389
- comp.update();
2390
- }
2391
- });
2604
+ exports.muMeasure = muMeasure;
2605
+ /**
2606
+ * Quantum Loop: Parallel Execution
2607
+ * Applies a gate to multiple qubits "simultaneously" (in simulation steps).
2608
+ * Ideal for initialization (Hadamard Transform) or global operations.
2609
+ * @param reg Quantum Register
2610
+ * @param qubits Array of qubit indices
2611
+ * @param gate Gate type to apply (e.g. 'H', 'X')
2612
+ */
2613
+ function muParallel(reg, qubits, gate) {
2614
+ if (gate === 'SWAP') {
2615
+ throw new Error("SWAP cannot be applied in parallel (requires pairs).");
2616
+ }
2617
+ // In a real quantum computer, these happen at t=0.
2618
+ // Here, we loop, but logical time is constant.
2619
+ qubits.forEach(q => muGate(reg, gate, q));
2620
+ }
2621
+ exports.muParallel = muParallel;
2622
+ /**
2623
+ * Applies a block of operations controlled by specific qubits.
2624
+ * Enables "Quantum If/Else".
2625
+ */
2626
+ function muControl(reg, controlQubit, inverse, block) {
2627
+ // 1. Setup Context
2628
+ if (inverse) {
2629
+ muGate(reg, 'X', controlQubit); // Flip 0 to 1 to activate
2630
+ }
2631
+ exports.activeControls.push(controlQubit);
2632
+ try {
2633
+ block();
2634
+ }
2635
+ finally {
2636
+ exports.activeControls.pop();
2637
+ // Uncompute (Restore 0)
2638
+ if (inverse) {
2639
+ muGate(reg, 'X', controlQubit);
2392
2640
  }
2393
- };
2641
+ }
2394
2642
  }
2395
- if (typeof window !== 'undefined') {
2396
- window.Mulan = Mulan;
2643
+ exports.muControl = muControl;
2644
+ /**
2645
+ * Quantum Switch: conditional Logic on Superposition
2646
+ * Executes different logic branches based on the state of control qubits.
2647
+ * Because the register can be in a superposition of states (e.g. |0> + |1>),
2648
+ * MULTIPLE branches can execute effectively simultaneously on different subspaces.
2649
+ *
2650
+ * @param reg Quantum Register
2651
+ * @param controlQubit The qubit controlling the switch (Single control for v1)
2652
+ * @param cases Object mapping state (0 or 1) to a function executing quantum operations
2653
+ */
2654
+ function muSwitch(reg, controlQubit, cases) {
2655
+ if (cases[0]) {
2656
+ muControl(reg, controlQubit, true, cases[0]);
2657
+ }
2658
+ if (cases[1]) {
2659
+ muControl(reg, controlQubit, false, cases[1]);
2660
+ }
2397
2661
  }
2398
- /* harmony default export */ const src = (Mulan);
2662
+ exports.muSwitch = muSwitch;
2663
+
2399
2664
 
2400
- __webpack_exports__ = __webpack_exports__["default"];
2665
+ /***/ }
2666
+
2667
+ /******/ });
2668
+ /************************************************************************/
2669
+ /******/ // The module cache
2670
+ /******/ var __webpack_module_cache__ = {};
2671
+ /******/
2672
+ /******/ // The require function
2673
+ /******/ function __webpack_require__(moduleId) {
2674
+ /******/ // Check if module is in cache
2675
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
2676
+ /******/ if (cachedModule !== undefined) {
2677
+ /******/ return cachedModule.exports;
2678
+ /******/ }
2679
+ /******/ // Create a new module (and put it into the cache)
2680
+ /******/ var module = __webpack_module_cache__[moduleId] = {
2681
+ /******/ // no module.id needed
2682
+ /******/ // no module.loaded needed
2683
+ /******/ exports: {}
2684
+ /******/ };
2685
+ /******/
2686
+ /******/ // Execute the module function
2687
+ /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
2688
+ /******/
2689
+ /******/ // Return the exports of the module
2690
+ /******/ return module.exports;
2691
+ /******/ }
2692
+ /******/
2693
+ /************************************************************************/
2694
+ /******/
2695
+ /******/ // startup
2696
+ /******/ // Load entry module and return exports
2697
+ /******/ // This entry module is referenced by other modules so it can't be inlined
2698
+ /******/ var __webpack_exports__ = __webpack_require__(156);
2699
+ /******/ __webpack_exports__ = __webpack_exports__["default"];
2700
+ /******/
2401
2701
  /******/ return __webpack_exports__;
2402
2702
  /******/ })()
2403
2703
  ;