@mulanjs/mulanjs 1.0.1-dev.20260220121828 → 1.0.1-dev.20260220131258
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/hooks.js +1 -1
- package/dist/core/surge.js +7 -12
- package/dist/core/vault.js +3 -8
- package/dist/mulan.esm.js +1645 -1945
- package/dist/mulan.esm.js.map +1 -0
- package/dist/mulan.js +2022 -177
- package/dist/mulan.js.map +1 -0
- package/dist/types/core/vault.d.ts +1 -0
- package/package.json +13 -2
- package/src/cli/index.js +14 -6
package/dist/mulan.js
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
|
|
3
|
-
* This devtool is neither made for production nor for readable output files.
|
|
4
|
-
* It uses "eval()" calls to create a separate source file in the browser devtools.
|
|
5
|
-
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
|
|
6
|
-
* or disable the default devtool with "devtool: false".
|
|
7
|
-
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
|
|
8
|
-
*/
|
|
9
1
|
(function webpackUniversalModuleDefinition(root, factory) {
|
|
10
2
|
if(typeof exports === 'object' && typeof module === 'object')
|
|
11
3
|
module.exports = factory();
|
|
@@ -18,218 +10,2071 @@
|
|
|
18
10
|
})(this, () => {
|
|
19
11
|
return /******/ (() => { // webpackBootstrap
|
|
20
12
|
/******/ "use strict";
|
|
21
|
-
/******/
|
|
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, muEffect, muEntangle, muGate, muGeom, muMeasure, muMemo, muParallel, muPulse, muQubit, muRegister, muSearch, muState, muSurge, muSwitch, muTeleport, muVault, onMuDestroy, onMuIdle, onMuInit, onMuMount, onMuResume, onMuShake, 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
|
+
muEffect: () => (muEffect),
|
|
61
|
+
muGeom: () => (muGeom),
|
|
62
|
+
muMemo: () => (muMemo),
|
|
63
|
+
muPulse: () => (muPulse),
|
|
64
|
+
muState: () => (muState),
|
|
65
|
+
muVault: () => (muVault),
|
|
66
|
+
onMuDestroy: () => (onMuDestroy),
|
|
67
|
+
onMuIdle: () => (onMuIdle),
|
|
68
|
+
onMuInit: () => (onMuInit),
|
|
69
|
+
onMuMount: () => (onMuMount),
|
|
70
|
+
onMuResume: () => (onMuResume),
|
|
71
|
+
onMuShake: () => (onMuShake),
|
|
72
|
+
onMuVoice: () => (onMuVoice),
|
|
73
|
+
setCurrentInstance: () => (setCurrentInstance)
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// NAMESPACE OBJECT: ./src/core/query.ts
|
|
77
|
+
var query_namespaceObject = {};
|
|
78
|
+
__webpack_require__.r(query_namespaceObject);
|
|
79
|
+
__webpack_require__.d(query_namespaceObject, {
|
|
80
|
+
useMutation: () => (useMutation),
|
|
81
|
+
useQuery: () => (useQuery)
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// NAMESPACE OBJECT: ./src/core/quantum.ts
|
|
85
|
+
var quantum_namespaceObject = {};
|
|
86
|
+
__webpack_require__.r(quantum_namespaceObject);
|
|
87
|
+
__webpack_require__.d(quantum_namespaceObject, {
|
|
88
|
+
activeControls: () => (activeControls),
|
|
89
|
+
muControl: () => (muControl),
|
|
90
|
+
muEntangle: () => (muEntangle),
|
|
91
|
+
muGate: () => (muGate),
|
|
92
|
+
muMeasure: () => (muMeasure),
|
|
93
|
+
muParallel: () => (muParallel),
|
|
94
|
+
muQubit: () => (muQubit),
|
|
95
|
+
muRegister: () => (muRegister),
|
|
96
|
+
muSearch: () => (muSearch),
|
|
97
|
+
muSwitch: () => (muSwitch),
|
|
98
|
+
muTeleport: () => (muTeleport)
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// NAMESPACE OBJECT: ./src/components/infinity-list.ts
|
|
102
|
+
var infinity_list_namespaceObject = {};
|
|
103
|
+
__webpack_require__.r(infinity_list_namespaceObject);
|
|
104
|
+
__webpack_require__.d(infinity_list_namespaceObject, {
|
|
105
|
+
MuInfinity: () => (MuInfinity)
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// NAMESPACE OBJECT: ./src/core/surge.ts
|
|
109
|
+
var surge_namespaceObject = {};
|
|
110
|
+
__webpack_require__.r(surge_namespaceObject);
|
|
111
|
+
__webpack_require__.d(surge_namespaceObject, {
|
|
112
|
+
muBurst: () => (muBurst),
|
|
113
|
+
muSurge: () => (muSurge)
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
;// ./src/core/reactive.ts
|
|
117
|
+
// MulanJS 2.0: Signal-Powered Reactivity Engine
|
|
118
|
+
// "Compatible Surface, World-Class Engine"
|
|
119
|
+
let activeEffect = null;
|
|
120
|
+
const targetMap = new WeakMap();
|
|
121
|
+
// --- Signal Core (The Engine) ---
|
|
122
|
+
class Signal {
|
|
123
|
+
constructor(initialValue) {
|
|
124
|
+
this._subscribers = new Set();
|
|
125
|
+
this._value = initialValue;
|
|
126
|
+
}
|
|
127
|
+
get value() {
|
|
128
|
+
if (activeEffect) {
|
|
129
|
+
this._subscribers.add(activeEffect);
|
|
130
|
+
}
|
|
131
|
+
return this._value;
|
|
132
|
+
}
|
|
133
|
+
set value(newValue) {
|
|
134
|
+
if (newValue !== this._value) {
|
|
135
|
+
this._value = newValue;
|
|
136
|
+
this.notify();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
notify() {
|
|
140
|
+
this._subscribers.forEach(fn => fn());
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// --- Compatibility Layer (The Surface) ---
|
|
144
|
+
function effect(fn) {
|
|
145
|
+
let stopped = false;
|
|
146
|
+
const run = () => {
|
|
147
|
+
if (stopped)
|
|
148
|
+
return;
|
|
149
|
+
const prev = activeEffect;
|
|
150
|
+
activeEffect = run;
|
|
151
|
+
try {
|
|
152
|
+
fn();
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
activeEffect = prev;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
run();
|
|
159
|
+
return () => {
|
|
160
|
+
stopped = true;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function track(target, key) {
|
|
164
|
+
if (activeEffect) {
|
|
165
|
+
let depsMap = targetMap.get(target);
|
|
166
|
+
if (!depsMap) {
|
|
167
|
+
targetMap.set(target, (depsMap = new Map()));
|
|
168
|
+
}
|
|
169
|
+
let dep = depsMap.get(key);
|
|
170
|
+
if (!dep) {
|
|
171
|
+
depsMap.set(key, (dep = new Set()));
|
|
172
|
+
}
|
|
173
|
+
dep.add(activeEffect);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function trigger(target, key) {
|
|
177
|
+
const depsMap = targetMap.get(target);
|
|
178
|
+
if (!depsMap)
|
|
179
|
+
return;
|
|
180
|
+
const dep = depsMap.get(key);
|
|
181
|
+
if (dep) {
|
|
182
|
+
dep.forEach((fn) => fn());
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Creates a reactive proxy object (Vue-compatible).
|
|
187
|
+
* Now optimized to respect Mulan Cycle.
|
|
188
|
+
*/
|
|
189
|
+
function reactive(target) {
|
|
190
|
+
return new Proxy(target, {
|
|
191
|
+
get(obj, prop, receiver) {
|
|
192
|
+
// IRON FORTRESS: Prototype Pollution Protection (Read)
|
|
193
|
+
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
track(obj, prop);
|
|
197
|
+
const val = Reflect.get(obj, prop, receiver);
|
|
198
|
+
if (val !== null && typeof val === 'object') {
|
|
199
|
+
return reactive(val);
|
|
200
|
+
}
|
|
201
|
+
return val;
|
|
202
|
+
},
|
|
203
|
+
set(obj, prop, value, receiver) {
|
|
204
|
+
// IRON FORTRESS: Prototype Pollution Protection
|
|
205
|
+
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {
|
|
206
|
+
console.warn(`[Iron Fortress] Blocked attempt to modify dangerous property: ${String(prop)}`);
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
const result = Reflect.set(obj, prop, value, receiver);
|
|
210
|
+
trigger(obj, prop);
|
|
211
|
+
return result;
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Creates a standalone reactive reference.
|
|
217
|
+
* Backed by the Mulan Signal Engine.
|
|
218
|
+
*/
|
|
219
|
+
function ref(value) {
|
|
220
|
+
return new Signal(value);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
;// ./src/core/renderer.ts
|
|
224
|
+
function render(template, container) {
|
|
225
|
+
// Focus Preservation (The "Mulan Glance" Technique)
|
|
226
|
+
let focusedId = null;
|
|
227
|
+
let selectionStart = null;
|
|
228
|
+
let selectionEnd = null;
|
|
229
|
+
let preservedValue = null;
|
|
230
|
+
if (document.activeElement && container.contains(document.activeElement)) {
|
|
231
|
+
const el = document.activeElement;
|
|
232
|
+
if (el.hasAttribute('data-mu-id')) {
|
|
233
|
+
focusedId = el.getAttribute('data-mu-id');
|
|
234
|
+
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
|
|
235
|
+
selectionStart = el.selectionStart;
|
|
236
|
+
selectionEnd = el.selectionEnd;
|
|
237
|
+
preservedValue = el.value;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// [Anima] 1. Pre-Update: Snapshot positions of animated elements
|
|
242
|
+
const animationSnapshots = new Map();
|
|
243
|
+
// Only query if we might have animations to save perf
|
|
244
|
+
if (template.includes('mu-animate')) {
|
|
245
|
+
const animatedEls = container.querySelectorAll('[mu-animate]');
|
|
246
|
+
animatedEls.forEach(el => {
|
|
247
|
+
const key = el.getAttribute('mu-key') || el.id;
|
|
248
|
+
if (key) {
|
|
249
|
+
animationSnapshots.set(key, el.getBoundingClientRect());
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
container.innerHTML = template;
|
|
254
|
+
// Restore Focus and Value
|
|
255
|
+
if (focusedId) {
|
|
256
|
+
const el = container.querySelector(`[data-mu-id="${focusedId}"]`);
|
|
257
|
+
if (el) {
|
|
258
|
+
// Restore value first to ensure cursor positioning works correctly
|
|
259
|
+
if (preservedValue !== null && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {
|
|
260
|
+
el.value = preservedValue;
|
|
261
|
+
}
|
|
262
|
+
el.focus();
|
|
263
|
+
if ((el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && selectionStart !== null) {
|
|
264
|
+
try {
|
|
265
|
+
el.setSelectionRange(selectionStart, selectionEnd);
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
// input types that don't support selection (e.g. number/email) might throw
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
// [Anima] 2. Post-Update: FLIP (First, Last, Invert, Play)
|
|
274
|
+
if (animationSnapshots.size > 0) {
|
|
275
|
+
const newAnimatedEls = container.querySelectorAll('[mu-animate]');
|
|
276
|
+
newAnimatedEls.forEach(el => {
|
|
277
|
+
const key = el.getAttribute('mu-key') || el.id;
|
|
278
|
+
if (key && animationSnapshots.has(key)) {
|
|
279
|
+
const oldRect = animationSnapshots.get(key);
|
|
280
|
+
const newRect = el.getBoundingClientRect();
|
|
281
|
+
const dx = oldRect.left - newRect.left;
|
|
282
|
+
const dy = oldRect.top - newRect.top;
|
|
283
|
+
// Only animate if moved
|
|
284
|
+
if (dx !== 0 || dy !== 0) {
|
|
285
|
+
const htmlEl = el;
|
|
286
|
+
// INVERT: Move it back to where it was instantly
|
|
287
|
+
htmlEl.style.transform = `translate(${dx}px, ${dy}px)`;
|
|
288
|
+
htmlEl.style.transition = 'none';
|
|
289
|
+
// PLAY: Animate to zero (new position)
|
|
290
|
+
requestAnimationFrame(() => {
|
|
291
|
+
// Force reflow
|
|
292
|
+
// void htmlEl.offsetWidth;
|
|
293
|
+
htmlEl.style.transition = 'transform 500ms cubic-bezier(0.25, 0.8, 0.25, 1)';
|
|
294
|
+
htmlEl.style.transform = '';
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function hydrate(template, container) {
|
|
302
|
+
// In a string-based framework, hydration is often just "take over".
|
|
303
|
+
// For now, we'll verify if the server content matches (simple check)
|
|
304
|
+
// and then assume control. In a more advanced version, we'd attach listeners without re-rendering.
|
|
305
|
+
if (container.innerHTML.trim() !== template.trim()) {
|
|
306
|
+
console.warn('Hydration Mismatch: Server rendered content differs from Client.');
|
|
307
|
+
container.innerHTML = template; // Fallback to full render
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
// console.log('Hydration Successful.');
|
|
311
|
+
}
|
|
312
|
+
// Future: Attach event listeners here if we had a mechanism for it.
|
|
313
|
+
}
|
|
314
|
+
function renderToString(template) {
|
|
315
|
+
// SSR Function: returns the HTML string for the server to send.
|
|
316
|
+
// Can include additional sanitization or metadata injection here.
|
|
317
|
+
return template;
|
|
318
|
+
}
|
|
319
|
+
function sanitize(str) {
|
|
320
|
+
// Check if we are in a browser environment
|
|
321
|
+
if (typeof document !== 'undefined') {
|
|
322
|
+
const temp = document.createElement('div');
|
|
323
|
+
temp.textContent = str;
|
|
324
|
+
return temp.innerHTML;
|
|
325
|
+
}
|
|
326
|
+
// Simple SSR fallback sanitizer (rudimentary)
|
|
327
|
+
return str.replace(/&/g, "&")
|
|
328
|
+
.replace(/</g, "<")
|
|
329
|
+
.replace(/>/g, ">")
|
|
330
|
+
.replace(/"/g, """)
|
|
331
|
+
.replace(/'/g, "'");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
;// ./src/core/vault.ts
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Mulan Vault: The World's First Native Persistent State Primitive.
|
|
339
|
+
*/
|
|
340
|
+
function persistent(key, initialValue, options = {}) {
|
|
341
|
+
const storage = options.storage || window.localStorage;
|
|
342
|
+
// 1. Load from Storage
|
|
343
|
+
const stored = storage.getItem(key);
|
|
344
|
+
let startVal = initialValue;
|
|
345
|
+
if (stored) {
|
|
346
|
+
try {
|
|
347
|
+
startVal = JSON.parse(stored);
|
|
348
|
+
}
|
|
349
|
+
catch (e) {
|
|
350
|
+
console.warn(`[Mulan Vault] Corrupt persistent data for key "${key}", resetting.`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// 2. Create Reactive State (Follow muState pattern for consistency)
|
|
354
|
+
const isObject = typeof startVal === 'object' && startVal !== null;
|
|
355
|
+
const state = isObject ? reactive(startVal) : reactive({ value: startVal });
|
|
356
|
+
// 3. Auto-Save on Change
|
|
357
|
+
muEffect(() => {
|
|
358
|
+
try {
|
|
359
|
+
const payload = isObject ? state : state.value;
|
|
360
|
+
const toSave = JSON.stringify(payload);
|
|
361
|
+
// Non-obfuscated persistence to satisfy security audits
|
|
362
|
+
storage.setItem(key, toSave);
|
|
363
|
+
}
|
|
364
|
+
catch (e) {
|
|
365
|
+
console.error(`[Mulan Vault] Failed to save key "${key}"`);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
// 4. Sync across Tabs
|
|
369
|
+
const sync = (e) => {
|
|
370
|
+
if (e.key === key && e.newValue) {
|
|
371
|
+
try {
|
|
372
|
+
const newVal = JSON.parse(e.newValue);
|
|
373
|
+
if (isObject) {
|
|
374
|
+
Object.assign(state, newVal);
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
state.value = newVal;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
catch (e) { }
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
window.addEventListener('storage', sync);
|
|
384
|
+
// Explicit cleanup if provided by the environment (e.g. Mulan Hooks)
|
|
385
|
+
if (options.onCleanup) {
|
|
386
|
+
options.onCleanup(() => {
|
|
387
|
+
window.removeEventListener('storage', sync);
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
return state;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
;// ./src/core/hooks.ts
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
// Global context to track the current component instance
|
|
397
|
+
let currentInstance = null;
|
|
398
|
+
function setCurrentInstance(instance) {
|
|
399
|
+
currentInstance = instance;
|
|
400
|
+
}
|
|
401
|
+
function getCurrentInstance() {
|
|
402
|
+
return currentInstance;
|
|
403
|
+
}
|
|
404
|
+
// --- Mulan Unique Reactivity Hooks ---
|
|
405
|
+
function muState(initialValue) {
|
|
406
|
+
if (typeof initialValue === 'object' && initialValue !== null) {
|
|
407
|
+
return reactive(initialValue);
|
|
408
|
+
}
|
|
409
|
+
// Core reactive state container for primitives
|
|
410
|
+
return reactive({ value: initialValue });
|
|
411
|
+
}
|
|
412
|
+
function muMemo(computeFn) {
|
|
413
|
+
const signal = reactive({ value: undefined });
|
|
414
|
+
const stop = effect(() => {
|
|
415
|
+
signal.value = computeFn();
|
|
416
|
+
});
|
|
417
|
+
const instance = getCurrentInstance();
|
|
418
|
+
if (instance) {
|
|
419
|
+
if (!instance._effects)
|
|
420
|
+
instance._effects = [];
|
|
421
|
+
instance._effects.push(stop);
|
|
422
|
+
}
|
|
423
|
+
return signal;
|
|
424
|
+
}
|
|
425
|
+
function muEffect(fn) {
|
|
426
|
+
const stop = effect(fn);
|
|
427
|
+
const instance = getCurrentInstance();
|
|
428
|
+
if (instance) {
|
|
429
|
+
if (!instance._effects)
|
|
430
|
+
instance._effects = [];
|
|
431
|
+
instance._effects.push(stop);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
// --- The "Mulan Cycle" (Lifecycle) ---
|
|
435
|
+
function onMuInit(fn) {
|
|
436
|
+
const instance = getCurrentInstance();
|
|
437
|
+
if (instance) {
|
|
438
|
+
if (!instance._hooks)
|
|
439
|
+
instance._hooks = {};
|
|
440
|
+
if (!instance._hooks.onMuInit)
|
|
441
|
+
instance._hooks.onMuInit = [];
|
|
442
|
+
instance._hooks.onMuInit.push(fn);
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
console.warn('onMuInit called outside of component setup context.');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function onMuMount(fn) {
|
|
449
|
+
// New hook for when component is actually in DOM (simulated for now via update)
|
|
450
|
+
const instance = getCurrentInstance();
|
|
451
|
+
if (instance) {
|
|
452
|
+
if (!instance._hooks)
|
|
453
|
+
instance._hooks = {};
|
|
454
|
+
if (!instance._hooks.onMuMount)
|
|
455
|
+
instance._hooks.onMuMount = [];
|
|
456
|
+
instance._hooks.onMuMount.push(fn);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
function onMuDestroy(fn) {
|
|
460
|
+
const instance = getCurrentInstance();
|
|
461
|
+
if (instance) {
|
|
462
|
+
if (!instance._hooks)
|
|
463
|
+
instance._hooks = {};
|
|
464
|
+
if (!instance._hooks.onMuDestroy)
|
|
465
|
+
instance._hooks.onMuDestroy = [];
|
|
466
|
+
instance._hooks.onMuDestroy.push(fn);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* onMuIdle - The "Environment Life" Hook.
|
|
471
|
+
* Executes heavy logic ONLY when the browser is taking a nap (idle).
|
|
472
|
+
*/
|
|
473
|
+
function onMuIdle(fn) {
|
|
474
|
+
const instance = getCurrentInstance();
|
|
475
|
+
// Polyfill for Safari/Old Browsers
|
|
476
|
+
const requestIdleCallback = window.requestIdleCallback || function (cb) {
|
|
477
|
+
return setTimeout(() => {
|
|
478
|
+
cb({
|
|
479
|
+
didTimeout: false,
|
|
480
|
+
timeRemaining: function () { return 50; }
|
|
481
|
+
});
|
|
482
|
+
}, 1);
|
|
483
|
+
};
|
|
484
|
+
const cancelIdleCallback = window.cancelIdleCallback || function (id) {
|
|
485
|
+
clearTimeout(id);
|
|
486
|
+
};
|
|
487
|
+
const idleId = requestIdleCallback(() => {
|
|
488
|
+
fn();
|
|
489
|
+
});
|
|
490
|
+
// Auto-cleanup if component dies before idle time
|
|
491
|
+
if (instance) {
|
|
492
|
+
onMuDestroy(() => {
|
|
493
|
+
cancelIdleCallback(idleId);
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* onMuResume - The "Tab Life" Hook.
|
|
499
|
+
* Executes when the user switches BACK to this tab.
|
|
500
|
+
* Perfect for refreshing data or resuming animations to save battery.
|
|
501
|
+
*/
|
|
502
|
+
function onMuResume(fn) {
|
|
503
|
+
const handler = () => {
|
|
504
|
+
if (document.visibilityState === 'visible') {
|
|
505
|
+
fn();
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
document.addEventListener('visibilitychange', handler);
|
|
509
|
+
onMuDestroy(() => document.removeEventListener('visibilitychange', handler));
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* onMuShake - The "Physical Life" Hook.
|
|
513
|
+
* Executes when the device is shaken.
|
|
514
|
+
* Usage: Undo, Refresh, or "Rage Quit" easter eggs.
|
|
515
|
+
*/
|
|
516
|
+
function onMuShake(fn) {
|
|
517
|
+
// Threshold for shake detection
|
|
518
|
+
const threshold = 15;
|
|
519
|
+
let lastX = 0, lastY = 0, lastZ = 0;
|
|
520
|
+
let lastTime = 0;
|
|
521
|
+
const handler = (e) => {
|
|
522
|
+
const current = e.accelerationIncludingGravity;
|
|
523
|
+
if (!current)
|
|
524
|
+
return;
|
|
525
|
+
const time = Date.now();
|
|
526
|
+
if ((time - lastTime) > 100) {
|
|
527
|
+
const diffTime = time - lastTime;
|
|
528
|
+
lastTime = time;
|
|
529
|
+
const x = current.x || 0;
|
|
530
|
+
const y = current.y || 0;
|
|
531
|
+
const z = current.z || 0;
|
|
532
|
+
const speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
|
|
533
|
+
if (speed > threshold) {
|
|
534
|
+
fn();
|
|
535
|
+
}
|
|
536
|
+
lastX = x;
|
|
537
|
+
lastY = y;
|
|
538
|
+
lastZ = z;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
if (window.DeviceMotionEvent) {
|
|
542
|
+
window.addEventListener('devicemotion', handler);
|
|
543
|
+
onMuDestroy(() => window.removeEventListener('devicemotion', handler));
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
console.warn("[MulanJS] Device Motion not supported on this device.");
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* onMuVoice - The "Sound Life" Hook.
|
|
551
|
+
* Executes when a specific word is spoken.
|
|
552
|
+
* @param command The word to listen for (e.g., "save", "next")
|
|
553
|
+
* @param fn The action to take
|
|
554
|
+
*/
|
|
555
|
+
function onMuVoice(command, fn) {
|
|
556
|
+
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
557
|
+
if (!SpeechRecognition) {
|
|
558
|
+
console.warn("[MulanJS] Voice Control (Web Speech API) not supported in this browser.");
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const recognition = new SpeechRecognition();
|
|
562
|
+
recognition.continuous = true;
|
|
563
|
+
recognition.lang = 'en-US';
|
|
564
|
+
recognition.interimResults = false;
|
|
565
|
+
recognition.onresult = (event) => {
|
|
566
|
+
const last = event.results.length - 1;
|
|
567
|
+
const spoken = event.results[last][0].transcript.trim().toLowerCase();
|
|
568
|
+
console.log(`[Mulan Voice] Heard: "${spoken}"`);
|
|
569
|
+
if (spoken.includes(command.toLowerCase())) {
|
|
570
|
+
fn();
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
recognition.start();
|
|
574
|
+
// Auto-restart if it stops (Continuous listening)
|
|
575
|
+
recognition.onend = () => {
|
|
576
|
+
// Simple check to see if we should still be listening
|
|
577
|
+
// In a real app we might want more control
|
|
578
|
+
// recognition.start();
|
|
579
|
+
};
|
|
580
|
+
onMuDestroy(() => {
|
|
581
|
+
recognition.stop();
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
// --- "Outside The Box" Hooks (Mulan Exclusives) ---
|
|
585
|
+
/**
|
|
586
|
+
* muGeom - Tracks window or element dimensions reactively.
|
|
587
|
+
*/
|
|
588
|
+
function muGeom() {
|
|
589
|
+
const dims = muState({ width: window.innerWidth, height: window.innerHeight });
|
|
590
|
+
const handler = () => {
|
|
591
|
+
dims.width = window.innerWidth;
|
|
592
|
+
dims.height = window.innerHeight;
|
|
593
|
+
};
|
|
594
|
+
window.addEventListener('resize', handler);
|
|
595
|
+
// Auto-cleanup
|
|
596
|
+
onMuDestroy(() => {
|
|
597
|
+
window.removeEventListener('resize', handler);
|
|
598
|
+
});
|
|
599
|
+
return dims;
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* muPulse - Reactive network status.
|
|
603
|
+
*/
|
|
604
|
+
function muPulse() {
|
|
605
|
+
const status = muState({ online: navigator.onLine });
|
|
606
|
+
const setOnline = () => status.online = true;
|
|
607
|
+
const setOffline = () => status.online = false;
|
|
608
|
+
window.addEventListener('online', setOnline);
|
|
609
|
+
window.addEventListener('offline', setOffline);
|
|
610
|
+
onMuDestroy(() => {
|
|
611
|
+
window.removeEventListener('online', setOnline);
|
|
612
|
+
window.removeEventListener('offline', setOffline);
|
|
613
|
+
});
|
|
614
|
+
return status;
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* muVault - Secure reactive LocalStorage wrapper.
|
|
618
|
+
* Powered by the Iron Fortress persistent primitive.
|
|
619
|
+
*/
|
|
620
|
+
function muVault(key, initial, options = {}) {
|
|
621
|
+
return persistent(key, initial, Object.assign(Object.assign({}, options), { onCleanup: (fn) => onMuDestroy(fn) }));
|
|
622
|
+
}
|
|
22
623
|
|
|
23
|
-
|
|
24
|
-
/*!****************************************!*\
|
|
25
|
-
!*** ./src/components/bloch-sphere.ts ***!
|
|
26
|
-
\****************************************/
|
|
27
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
624
|
+
;// ./src/core/component.ts
|
|
28
625
|
|
|
29
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MuBlochSphereElement: () => (/* binding */ MuBlochSphereElement)\n/* harmony export */ });\n/* harmony import */ var _core_reactive__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/reactive */ \"./src/core/reactive.ts\");\n\nclass MuBlochSphereElement extends HTMLElement {\n static get observedAttributes() {\n return ['size'];\n }\n constructor() {\n super();\n this._arrow = null;\n this._container = null;\n this._disposeEffect = null;\n this.attachShadow({ mode: 'open' });\n }\n connectedCallback() {\n this.render();\n }\n disconnectedCallback() {\n if (this._disposeEffect) {\n this._disposeEffect();\n this._disposeEffect = null;\n }\n }\n // Property setter for 'qubit' (passed as .qubit=\"${q}\" in Mulan)\n set qubit(val) {\n this._qubit = val;\n this.initReactivity();\n }\n get qubit() {\n return this._qubit;\n }\n attributeChangedCallback(name, oldValue, newValue) {\n if (name === 'size' && this._container) {\n this._container.style.width = newValue + 'px';\n this._container.style.height = newValue + 'px';\n }\n }\n initReactivity() {\n if (this._disposeEffect)\n this._disposeEffect();\n if (!this._qubit)\n return;\n // MulanJS Effect: Run whenever the qubit state changes\n this._disposeEffect = (0,_core_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(() => {\n const state = this._qubit.value; // Access reactive proxy\n if (!state || !state.amplitudes)\n return;\n // Assume Single Qubit for Visualizer (Index 0 if passed a register)\n // If passed a register, we visualize the first qubit's logical projection (partial trace simplified)\n // Or assume input IS a specific qubit projection?\n // For simplified demo, we assume the register is size 1 OR we visualize Q0 of the register.\n const amps = state.amplitudes;\n // Support 1-qubit visualization from N-qubit register requires partial trace.\n // For now, let's assume the user passes a 1-qubit register OR we visualize index 0.\n // |psi> = a|0> + b|1>\n // a = amps[0] (re, im)\n // b = amps[1] (re, im)\n // Dealing with multi-qubit registers (naive projection for visualization):\n // We sum up probabilities for 0xxxx vs 1xxxx to get Z-axis.\n // This is \"marginal probability\".\n let p0 = 0;\n let p1 = 0;\n // Calculate Probabilities\n for (let i = 0; i < amps.length; i++) {\n const mag = amps[i].re * amps[i].re + amps[i].im * amps[i].im;\n if ((i & 1) === 0)\n p0 += mag;\n else\n p1 += mag;\n }\n // Theta from Z-projection\n // P0 = cos^2(theta/2) -> theta = 2 * acos(sqrt(P0))\n const theta = 2 * Math.acos(Math.min(1, Math.sqrt(p0)));\n // Phi?\n // Phase is relative phase between |0> and |1>.\n // We can look at the phase of the '1' component relative to '0'.\n // Simple approach: Look at amps[1] phase vs amps[0] phase.\n // But with entanglement, pure state phase is tricky.\n // Let's implement full density matrix if needed, but for now:\n // naive: atan2(amps[1].im, amps[1].re) - atan2(amps[0].im, amps[0].re)\n // We use the first pair (0 and 1) as proxy if multiple.\n const a0 = amps[0];\n const a1 = amps[1]; // Valid for N>=1\n const phase0 = Math.atan2(a0.im, a0.re);\n const phase1 = Math.atan2(a1.im, a1.re);\n let phi = phase1 - phase0;\n // Update Arrow\n this.updateArrow(theta, phi);\n });\n }\n updateArrow(theta, phi) {\n if (!this._arrow)\n return;\n // Convert Quantum Coords (Theta, Phi) to CSS Transforms\n // Theta 0 = Top (|0>)\n // Theta PI = Bottom (|1>)\n // Theta PI/2 = Equator\n // CSS Rotate sequence:\n // 1. Start pointing UP (Y or Z axis in CSS?)\n // Let's say Arrow starts pointing UP (Y-).\n // Rotate Z by Phi (Azimuth)\n // Rotate X by Theta (Polar) - No, that's not standard Euler.\n // Standard Physics:\n // Z is Up (in Bloch), but CSS 3D Y is usually 'Down' or 'Up'.\n // Let's Map:\n // Bloch Z+ (|0>) -> CSS Y- (Top)\n // Bloch Z- (|1>) -> CSS Y+ (Bottom)\n // Bloch X+ (|+>) -> CSS Z+ (Front)\n // Transform:\n // rotateY(phi) ? No, phi rotates around Z-axis (Vertical).\n // theta rotates from Z-axis down.\n // CSS:\n // rotateY(phi) -> Rotates around Vertical axis.\n // rotateZ(theta) -> Rotates \"down\" from up?\n // Let's simplify:\n // transform: rotateY(${phi}rad) rotateZ(${theta}rad)\n // Note: CSS rotations order matters.\n const degTheta = theta * (180 / Math.PI);\n const degPhi = phi * (180 / Math.PI);\n // Adjustment for visual alignment\n this._arrow.style.transform = `rotateY(${degPhi}deg) rotateZ(${degTheta}deg)`;\n // Color based on state\n const isSuperposition = Math.abs(theta - Math.PI / 2) < 0.1;\n this._arrow.style.backgroundColor = isSuperposition ? '#00ffff' : '#ff00ff';\n }\n render() {\n if (!this.shadowRoot)\n return;\n const size = this.getAttribute('size') || '200';\n this.shadowRoot.innerHTML = `\r\n <style>\r\n :host {\r\n display: inline-block;\r\n perspective: 1000px;\r\n }\r\n .sphere-container {\r\n width: ${size}px;\r\n height: ${size}px;\r\n position: relative;\r\n transform-style: preserve-3d;\r\n margin: 0 auto;\r\n }\r\n .sphere {\r\n width: 100%;\r\n height: 100%;\r\n border-radius: 50%;\r\n border: 1px solid rgba(255, 255, 255, 0.2);\r\n position: absolute;\r\n background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.1), rgba(0, 0, 0, 0.8));\r\n box-shadow: inset 0 0 20px rgba(255, 255, 255, 0.05);\r\n transform: rotateX(15deg) rotateY(15deg); /* Initial tilt for view */\r\n }\r\n /* Equator Ring */\r\n .equator {\r\n position: absolute;\r\n top: 50%;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n border: 1px dashed rgba(255, 255, 255, 0.3);\r\n border-radius: 50%;\r\n transform: rotateX(90deg);\r\n pointer-events: none;\r\n }\r\n /* Axis Lines */\r\n .axis {\r\n position: absolute;\r\n background: rgba(255, 255, 255, 0.1);\r\n }\r\n .z-axis { width: 2px; height: 100%; left: 50%; top: 0; }\r\n \r\n /* The Quantum Arrow */\r\n .arrow-container {\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n width: 0;\r\n height: 0;\r\n transform-style: preserve-3d;\r\n transform: rotateX(15deg) rotateY(15deg); /* Match sphere tilt */\r\n }\r\n \r\n .arrow-pivot {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 4px;\r\n height: 50%; /* Length of radius */\r\n /* Pivot logic: we want to rotate around the center point */\r\n /* CSS Default transform-origin is 50% 50% */\r\n /* We construct the arrow such that it points UP from center */\r\n }\r\n \r\n .arrow-rod {\r\n width: 4px;\r\n height: ${parseInt(size) / 2 - 10}px;\r\n background: #ff00ff;\r\n position: absolute;\r\n bottom: 0;\r\n left: -2px;\r\n transform-origin: bottom center;\r\n transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), background-color 0.3s;\r\n border-radius: 2px;\r\n box-shadow: 0 0 10px currentColor;\r\n }\r\n \r\n .arrow-head {\r\n width: 0; \r\n height: 0; \r\n border-left: 6px solid transparent;\r\n border-right: 6px solid transparent;\r\n border-bottom: 12px solid #ff00ff;\r\n position: absolute;\r\n top: -10px;\r\n left: -6px;\r\n }\r\n \r\n .label {\r\n position: absolute;\r\n color: #aaa;\r\n font-family: monospace;\r\n font-size: 10px;\r\n }\r\n .label-0 { top: 5px; left: 50%; transform: translateX(-50%); }\r\n .label-1 { bottom: 5px; left: 50%; transform: translateX(-50%); }\r\n </style>\r\n \r\n <div class=\"sphere-container\">\r\n <div class=\"sphere\">\r\n <div class=\"equator\"></div>\r\n <div class=\"axis z-axis\"></div>\r\n <div class=\"label label-0\">|0></div>\r\n <div class=\"label label-1\">|1></div>\r\n </div>\r\n \r\n <div class=\"arrow-container\">\r\n <!-- The rod is the actual rotating element -->\r\n <div class=\"arrow-rod\">\r\n <div class=\"arrow-head\"></div>\r\n </div>\r\n </div>\r\n </div>\r\n `;\n this._container = this.shadowRoot.querySelector('.sphere-container');\n this._arrow = this.shadowRoot.querySelector('.arrow-rod');\n // Re-init reactivity if qubit was set before render\n if (this._qubit)\n this.initReactivity();\n }\n}\n// Register the custom element\nif (typeof customElements !== 'undefined') {\n customElements.define('mu-bloch-sphere', MuBlochSphereElement);\n}\n\n\n//# sourceURL=webpack://Mulan/./src/components/bloch-sphere.ts?\n}");
|
|
30
626
|
|
|
31
|
-
/***/ },
|
|
32
627
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
628
|
+
// Or a simple component that returns an object of state/methods used by template?
|
|
629
|
+
// For Mulan 2.0, let's say functional component returns a template string render function explicitly.
|
|
630
|
+
class MuComponent {
|
|
631
|
+
constructor(container) {
|
|
632
|
+
this._hooks = {};
|
|
633
|
+
this._effects = [];
|
|
634
|
+
this._isDestroyed = false;
|
|
635
|
+
this._propsQueue = [];
|
|
636
|
+
this._eventQueue = [];
|
|
637
|
+
this.container = container;
|
|
638
|
+
this.state = {};
|
|
639
|
+
this.$uid = 'mu_' + Math.random().toString(36).substr(2, 9);
|
|
640
|
+
// MULAN INSIGHT: Global Registry for Debugging
|
|
641
|
+
if (typeof window !== 'undefined') {
|
|
642
|
+
const global = window;
|
|
643
|
+
global.__MULAN_INSIGHT__ = global.__MULAN_INSIGHT__ || { components: new Map() };
|
|
644
|
+
global.__MULAN_INSIGHT__.components.set(this.$uid, this);
|
|
645
|
+
}
|
|
646
|
+
// Setup context for hooks
|
|
647
|
+
setCurrentInstance(this);
|
|
648
|
+
this.setup();
|
|
649
|
+
setCurrentInstance(null);
|
|
650
|
+
}
|
|
651
|
+
// Optional setup method for class components wanting to use hooks
|
|
652
|
+
setup() { }
|
|
653
|
+
onMount() {
|
|
654
|
+
var _a, _c;
|
|
655
|
+
// Mulan Cycle: Init
|
|
656
|
+
(_a = this._hooks.onMuInit) === null || _a === void 0 ? void 0 : _a.forEach(fn => fn());
|
|
657
|
+
// Mulan Cycle: Mount (Simulated immediately after init for now in this version)
|
|
658
|
+
(_c = this._hooks.onMuMount) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
|
|
659
|
+
}
|
|
660
|
+
onUpdate() { }
|
|
661
|
+
onDestroy() {
|
|
662
|
+
var _a, _c;
|
|
663
|
+
if (this._isDestroyed)
|
|
664
|
+
return;
|
|
665
|
+
this._isDestroyed = true;
|
|
666
|
+
console.log(`[Mulan Cycle] Destroying component ${this.$uid} (${this.constructor.name})`);
|
|
667
|
+
// MULAN INSIGHT: Cleanup
|
|
668
|
+
if (typeof window !== 'undefined') {
|
|
669
|
+
const global = window;
|
|
670
|
+
(_a = global.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components.delete(this.$uid);
|
|
671
|
+
}
|
|
672
|
+
// Mulan Cycle: Stop all effects to prevent leaks
|
|
673
|
+
console.log(`[Mulan Cycle] Stopping ${this._effects.length} effects for ${this.$uid}`);
|
|
674
|
+
this._effects.forEach(stop => stop());
|
|
675
|
+
this._effects = [];
|
|
676
|
+
// Mulan Cycle: Destroy hooks
|
|
677
|
+
(_c = this._hooks.onMuDestroy) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());
|
|
678
|
+
}
|
|
679
|
+
// Helper for compiler to register property bindings
|
|
680
|
+
_b(id, prop, value) {
|
|
681
|
+
this._propsQueue.push([id, prop, value]);
|
|
682
|
+
return "";
|
|
683
|
+
}
|
|
684
|
+
// Helper for compiler to register event bindings
|
|
685
|
+
_e(id, type, handler) {
|
|
686
|
+
this._eventQueue.push([id, type, handler]);
|
|
687
|
+
return "";
|
|
688
|
+
}
|
|
689
|
+
mount() {
|
|
690
|
+
console.log(`[Mulan Cycle] Mounting component ${this.$uid}`);
|
|
691
|
+
const stop = effect(() => {
|
|
692
|
+
console.log(`[Mulan Reactivity] Triggering update for ${this.$uid}`);
|
|
693
|
+
this.update();
|
|
694
|
+
});
|
|
695
|
+
this._effects.push(stop);
|
|
696
|
+
this.onMount();
|
|
697
|
+
}
|
|
698
|
+
update() {
|
|
699
|
+
if (this._isDestroyed) {
|
|
700
|
+
console.warn(`[Mulan Warning] Update called on destroyed component ${this.$uid}. Blocking render.`);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
// Clear queues before render
|
|
704
|
+
this._propsQueue = [];
|
|
705
|
+
this._eventQueue = [];
|
|
706
|
+
const template = this.template();
|
|
707
|
+
// Render HTML
|
|
708
|
+
render(template, this.container);
|
|
709
|
+
// Flush Side Effects
|
|
710
|
+
this.flushProps();
|
|
711
|
+
this.flushEvents();
|
|
712
|
+
this.onUpdate();
|
|
713
|
+
}
|
|
714
|
+
flushProps() {
|
|
715
|
+
for (const [id, prop, value] of this._propsQueue) {
|
|
716
|
+
const el = this.container.querySelector(`[data-mu-id="${id}"]`);
|
|
717
|
+
if (el) {
|
|
718
|
+
// @ts-ignore
|
|
719
|
+
el[prop] = value;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
this._propsQueue = [];
|
|
723
|
+
}
|
|
724
|
+
flushEvents() {
|
|
725
|
+
for (const [id, type, handler] of this._eventQueue) {
|
|
726
|
+
const el = this.container.querySelector(`[data-mu-id="${id}"]`);
|
|
727
|
+
if (el) {
|
|
728
|
+
// Bind handler to this component instance to ensure 'this' works in methods
|
|
729
|
+
el.addEventListener(type, handler.bind(this));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
this._eventQueue = [];
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
// Helper to create functional components wrapped in the class system
|
|
736
|
+
// Helper to create functional components wrapped in the class system
|
|
737
|
+
// Supports both () => render and { setup() } signatures
|
|
738
|
+
function defineComponent(optionsOrSetup) {
|
|
739
|
+
return class UniversalComponent extends MuComponent {
|
|
740
|
+
constructor(container) {
|
|
741
|
+
super(container);
|
|
742
|
+
// setup() is called by super constructor
|
|
743
|
+
}
|
|
744
|
+
setup() {
|
|
745
|
+
let setupResult;
|
|
746
|
+
if (typeof optionsOrSetup === 'function') {
|
|
747
|
+
// It's a setup function returning render fn
|
|
748
|
+
setupResult = optionsOrSetup.call(this);
|
|
749
|
+
}
|
|
750
|
+
else if (typeof optionsOrSetup === 'object' && optionsOrSetup.setup) {
|
|
751
|
+
// It's an options object with setup()
|
|
752
|
+
setupResult = optionsOrSetup.setup.call(this);
|
|
753
|
+
}
|
|
754
|
+
// Handle result
|
|
755
|
+
if (typeof setupResult === 'function') {
|
|
756
|
+
// It's a render function
|
|
757
|
+
this.template = setupResult;
|
|
758
|
+
}
|
|
759
|
+
else if (setupResult && typeof setupResult === 'object') {
|
|
760
|
+
// It's bindings
|
|
761
|
+
Object.assign(this, setupResult);
|
|
762
|
+
// We assume template is assigned to prototype by compiler
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
template() {
|
|
766
|
+
return '';
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
}
|
|
38
770
|
|
|
39
|
-
|
|
771
|
+
;// ./src/security/sanitizer.ts
|
|
772
|
+
class Security {
|
|
773
|
+
/**
|
|
774
|
+
* IRON FORTRESS PROTOCOL
|
|
775
|
+
* Strictly escapes all HTML entities to prevent XSS.
|
|
776
|
+
* Use `mu-raw` attribute in templates to bypass this for trusted content.
|
|
777
|
+
*/
|
|
778
|
+
static sanitize(input) {
|
|
779
|
+
// 1. Basic entity encoding
|
|
780
|
+
let secure = input
|
|
781
|
+
.replace(/&/g, "&")
|
|
782
|
+
.replace(/</g, "<")
|
|
783
|
+
.replace(/>/g, ">")
|
|
784
|
+
.replace(/"/g, """)
|
|
785
|
+
.replace(/'/g, "'");
|
|
786
|
+
// 2. Remove dangerous events (extra layer if encoding fails)
|
|
787
|
+
const dangerousEvents = ['onload', 'onclick', 'onerror', 'onmouseover', 'onfocus'];
|
|
788
|
+
dangerousEvents.forEach(event => {
|
|
789
|
+
const regex = new RegExp(event, 'gi');
|
|
790
|
+
secure = secure.replace(regex, 'data-blocked-' + event);
|
|
791
|
+
});
|
|
792
|
+
return secure;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Generates a strict Content Security Policy header value.
|
|
796
|
+
* @param options Configuration for allowed sources
|
|
797
|
+
*/
|
|
798
|
+
static generateCSP(options = {}) {
|
|
799
|
+
const scriptSrc = ["'self'", ...(options.scriptSrc || [])].join(" ");
|
|
800
|
+
const styleSrc = ["'self'", "'unsafe-inline'", ...(options.styleSrc || [])].join(" ");
|
|
801
|
+
return `default-src 'self'; script-src ${scriptSrc}; style-src ${styleSrc}; object-src 'none'; base-uri 'self';`;
|
|
802
|
+
}
|
|
803
|
+
static validateUrl(url) {
|
|
804
|
+
// Basic URL validation
|
|
805
|
+
const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
|
|
806
|
+
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
|
|
807
|
+
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
|
|
808
|
+
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
|
|
809
|
+
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
|
|
810
|
+
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
|
|
811
|
+
return !!pattern.test(url);
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Prevents XSS by sanitizing common input fields on blur.
|
|
815
|
+
* Can be used as a utility in forms.
|
|
816
|
+
*/
|
|
817
|
+
static preventXSS(inputElement) {
|
|
818
|
+
inputElement.addEventListener('blur', (e) => {
|
|
819
|
+
const target = e.target;
|
|
820
|
+
target.value = Security.sanitize(target.value);
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
40
824
|
|
|
41
|
-
|
|
825
|
+
;// ./src/router/index.ts
|
|
826
|
+
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
827
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
828
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
829
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
830
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
831
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
832
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
833
|
+
});
|
|
834
|
+
};
|
|
42
835
|
|
|
43
|
-
/***/ "./src/core/component.ts"
|
|
44
|
-
/*!*******************************!*\
|
|
45
|
-
!*** ./src/core/component.ts ***!
|
|
46
|
-
\*******************************/
|
|
47
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
48
836
|
|
|
49
|
-
|
|
837
|
+
class MuRouter {
|
|
838
|
+
constructor(routes, rootContainer = null) {
|
|
839
|
+
this.currentPath = '';
|
|
840
|
+
this.currentComponent = null;
|
|
841
|
+
this.lastRouteId = 0;
|
|
842
|
+
this.routes = routes;
|
|
843
|
+
this.rootContainer = rootContainer;
|
|
844
|
+
this.isServer = rootContainer === null; // If no container, assume server/headless mode
|
|
845
|
+
if (!this.isServer) {
|
|
846
|
+
window.addEventListener('hashchange', this.handleRoute.bind(this));
|
|
847
|
+
this.handleRoute(); // Initial load
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
// SSR Method: Simulate a route visit on the server
|
|
851
|
+
serverLookup(path) {
|
|
852
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
853
|
+
this.currentPath = path;
|
|
854
|
+
const { route, params } = this.matchRoute(path);
|
|
855
|
+
if (route) {
|
|
856
|
+
// Run guards/resolvers here if needed
|
|
857
|
+
let componentToRender = route.component;
|
|
858
|
+
// Support Lazy Loading
|
|
859
|
+
if (typeof componentToRender === 'function' && !componentToRender.prototype) {
|
|
860
|
+
const module = yield componentToRender();
|
|
861
|
+
componentToRender = module.default || module;
|
|
862
|
+
}
|
|
863
|
+
if (typeof componentToRender === 'function') {
|
|
864
|
+
// Class component SSR
|
|
865
|
+
// We need a dummy container for the component to "render" into its own buffer
|
|
866
|
+
// For simplicity in this string-based framework, we mock the container
|
|
867
|
+
const mockContainer = { innerHTML: '' };
|
|
868
|
+
const instance = new componentToRender(mockContainer);
|
|
869
|
+
if (instance.setParams)
|
|
870
|
+
instance.setParams(params);
|
|
871
|
+
// Manually trigger mount logic without DOM effects if possible, or just template()
|
|
872
|
+
// Ideally, we just want the template string.
|
|
873
|
+
return instance.template();
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
return componentToRender;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return '<!-- 404 -->';
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
matchRoute(hash) {
|
|
883
|
+
// Simple exact match first
|
|
884
|
+
let route = this.routes.find((r) => r.path === hash);
|
|
885
|
+
if (route)
|
|
886
|
+
return { route, params: {} };
|
|
887
|
+
// Regex match for params e.g. /user/:id
|
|
888
|
+
for (const r of this.routes) {
|
|
889
|
+
const paramNames = [];
|
|
890
|
+
const regexPath = r.path.replace(/:([^/]+)/g, (_, key) => {
|
|
891
|
+
paramNames.push(key);
|
|
892
|
+
return '([^/]+)';
|
|
893
|
+
});
|
|
894
|
+
const match = new RegExp(`^${regexPath}$`).exec(hash);
|
|
895
|
+
if (match) {
|
|
896
|
+
const params = {};
|
|
897
|
+
paramNames.forEach((name, i) => {
|
|
898
|
+
// SECURE: Automatically sanitize all route parameters
|
|
899
|
+
params[name] = Security.sanitize(match[i + 1]);
|
|
900
|
+
});
|
|
901
|
+
return { route: r, params };
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
return { route: undefined, params: {} };
|
|
905
|
+
}
|
|
906
|
+
handleRoute() {
|
|
907
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
908
|
+
if (this.isServer)
|
|
909
|
+
return;
|
|
910
|
+
const currentRouteId = ++this.lastRouteId;
|
|
911
|
+
const hash = window.location.hash.slice(1) || '/';
|
|
912
|
+
const { route, params } = this.matchRoute(hash);
|
|
913
|
+
// Security Check: Validate URL to prevent malicious hash injection
|
|
914
|
+
if (hash !== '/' && !Security.validateUrl('http://dummy.com' + hash)) {
|
|
915
|
+
console.error("Security Alert: Malformed URL detected.");
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
// Navigation Guard (Middleware)
|
|
919
|
+
if (route === null || route === void 0 ? void 0 : route.beforeEnter) {
|
|
920
|
+
yield new Promise((resolve) => {
|
|
921
|
+
route.beforeEnter(hash, this.currentPath, (allow) => {
|
|
922
|
+
if (allow)
|
|
923
|
+
resolve();
|
|
924
|
+
else {
|
|
925
|
+
console.warn(`Navigation to ${hash} blocked by guard.`);
|
|
926
|
+
// Ideally redirect or stay, here we just stop processing
|
|
927
|
+
throw new Error('Navigation Blocked');
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
}).catch(() => { return; }); // Stop execution if blocked
|
|
931
|
+
}
|
|
932
|
+
this.currentPath = hash;
|
|
933
|
+
if (route) {
|
|
934
|
+
if (route.title) {
|
|
935
|
+
document.title = route.title;
|
|
936
|
+
}
|
|
937
|
+
else if (route.meta && route.meta.title) {
|
|
938
|
+
// Fallback to meta.title if used
|
|
939
|
+
document.title = route.meta.title;
|
|
940
|
+
}
|
|
941
|
+
if (this.rootContainer) {
|
|
942
|
+
// Mulan Cycle: Destroy previous component before rendering new one
|
|
943
|
+
if (this.currentComponent) {
|
|
944
|
+
console.log(`[Router] Navigation from ${this.currentPath} to ${hash}. Destroying previous component.`);
|
|
945
|
+
if (this.currentComponent.onDestroy) {
|
|
946
|
+
this.currentComponent.onDestroy();
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
this.rootContainer.innerHTML = ''; // Clear previous content
|
|
950
|
+
}
|
|
951
|
+
let componentToRender = route.component;
|
|
952
|
+
// Support Lazy Loading
|
|
953
|
+
if (typeof componentToRender === 'function' && !componentToRender.prototype) {
|
|
954
|
+
try {
|
|
955
|
+
const module = yield componentToRender();
|
|
956
|
+
if (currentRouteId !== this.lastRouteId) {
|
|
957
|
+
console.log(`[Router] Navigation to ${hash} interrupted by newer navigation. Abandoning.`);
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
componentToRender = module.default || module;
|
|
961
|
+
}
|
|
962
|
+
catch (e) {
|
|
963
|
+
console.error("Failed to lazy load component", e);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
if (typeof componentToRender === 'function') {
|
|
968
|
+
// It's a class component
|
|
969
|
+
if (this.rootContainer) {
|
|
970
|
+
const instance = new componentToRender(this.rootContainer);
|
|
971
|
+
this.currentComponent = instance;
|
|
972
|
+
// Inject params if the component accepts them
|
|
973
|
+
if (instance.setParams) {
|
|
974
|
+
instance.setParams(params);
|
|
975
|
+
}
|
|
976
|
+
instance.mount();
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
else if (typeof componentToRender === 'object' && componentToRender.template) {
|
|
980
|
+
// Object Component (Simple SFC without script or Options API)
|
|
981
|
+
const html = componentToRender.template();
|
|
982
|
+
if (this.rootContainer)
|
|
983
|
+
render(html, this.rootContainer);
|
|
984
|
+
this.currentComponent = null;
|
|
985
|
+
}
|
|
986
|
+
else {
|
|
987
|
+
// Simple HTML string/template
|
|
988
|
+
if (this.rootContainer)
|
|
989
|
+
render(componentToRender, this.rootContainer);
|
|
990
|
+
this.currentComponent = null; // String templates don't have lifecycle instances
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
else {
|
|
994
|
+
if (this.rootContainer)
|
|
995
|
+
render('<div style="text-align:center; padding:50px;"><h1>404</h1><p>Page Not Found</p></div>', this.rootContainer);
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
// [Chronos] Prefetch a route's component code in the background
|
|
1000
|
+
prefetch(path) {
|
|
1001
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
1002
|
+
if (this.isServer)
|
|
1003
|
+
return;
|
|
1004
|
+
const { route } = this.matchRoute(path);
|
|
1005
|
+
if (route) {
|
|
1006
|
+
let componentToRender = route.component;
|
|
1007
|
+
// Check if it's a lazy-loaded function that hasn't been resolved yet
|
|
1008
|
+
if (typeof componentToRender === 'function' && !componentToRender.prototype) {
|
|
1009
|
+
// If it's already a resolved module (from previous prefetch), componentToRender might be the result.
|
|
1010
|
+
// But typically in our simple implementation, route.component stays as the function until we replace it.
|
|
1011
|
+
// To avoid double-fetching, we can check if it has a specific flag or property.
|
|
1012
|
+
// For this implementation, we'll just run it and let the browser cache the module request (standard ES Module behavior).
|
|
1013
|
+
try {
|
|
1014
|
+
// console.log(`[Chronos] Prefetching ${path}...`);
|
|
1015
|
+
yield componentToRender();
|
|
1016
|
+
// We don't need to do anything with the result here.
|
|
1017
|
+
// The browser's module cache will handle the speedup when the user actually navigates.
|
|
1018
|
+
}
|
|
1019
|
+
catch (e) {
|
|
1020
|
+
console.warn(`[Chronos] Failed to prefetch ${path}`, e);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
navigate(path) {
|
|
1027
|
+
if (this.isServer) {
|
|
1028
|
+
this.currentPath = path;
|
|
1029
|
+
}
|
|
1030
|
+
else {
|
|
1031
|
+
window.location.hash = path;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
// --- Factory for Easy Usage ---
|
|
1036
|
+
const createRouter = (options) => {
|
|
1037
|
+
// Expose the router instance globally for <mu-link> to access
|
|
1038
|
+
const router = new MuRouter(options.routes, options.rootContainer);
|
|
1039
|
+
if (typeof window !== 'undefined') {
|
|
1040
|
+
window.__MULAN_ROUTER__ = router;
|
|
1041
|
+
}
|
|
1042
|
+
return router;
|
|
1043
|
+
};
|
|
1044
|
+
// --- Web Component: <mu-link> ---
|
|
1045
|
+
// Usage: <mu-link to="/about">About Us</mu-link>
|
|
1046
|
+
if (typeof window !== 'undefined' && !customElements.get('mu-link')) {
|
|
1047
|
+
class MuLink extends HTMLElement {
|
|
1048
|
+
constructor() {
|
|
1049
|
+
super();
|
|
1050
|
+
this.addEventListener('click', (e) => {
|
|
1051
|
+
e.preventDefault();
|
|
1052
|
+
const to = this.getAttribute('to');
|
|
1053
|
+
if (to) {
|
|
1054
|
+
// Update Hash for SPA Navigation
|
|
1055
|
+
window.location.hash = to;
|
|
1056
|
+
}
|
|
1057
|
+
});
|
|
1058
|
+
// [Chronos] Intelligent Pre-fetching
|
|
1059
|
+
this.addEventListener('mouseenter', () => {
|
|
1060
|
+
const to = this.getAttribute('to');
|
|
1061
|
+
if (to) {
|
|
1062
|
+
const router = window.__MULAN_ROUTER__;
|
|
1063
|
+
if (router && typeof router.prefetch === 'function') {
|
|
1064
|
+
router.prefetch(to);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
// [Chronos] Also prefetch on focus for keyboard users
|
|
1069
|
+
this.addEventListener('focus', () => {
|
|
1070
|
+
const to = this.getAttribute('to');
|
|
1071
|
+
if (to) {
|
|
1072
|
+
const router = window.__MULAN_ROUTER__;
|
|
1073
|
+
if (router && typeof router.prefetch === 'function') {
|
|
1074
|
+
router.prefetch(to);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
connectedCallback() {
|
|
1080
|
+
this.style.cursor = 'pointer';
|
|
1081
|
+
this.style.color = 'var(--primary, #9C27B0)'; // Default to brand color if available
|
|
1082
|
+
this.style.textDecoration = 'none';
|
|
1083
|
+
}
|
|
1084
|
+
static get observedAttributes() { return ['to']; }
|
|
1085
|
+
}
|
|
1086
|
+
customElements.define('mu-link', MuLink);
|
|
1087
|
+
}
|
|
50
1088
|
|
|
51
|
-
|
|
1089
|
+
;// ./src/store/index.ts
|
|
52
1090
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
1091
|
+
class MuStore {
|
|
1092
|
+
constructor(initialState, options) {
|
|
1093
|
+
this.subscribers = [];
|
|
1094
|
+
// Load from local storage if persist is true
|
|
1095
|
+
let loadedState = initialState;
|
|
1096
|
+
if (options === null || options === void 0 ? void 0 : options.persist) {
|
|
1097
|
+
const key = options.key || 'mulan-store';
|
|
1098
|
+
try {
|
|
1099
|
+
const stored = localStorage.getItem(key);
|
|
1100
|
+
if (stored) {
|
|
1101
|
+
loadedState = Object.assign(Object.assign({}, initialState), JSON.parse(stored));
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
catch (e) {
|
|
1105
|
+
console.error("Failed to load state", e);
|
|
1106
|
+
}
|
|
1107
|
+
// Auto-save effect
|
|
1108
|
+
effect(() => {
|
|
1109
|
+
localStorage.setItem(key, JSON.stringify(this.state));
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
this.state = reactive(loadedState);
|
|
1113
|
+
}
|
|
1114
|
+
// Subscribe to changes
|
|
1115
|
+
subscribe(fn) {
|
|
1116
|
+
this.subscribers.push(fn);
|
|
1117
|
+
effect(() => {
|
|
1118
|
+
fn(this.state);
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
// Action dispatcher pattern
|
|
1122
|
+
dispatch(action) {
|
|
1123
|
+
const result = action(this.state);
|
|
1124
|
+
if (result instanceof Promise) {
|
|
1125
|
+
result.then(() => {
|
|
1126
|
+
// Optional: Notify subscribers of async completion if needed manually?
|
|
1127
|
+
// But reactive() handles updates automatically.
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
58
1132
|
|
|
59
|
-
|
|
1133
|
+
;// ./src/core/query.ts
|
|
1134
|
+
var query_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
1135
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
1136
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
1137
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
1138
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
1139
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
1140
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
1141
|
+
});
|
|
1142
|
+
};
|
|
60
1143
|
|
|
61
|
-
|
|
1144
|
+
function useQuery(queryFn, options = { enabled: true }) {
|
|
1145
|
+
const state = reactive({
|
|
1146
|
+
data: null,
|
|
1147
|
+
isLoading: false,
|
|
1148
|
+
error: null
|
|
1149
|
+
});
|
|
1150
|
+
const execute = () => query_awaiter(this, void 0, void 0, function* () {
|
|
1151
|
+
state.isLoading = true;
|
|
1152
|
+
state.error = null;
|
|
1153
|
+
try {
|
|
1154
|
+
const result = yield queryFn();
|
|
1155
|
+
state.data = result;
|
|
1156
|
+
}
|
|
1157
|
+
catch (err) {
|
|
1158
|
+
state.error = err;
|
|
1159
|
+
}
|
|
1160
|
+
finally {
|
|
1161
|
+
state.isLoading = false;
|
|
1162
|
+
}
|
|
1163
|
+
});
|
|
1164
|
+
if (options.enabled) {
|
|
1165
|
+
// Run automatically
|
|
1166
|
+
effect(() => {
|
|
1167
|
+
// Basic effect wrapper to allow reactivity if queryFn relies on signals
|
|
1168
|
+
execute();
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
get data() { return state.data; },
|
|
1173
|
+
get isLoading() { return state.isLoading; },
|
|
1174
|
+
get error() { return state.error; },
|
|
1175
|
+
refetch: execute
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
function useMutation(mutationFn) {
|
|
1179
|
+
const state = reactive({
|
|
1180
|
+
data: null,
|
|
1181
|
+
isLoading: false,
|
|
1182
|
+
error: null
|
|
1183
|
+
});
|
|
1184
|
+
const mutate = (args) => query_awaiter(this, void 0, void 0, function* () {
|
|
1185
|
+
state.isLoading = true;
|
|
1186
|
+
state.error = null;
|
|
1187
|
+
try {
|
|
1188
|
+
const result = yield mutationFn(args);
|
|
1189
|
+
state.data = result;
|
|
1190
|
+
return result;
|
|
1191
|
+
}
|
|
1192
|
+
catch (err) {
|
|
1193
|
+
state.error = err;
|
|
1194
|
+
throw err;
|
|
1195
|
+
}
|
|
1196
|
+
finally {
|
|
1197
|
+
state.isLoading = false;
|
|
1198
|
+
}
|
|
1199
|
+
});
|
|
1200
|
+
return {
|
|
1201
|
+
get data() { return state.data; },
|
|
1202
|
+
get isLoading() { return state.isLoading; },
|
|
1203
|
+
get error() { return state.error; },
|
|
1204
|
+
mutate
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
62
1207
|
|
|
63
|
-
|
|
64
|
-
/*!*****************************!*\
|
|
65
|
-
!*** ./src/core/quantum.ts ***!
|
|
66
|
-
\*****************************/
|
|
67
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
1208
|
+
;// ./src/core/quantum.ts
|
|
68
1209
|
|
|
69
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ activeControls: () => (/* binding */ activeControls),\n/* harmony export */ muControl: () => (/* binding */ muControl),\n/* harmony export */ muEntangle: () => (/* binding */ muEntangle),\n/* harmony export */ muGate: () => (/* binding */ muGate),\n/* harmony export */ muMeasure: () => (/* binding */ muMeasure),\n/* harmony export */ muParallel: () => (/* binding */ muParallel),\n/* harmony export */ muQubit: () => (/* binding */ muQubit),\n/* harmony export */ muRegister: () => (/* binding */ muRegister),\n/* harmony export */ muSearch: () => (/* binding */ muSearch),\n/* harmony export */ muSwitch: () => (/* binding */ muSwitch),\n/* harmony export */ muTeleport: () => (/* binding */ muTeleport)\n/* harmony export */ });\n/* harmony import */ var _hooks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hooks */ \"./src/core/hooks.ts\");\n\n/**\n * Mulan Quantum (ASTR-Q+) Core\n * Advanced Simulation Engine for multi-qubit registers and entanglement.\n */\n// -- GLOBAL CONTEXT FOR QUANTUM CONTROL --\n// Defined at top to ensure visibility for muGate\nlet activeControls = [];\n/**\n * Creates a quantum register of size n.\n * State vector will have 2^n amplitudes.\n */\nfunction muRegister(n) {\n const numStates = Math.pow(2, n);\n const amplitudes = new Array(numStates).fill(0).map((_, i) => ({\n re: i === 0 ? 1 : 0,\n im: 0\n }));\n return (0,_hooks__WEBPACK_IMPORTED_MODULE_0__.muState)({\n value: {\n size: n,\n amplitudes\n }\n });\n}\n/**\n * Backward compatible muQubit (Single Qubit Register)\n */\nfunction muQubit(initial = 0) {\n const q = muRegister(1);\n if (initial === 1) {\n muGate(q, 'X', 0);\n }\n // Add compatibility properties for Phase 1 components\n // These properties are getters that dynamically access the amplitudes array\n Object.defineProperty(q.value, 'alpha', { get: () => q.value.amplitudes[0] });\n Object.defineProperty(q.value, 'beta', { get: () => q.value.amplitudes[1] });\n return q;\n}\n/**\n * Internal helper to update register state while maintaining compatibility\n */\nfunction updateState(reg, newState) {\n if (newState.size === 1) {\n // Re-inject compatibility getters for muQubit users\n Object.defineProperty(newState, 'alpha', {\n get: () => newState.amplitudes[0],\n configurable: true,\n enumerable: true\n });\n Object.defineProperty(newState, 'beta', {\n get: () => newState.amplitudes[1],\n configurable: true,\n enumerable: true\n });\n }\n reg.value = newState;\n}\nfunction muGate(reg, type, target = 0, control) {\n const state = reg.value;\n const n = state.size;\n const amplitudes = state.amplitudes;\n const newAmps = amplitudes.map(a => (Object.assign({}, a)));\n // Prepare Effective Control (Explicit Arguments + Global Context)\n const effectiveControl = [...(control === undefined ? [] : (Array.isArray(control) ? control : [control])), ...activeControls];\n // Helper: Check if all control bits are 1\n const checkControl = (index, ctrl) => {\n if (ctrl === undefined || (Array.isArray(ctrl) && ctrl.length === 0))\n return true;\n const ctrls = Array.isArray(ctrl) ? ctrl : [ctrl];\n return ctrls.every(c => ((index >> c) & 1) === 1);\n };\n // SWAP Gate (Unique case: affects 2 targets)\n if (type === 'SWAP') {\n const t1 = target;\n const t2 = control; // SWAP uses control arg as second target \n // Iterate only half to avoid double swapping\n for (let i = 0; i < amplitudes.length; i++) {\n // Check active controls for SWAP too\n if (activeControls.length > 0 && !checkControl(i, activeControls))\n continue;\n const bit1 = (i >> t1) & 1;\n const bit2 = (i >> t2) & 1;\n if (bit1 !== bit2) {\n // Determine the swap partner index\n // If i has (0,1), partner has (1,0) at those positions\n const partner = i ^ (1 << t1) ^ (1 << t2);\n if (i < partner) {\n const temp = newAmps[i];\n newAmps[i] = newAmps[partner];\n newAmps[partner] = temp;\n }\n }\n }\n updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));\n return;\n }\n // Standard Single-Qubit & Controlled Gates\n if (type === 'H') {\n const s = 1 / Math.sqrt(2);\n const processed = new Set();\n for (let i = 0; i < state.amplitudes.length; i++) {\n if (processed.has(i))\n continue;\n // Check Controls first\n if (!checkControl(i, effectiveControl))\n continue;\n const targetBit = (i >> target) & 1;\n const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));\n const a = state.amplitudes[i];\n const b = state.amplitudes[pairedIndex];\n if (targetBit === 0) {\n newAmps[i] = { re: s * (a.re + b.re), im: s * (a.im + b.im) };\n newAmps[pairedIndex] = { re: s * (a.re - b.re), im: s * (a.im - b.im) };\n }\n else {\n newAmps[pairedIndex] = { re: s * (b.re + a.re), im: s * (b.im + a.im) };\n newAmps[i] = { re: s * (b.re - a.re), im: s * (b.im - a.im) };\n }\n processed.add(i);\n processed.add(pairedIndex);\n }\n }\n else if (type === 'X' || type === 'CNOT') {\n // CNOT is just Controlled-X\n for (let i = 0; i < amplitudes.length; i++) {\n if (!checkControl(i, effectiveControl))\n continue;\n const targetBit = (i >> target) & 1;\n const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));\n if (i < pairedIndex) {\n const temp = newAmps[i];\n newAmps[i] = newAmps[pairedIndex];\n newAmps[pairedIndex] = temp;\n }\n }\n }\n else if (type === 'Z' || type === 'CZ') {\n // Z and CZ are Phase Flips\n for (let i = 0; i < amplitudes.length; i++) {\n if (!checkControl(i, effectiveControl))\n continue;\n const targetBit = (i >> target) & 1;\n // Z Gate acts on |1>\n if (targetBit === 1) {\n newAmps[i] = { re: -amplitudes[i].re, im: -amplitudes[i].im };\n }\n }\n }\n else if (type === 'Y') {\n // Y: |0> -> i|1>, |1> -> -i|0>\n for (let i = 0; i < amplitudes.length; i++) {\n if (!checkControl(i, effectiveControl))\n continue;\n const targetBit = (i >> target) & 1;\n const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));\n if (i < pairedIndex) {\n // We process pairs (i, pairedIndex) where i has 0 at target, paired has 1\n const a = newAmps[i]; // Coeff of |0>\n const b = newAmps[pairedIndex]; // Coeff of |1>\n // New |0> = -i * Old |1>\n newAmps[i] = { re: b.im, im: -b.re };\n // New |1> = i * Old |0>\n newAmps[pairedIndex] = { re: -a.im, im: a.re };\n }\n }\n }\n updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));\n}\n/**\n * Mulan Search Logic (Grover's Operator)\n * Automatically constructs a multi-controlled Phase Flip (Z) for a specific target state.\n * This is the core of the \"Quantum Switch\" or \"Quantum Search\" capability.\n * @param reg Quantum Register\n * @param targetState The integer state to \"search\" and mark (e.g. 2 for |10>)\n */\nfunction muSearch(reg, targetState) {\n const n = reg.value.size;\n const controls = [];\n // 1. Identify which bits are 0 and need wrapping with X gates\n // Logic: To mark |010>, we want C-C-Z to trigger on 111.\n // So we apply X to bits that are 0, then C-C-Z, then X again.\n // We treat the last bit as the 'target' for the Z gate, rest as controls\n const targetQubit = n - 1;\n for (let i = 0; i < n; i++) {\n const bit = (targetState >> i) & 1;\n if (i === targetQubit) {\n // If target bit logic requires 0, we flip it to 1 for the Z gate to work\n if (bit === 0)\n muGate(reg, 'X', i);\n }\n else {\n controls.push(i);\n if (bit === 0)\n muGate(reg, 'X', i);\n }\n }\n // 2. Apply Multi-Controlled Z\n muGate(reg, 'Z', targetQubit, controls);\n // 3. Uncompute (Restore 0s)\n for (let i = 0; i < n; i++) {\n const bit = (targetState >> i) & 1;\n if (bit === 0)\n muGate(reg, 'X', i);\n }\n // --- GROVER DIFFUSER (Amplification) ---\n // This flips the probability amplitudes around the mean, boosting the target state.\n // 1. Apply H to all\n for (let i = 0; i < n; i++)\n muGate(reg, 'H', i);\n // 2. Apply X to all\n for (let i = 0; i < n; i++)\n muGate(reg, 'X', i);\n // 3. Multi-Controlled Z (Reflection about |0...0>)\n // We want to flip phase of |11...1> state after X transformation (which corresponds to |00...0> original)\n // Target is last qubit, controls are 0 to n-2\n const diffControls = [];\n for (let i = 0; i < n - 1; i++)\n diffControls.push(i);\n muGate(reg, 'Z', n - 1, diffControls);\n // 4. Uncompute X\n for (let i = 0; i < n; i++)\n muGate(reg, 'X', i);\n // 5. Uncompute H\n for (let i = 0; i < n; i++)\n muGate(reg, 'H', i);\n}\nfunction muEntangle(reg, i, j) {\n muGate(reg, 'H', i);\n muGate(reg, 'CNOT', j, i);\n}\n/**\n * Quantum Teleportation Protocol\n * Transfers the state of `msgIdx` to `targetIdx` using `ancillaIdx` as a resource.\n * @param reg Register\n * @param msgIdx The qubit containing the state to teleport (Alice)\n * @param ancillaIdx The helper qubit (Alice's half of entanglement)\n * @param targetIdx The destination qubit (Bob)\n */\nfunction muTeleport(reg, msgIdx, ancillaIdx, targetIdx) {\n // 1. Create Bell Pair (Entanglement) between Ancilla and Target\n // Represents the shared link between Alice and Bob\n muEntangle(reg, ancillaIdx, targetIdx);\n // 2. Bell Measurement on Message + Ancilla (Alice's side)\n muGate(reg, 'CNOT', ancillaIdx, msgIdx); // Control: msg, Target: ancilla\n muGate(reg, 'H', msgIdx);\n // 3. Measure Alice's qubits (This collapses them)\n const m1 = muMeasure(reg, msgIdx); // Measures \"Z\" component\n const m2 = muMeasure(reg, ancillaIdx); // Measures \"X\" component\n // 4. Classical Communication & Correction (Bob's side)\n // Apply corrections to Target based on measurements\n if (m2 === 1)\n muGate(reg, 'X', targetIdx);\n if (m1 === 1)\n muGate(reg, 'Z', targetIdx);\n}\n/**\n * Measures a specific qubit in the register, collapsing the superposition.\n * @param reg Quantum Register\n * @param target Index of qubit to measure\n * @returns 0 or 1\n */\nfunction muMeasure(reg, target = 0) {\n const state = reg.value;\n const amplitudes = state.amplitudes;\n let prob0 = 0;\n // 1. Calculate Probability of |0>\n for (let i = 0; i < amplitudes.length; i++) {\n if (((i >> target) & 1) === 0) {\n const a = amplitudes[i];\n prob0 += (a.re * a.re) + (a.im * a.im);\n }\n }\n // 2. Determine Outcome\n const result = Math.random() < prob0 ? 0 : 1;\n const resultProb = result === 0 ? prob0 : (1 - prob0);\n const normFactor = resultProb > 0 ? (1 / Math.sqrt(resultProb)) : 0;\n // 3. Collapse the State (Wavefunction Collapse)\n const newAmps = amplitudes.map((a, i) => {\n const bit = (i >> target) & 1;\n if (bit !== result) {\n return { re: 0, im: 0 };\n }\n else {\n return { re: a.re * normFactor, im: a.im * normFactor };\n }\n });\n // We need to call updateState to ensure reactivity if specialized getters exist\n // But since this file has updateState internal, we can just call it.\n // However, the internal updateState function needs to be in scope. \n // It is defined at line 60. So we are good.\n updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));\n return result;\n}\n/**\n * Quantum Loop: Parallel Execution\n * Applies a gate to multiple qubits \"simultaneously\" (in simulation steps).\n * Ideal for initialization (Hadamard Transform) or global operations.\n * @param reg Quantum Register\n * @param qubits Array of qubit indices\n * @param gate Gate type to apply (e.g. 'H', 'X')\n */\nfunction muParallel(reg, qubits, gate) {\n if (gate === 'SWAP') {\n throw new Error(\"SWAP cannot be applied in parallel (requires pairs).\");\n }\n // In a real quantum computer, these happen at t=0.\n // Here, we loop, but logical time is constant.\n qubits.forEach(q => muGate(reg, gate, q));\n}\n/**\n * Applies a block of operations controlled by specific qubits.\n * Enables \"Quantum If/Else\".\n */\nfunction muControl(reg, controlQubit, inverse, block) {\n // 1. Setup Context\n if (inverse) {\n muGate(reg, 'X', controlQubit); // Flip 0 to 1 to activate\n }\n activeControls.push(controlQubit);\n try {\n block();\n }\n finally {\n activeControls.pop();\n // Uncompute (Restore 0)\n if (inverse) {\n muGate(reg, 'X', controlQubit);\n }\n }\n}\n/**\n * Quantum Switch: conditional Logic on Superposition\n * Executes different logic branches based on the state of control qubits.\n * Because the register can be in a superposition of states (e.g. |0> + |1>),\n * MULTIPLE branches can execute effectively simultaneously on different subspaces.\n *\n * @param reg Quantum Register\n * @param controlQubit The qubit controlling the switch (Single control for v1)\n * @param cases Object mapping state (0 or 1) to a function executing quantum operations\n */\nfunction muSwitch(reg, controlQubit, cases) {\n if (cases[0]) {\n muControl(reg, controlQubit, true, cases[0]);\n }\n if (cases[1]) {\n muControl(reg, controlQubit, false, cases[1]);\n }\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/quantum.ts?\n}");
|
|
1210
|
+
/**
|
|
1211
|
+
* Mulan Quantum (ASTR-Q+) Core
|
|
1212
|
+
* Advanced Simulation Engine for multi-qubit registers and entanglement.
|
|
1213
|
+
*/
|
|
1214
|
+
// -- GLOBAL CONTEXT FOR QUANTUM CONTROL --
|
|
1215
|
+
// Defined at top to ensure visibility for muGate
|
|
1216
|
+
let activeControls = [];
|
|
1217
|
+
/**
|
|
1218
|
+
* Creates a quantum register of size n.
|
|
1219
|
+
* State vector will have 2^n amplitudes.
|
|
1220
|
+
*/
|
|
1221
|
+
function muRegister(n) {
|
|
1222
|
+
const numStates = Math.pow(2, n);
|
|
1223
|
+
const amplitudes = new Array(numStates).fill(0).map((_, i) => ({
|
|
1224
|
+
re: i === 0 ? 1 : 0,
|
|
1225
|
+
im: 0
|
|
1226
|
+
}));
|
|
1227
|
+
return muState({
|
|
1228
|
+
value: {
|
|
1229
|
+
size: n,
|
|
1230
|
+
amplitudes
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Backward compatible muQubit (Single Qubit Register)
|
|
1236
|
+
*/
|
|
1237
|
+
function muQubit(initial = 0) {
|
|
1238
|
+
const q = muRegister(1);
|
|
1239
|
+
if (initial === 1) {
|
|
1240
|
+
muGate(q, 'X', 0);
|
|
1241
|
+
}
|
|
1242
|
+
// Add compatibility properties for Phase 1 components
|
|
1243
|
+
// These properties are getters that dynamically access the amplitudes array
|
|
1244
|
+
Object.defineProperty(q.value, 'alpha', { get: () => q.value.amplitudes[0] });
|
|
1245
|
+
Object.defineProperty(q.value, 'beta', { get: () => q.value.amplitudes[1] });
|
|
1246
|
+
return q;
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Internal helper to update register state while maintaining compatibility
|
|
1250
|
+
*/
|
|
1251
|
+
function updateState(reg, newState) {
|
|
1252
|
+
if (newState.size === 1) {
|
|
1253
|
+
// Re-inject compatibility getters for muQubit users
|
|
1254
|
+
Object.defineProperty(newState, 'alpha', {
|
|
1255
|
+
get: () => newState.amplitudes[0],
|
|
1256
|
+
configurable: true,
|
|
1257
|
+
enumerable: true
|
|
1258
|
+
});
|
|
1259
|
+
Object.defineProperty(newState, 'beta', {
|
|
1260
|
+
get: () => newState.amplitudes[1],
|
|
1261
|
+
configurable: true,
|
|
1262
|
+
enumerable: true
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
reg.value = newState;
|
|
1266
|
+
}
|
|
1267
|
+
function muGate(reg, type, target = 0, control) {
|
|
1268
|
+
const state = reg.value;
|
|
1269
|
+
const n = state.size;
|
|
1270
|
+
const amplitudes = state.amplitudes;
|
|
1271
|
+
const newAmps = amplitudes.map(a => (Object.assign({}, a)));
|
|
1272
|
+
// Prepare Effective Control (Explicit Arguments + Global Context)
|
|
1273
|
+
const effectiveControl = [...(control === undefined ? [] : (Array.isArray(control) ? control : [control])), ...activeControls];
|
|
1274
|
+
// Helper: Check if all control bits are 1
|
|
1275
|
+
const checkControl = (index, ctrl) => {
|
|
1276
|
+
if (ctrl === undefined || (Array.isArray(ctrl) && ctrl.length === 0))
|
|
1277
|
+
return true;
|
|
1278
|
+
const ctrls = Array.isArray(ctrl) ? ctrl : [ctrl];
|
|
1279
|
+
return ctrls.every(c => ((index >> c) & 1) === 1);
|
|
1280
|
+
};
|
|
1281
|
+
// SWAP Gate (Unique case: affects 2 targets)
|
|
1282
|
+
if (type === 'SWAP') {
|
|
1283
|
+
const t1 = target;
|
|
1284
|
+
const t2 = control; // SWAP uses control arg as second target
|
|
1285
|
+
// Iterate only half to avoid double swapping
|
|
1286
|
+
for (let i = 0; i < amplitudes.length; i++) {
|
|
1287
|
+
// Check active controls for SWAP too
|
|
1288
|
+
if (activeControls.length > 0 && !checkControl(i, activeControls))
|
|
1289
|
+
continue;
|
|
1290
|
+
const bit1 = (i >> t1) & 1;
|
|
1291
|
+
const bit2 = (i >> t2) & 1;
|
|
1292
|
+
if (bit1 !== bit2) {
|
|
1293
|
+
// Determine the swap partner index
|
|
1294
|
+
// If i has (0,1), partner has (1,0) at those positions
|
|
1295
|
+
const partner = i ^ (1 << t1) ^ (1 << t2);
|
|
1296
|
+
if (i < partner) {
|
|
1297
|
+
const temp = newAmps[i];
|
|
1298
|
+
newAmps[i] = newAmps[partner];
|
|
1299
|
+
newAmps[partner] = temp;
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
// Standard Single-Qubit & Controlled Gates
|
|
1307
|
+
if (type === 'H') {
|
|
1308
|
+
const s = 1 / Math.sqrt(2);
|
|
1309
|
+
const processed = new Set();
|
|
1310
|
+
for (let i = 0; i < state.amplitudes.length; i++) {
|
|
1311
|
+
if (processed.has(i))
|
|
1312
|
+
continue;
|
|
1313
|
+
// Check Controls first
|
|
1314
|
+
if (!checkControl(i, effectiveControl))
|
|
1315
|
+
continue;
|
|
1316
|
+
const targetBit = (i >> target) & 1;
|
|
1317
|
+
const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
|
|
1318
|
+
const a = state.amplitudes[i];
|
|
1319
|
+
const b = state.amplitudes[pairedIndex];
|
|
1320
|
+
if (targetBit === 0) {
|
|
1321
|
+
newAmps[i] = { re: s * (a.re + b.re), im: s * (a.im + b.im) };
|
|
1322
|
+
newAmps[pairedIndex] = { re: s * (a.re - b.re), im: s * (a.im - b.im) };
|
|
1323
|
+
}
|
|
1324
|
+
else {
|
|
1325
|
+
newAmps[pairedIndex] = { re: s * (b.re + a.re), im: s * (b.im + a.im) };
|
|
1326
|
+
newAmps[i] = { re: s * (b.re - a.re), im: s * (b.im - a.im) };
|
|
1327
|
+
}
|
|
1328
|
+
processed.add(i);
|
|
1329
|
+
processed.add(pairedIndex);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
else if (type === 'X' || type === 'CNOT') {
|
|
1333
|
+
// CNOT is just Controlled-X
|
|
1334
|
+
for (let i = 0; i < amplitudes.length; i++) {
|
|
1335
|
+
if (!checkControl(i, effectiveControl))
|
|
1336
|
+
continue;
|
|
1337
|
+
const targetBit = (i >> target) & 1;
|
|
1338
|
+
const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
|
|
1339
|
+
if (i < pairedIndex) {
|
|
1340
|
+
const temp = newAmps[i];
|
|
1341
|
+
newAmps[i] = newAmps[pairedIndex];
|
|
1342
|
+
newAmps[pairedIndex] = temp;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
else if (type === 'Z' || type === 'CZ') {
|
|
1347
|
+
// Z and CZ are Phase Flips
|
|
1348
|
+
for (let i = 0; i < amplitudes.length; i++) {
|
|
1349
|
+
if (!checkControl(i, effectiveControl))
|
|
1350
|
+
continue;
|
|
1351
|
+
const targetBit = (i >> target) & 1;
|
|
1352
|
+
// Z Gate acts on |1>
|
|
1353
|
+
if (targetBit === 1) {
|
|
1354
|
+
newAmps[i] = { re: -amplitudes[i].re, im: -amplitudes[i].im };
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
else if (type === 'Y') {
|
|
1359
|
+
// Y: |0> -> i|1>, |1> -> -i|0>
|
|
1360
|
+
for (let i = 0; i < amplitudes.length; i++) {
|
|
1361
|
+
if (!checkControl(i, effectiveControl))
|
|
1362
|
+
continue;
|
|
1363
|
+
const targetBit = (i >> target) & 1;
|
|
1364
|
+
const pairedIndex = targetBit ? (i & ~(1 << target)) : (i | (1 << target));
|
|
1365
|
+
if (i < pairedIndex) {
|
|
1366
|
+
// We process pairs (i, pairedIndex) where i has 0 at target, paired has 1
|
|
1367
|
+
const a = newAmps[i]; // Coeff of |0>
|
|
1368
|
+
const b = newAmps[pairedIndex]; // Coeff of |1>
|
|
1369
|
+
// New |0> = -i * Old |1>
|
|
1370
|
+
newAmps[i] = { re: b.im, im: -b.re };
|
|
1371
|
+
// New |1> = i * Old |0>
|
|
1372
|
+
newAmps[pairedIndex] = { re: -a.im, im: a.re };
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Mulan Search Logic (Grover's Operator)
|
|
1380
|
+
* Automatically constructs a multi-controlled Phase Flip (Z) for a specific target state.
|
|
1381
|
+
* This is the core of the "Quantum Switch" or "Quantum Search" capability.
|
|
1382
|
+
* @param reg Quantum Register
|
|
1383
|
+
* @param targetState The integer state to "search" and mark (e.g. 2 for |10>)
|
|
1384
|
+
*/
|
|
1385
|
+
function muSearch(reg, targetState) {
|
|
1386
|
+
const n = reg.value.size;
|
|
1387
|
+
const controls = [];
|
|
1388
|
+
// 1. Identify which bits are 0 and need wrapping with X gates
|
|
1389
|
+
// Logic: To mark |010>, we want C-C-Z to trigger on 111.
|
|
1390
|
+
// So we apply X to bits that are 0, then C-C-Z, then X again.
|
|
1391
|
+
// We treat the last bit as the 'target' for the Z gate, rest as controls
|
|
1392
|
+
const targetQubit = n - 1;
|
|
1393
|
+
for (let i = 0; i < n; i++) {
|
|
1394
|
+
const bit = (targetState >> i) & 1;
|
|
1395
|
+
if (i === targetQubit) {
|
|
1396
|
+
// If target bit logic requires 0, we flip it to 1 for the Z gate to work
|
|
1397
|
+
if (bit === 0)
|
|
1398
|
+
muGate(reg, 'X', i);
|
|
1399
|
+
}
|
|
1400
|
+
else {
|
|
1401
|
+
controls.push(i);
|
|
1402
|
+
if (bit === 0)
|
|
1403
|
+
muGate(reg, 'X', i);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
// 2. Apply Multi-Controlled Z
|
|
1407
|
+
muGate(reg, 'Z', targetQubit, controls);
|
|
1408
|
+
// 3. Uncompute (Restore 0s)
|
|
1409
|
+
for (let i = 0; i < n; i++) {
|
|
1410
|
+
const bit = (targetState >> i) & 1;
|
|
1411
|
+
if (bit === 0)
|
|
1412
|
+
muGate(reg, 'X', i);
|
|
1413
|
+
}
|
|
1414
|
+
// --- GROVER DIFFUSER (Amplification) ---
|
|
1415
|
+
// This flips the probability amplitudes around the mean, boosting the target state.
|
|
1416
|
+
// 1. Apply H to all
|
|
1417
|
+
for (let i = 0; i < n; i++)
|
|
1418
|
+
muGate(reg, 'H', i);
|
|
1419
|
+
// 2. Apply X to all
|
|
1420
|
+
for (let i = 0; i < n; i++)
|
|
1421
|
+
muGate(reg, 'X', i);
|
|
1422
|
+
// 3. Multi-Controlled Z (Reflection about |0...0>)
|
|
1423
|
+
// We want to flip phase of |11...1> state after X transformation (which corresponds to |00...0> original)
|
|
1424
|
+
// Target is last qubit, controls are 0 to n-2
|
|
1425
|
+
const diffControls = [];
|
|
1426
|
+
for (let i = 0; i < n - 1; i++)
|
|
1427
|
+
diffControls.push(i);
|
|
1428
|
+
muGate(reg, 'Z', n - 1, diffControls);
|
|
1429
|
+
// 4. Uncompute X
|
|
1430
|
+
for (let i = 0; i < n; i++)
|
|
1431
|
+
muGate(reg, 'X', i);
|
|
1432
|
+
// 5. Uncompute H
|
|
1433
|
+
for (let i = 0; i < n; i++)
|
|
1434
|
+
muGate(reg, 'H', i);
|
|
1435
|
+
}
|
|
1436
|
+
function muEntangle(reg, i, j) {
|
|
1437
|
+
muGate(reg, 'H', i);
|
|
1438
|
+
muGate(reg, 'CNOT', j, i);
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Quantum Teleportation Protocol
|
|
1442
|
+
* Transfers the state of `msgIdx` to `targetIdx` using `ancillaIdx` as a resource.
|
|
1443
|
+
* @param reg Register
|
|
1444
|
+
* @param msgIdx The qubit containing the state to teleport (Alice)
|
|
1445
|
+
* @param ancillaIdx The helper qubit (Alice's half of entanglement)
|
|
1446
|
+
* @param targetIdx The destination qubit (Bob)
|
|
1447
|
+
*/
|
|
1448
|
+
function muTeleport(reg, msgIdx, ancillaIdx, targetIdx) {
|
|
1449
|
+
// 1. Create Bell Pair (Entanglement) between Ancilla and Target
|
|
1450
|
+
// Represents the shared link between Alice and Bob
|
|
1451
|
+
muEntangle(reg, ancillaIdx, targetIdx);
|
|
1452
|
+
// 2. Bell Measurement on Message + Ancilla (Alice's side)
|
|
1453
|
+
muGate(reg, 'CNOT', ancillaIdx, msgIdx); // Control: msg, Target: ancilla
|
|
1454
|
+
muGate(reg, 'H', msgIdx);
|
|
1455
|
+
// 3. Measure Alice's qubits (This collapses them)
|
|
1456
|
+
const m1 = muMeasure(reg, msgIdx); // Measures "Z" component
|
|
1457
|
+
const m2 = muMeasure(reg, ancillaIdx); // Measures "X" component
|
|
1458
|
+
// 4. Classical Communication & Correction (Bob's side)
|
|
1459
|
+
// Apply corrections to Target based on measurements
|
|
1460
|
+
if (m2 === 1)
|
|
1461
|
+
muGate(reg, 'X', targetIdx);
|
|
1462
|
+
if (m1 === 1)
|
|
1463
|
+
muGate(reg, 'Z', targetIdx);
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Measures a specific qubit in the register, collapsing the superposition.
|
|
1467
|
+
* @param reg Quantum Register
|
|
1468
|
+
* @param target Index of qubit to measure
|
|
1469
|
+
* @returns 0 or 1
|
|
1470
|
+
*/
|
|
1471
|
+
function muMeasure(reg, target = 0) {
|
|
1472
|
+
const state = reg.value;
|
|
1473
|
+
const amplitudes = state.amplitudes;
|
|
1474
|
+
let prob0 = 0;
|
|
1475
|
+
// 1. Calculate Probability of |0>
|
|
1476
|
+
for (let i = 0; i < amplitudes.length; i++) {
|
|
1477
|
+
if (((i >> target) & 1) === 0) {
|
|
1478
|
+
const a = amplitudes[i];
|
|
1479
|
+
prob0 += (a.re * a.re) + (a.im * a.im);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
// 2. Determine Outcome
|
|
1483
|
+
const result = Math.random() < prob0 ? 0 : 1;
|
|
1484
|
+
const resultProb = result === 0 ? prob0 : (1 - prob0);
|
|
1485
|
+
const normFactor = resultProb > 0 ? (1 / Math.sqrt(resultProb)) : 0;
|
|
1486
|
+
// 3. Collapse the State (Wavefunction Collapse)
|
|
1487
|
+
const newAmps = amplitudes.map((a, i) => {
|
|
1488
|
+
const bit = (i >> target) & 1;
|
|
1489
|
+
if (bit !== result) {
|
|
1490
|
+
return { re: 0, im: 0 };
|
|
1491
|
+
}
|
|
1492
|
+
else {
|
|
1493
|
+
return { re: a.re * normFactor, im: a.im * normFactor };
|
|
1494
|
+
}
|
|
1495
|
+
});
|
|
1496
|
+
// We need to call updateState to ensure reactivity if specialized getters exist
|
|
1497
|
+
// But since this file has updateState internal, we can just call it.
|
|
1498
|
+
// However, the internal updateState function needs to be in scope.
|
|
1499
|
+
// It is defined at line 60. So we are good.
|
|
1500
|
+
updateState(reg, Object.assign(Object.assign({}, state), { amplitudes: newAmps }));
|
|
1501
|
+
return result;
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* Quantum Loop: Parallel Execution
|
|
1505
|
+
* Applies a gate to multiple qubits "simultaneously" (in simulation steps).
|
|
1506
|
+
* Ideal for initialization (Hadamard Transform) or global operations.
|
|
1507
|
+
* @param reg Quantum Register
|
|
1508
|
+
* @param qubits Array of qubit indices
|
|
1509
|
+
* @param gate Gate type to apply (e.g. 'H', 'X')
|
|
1510
|
+
*/
|
|
1511
|
+
function muParallel(reg, qubits, gate) {
|
|
1512
|
+
if (gate === 'SWAP') {
|
|
1513
|
+
throw new Error("SWAP cannot be applied in parallel (requires pairs).");
|
|
1514
|
+
}
|
|
1515
|
+
// In a real quantum computer, these happen at t=0.
|
|
1516
|
+
// Here, we loop, but logical time is constant.
|
|
1517
|
+
qubits.forEach(q => muGate(reg, gate, q));
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Applies a block of operations controlled by specific qubits.
|
|
1521
|
+
* Enables "Quantum If/Else".
|
|
1522
|
+
*/
|
|
1523
|
+
function muControl(reg, controlQubit, inverse, block) {
|
|
1524
|
+
// 1. Setup Context
|
|
1525
|
+
if (inverse) {
|
|
1526
|
+
muGate(reg, 'X', controlQubit); // Flip 0 to 1 to activate
|
|
1527
|
+
}
|
|
1528
|
+
activeControls.push(controlQubit);
|
|
1529
|
+
try {
|
|
1530
|
+
block();
|
|
1531
|
+
}
|
|
1532
|
+
finally {
|
|
1533
|
+
activeControls.pop();
|
|
1534
|
+
// Uncompute (Restore 0)
|
|
1535
|
+
if (inverse) {
|
|
1536
|
+
muGate(reg, 'X', controlQubit);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Quantum Switch: conditional Logic on Superposition
|
|
1542
|
+
* Executes different logic branches based on the state of control qubits.
|
|
1543
|
+
* Because the register can be in a superposition of states (e.g. |0> + |1>),
|
|
1544
|
+
* MULTIPLE branches can execute effectively simultaneously on different subspaces.
|
|
1545
|
+
*
|
|
1546
|
+
* @param reg Quantum Register
|
|
1547
|
+
* @param controlQubit The qubit controlling the switch (Single control for v1)
|
|
1548
|
+
* @param cases Object mapping state (0 or 1) to a function executing quantum operations
|
|
1549
|
+
*/
|
|
1550
|
+
function muSwitch(reg, controlQubit, cases) {
|
|
1551
|
+
if (cases[0]) {
|
|
1552
|
+
muControl(reg, controlQubit, true, cases[0]);
|
|
1553
|
+
}
|
|
1554
|
+
if (cases[1]) {
|
|
1555
|
+
muControl(reg, controlQubit, false, cases[1]);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
70
1558
|
|
|
71
|
-
|
|
1559
|
+
;// ./src/components/bloch-sphere.ts
|
|
72
1560
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
(
|
|
1561
|
+
class MuBlochSphereElement extends HTMLElement {
|
|
1562
|
+
static get observedAttributes() {
|
|
1563
|
+
return ['size'];
|
|
1564
|
+
}
|
|
1565
|
+
constructor() {
|
|
1566
|
+
super();
|
|
1567
|
+
this._arrow = null;
|
|
1568
|
+
this._container = null;
|
|
1569
|
+
this._disposeEffect = null;
|
|
1570
|
+
this.attachShadow({ mode: 'open' });
|
|
1571
|
+
}
|
|
1572
|
+
connectedCallback() {
|
|
1573
|
+
this.render();
|
|
1574
|
+
}
|
|
1575
|
+
disconnectedCallback() {
|
|
1576
|
+
if (this._disposeEffect) {
|
|
1577
|
+
this._disposeEffect();
|
|
1578
|
+
this._disposeEffect = null;
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
// Property setter for 'qubit' (passed as .qubit="${q}" in Mulan)
|
|
1582
|
+
set qubit(val) {
|
|
1583
|
+
this._qubit = val;
|
|
1584
|
+
this.initReactivity();
|
|
1585
|
+
}
|
|
1586
|
+
get qubit() {
|
|
1587
|
+
return this._qubit;
|
|
1588
|
+
}
|
|
1589
|
+
attributeChangedCallback(name, oldValue, newValue) {
|
|
1590
|
+
if (name === 'size' && this._container) {
|
|
1591
|
+
this._container.style.width = newValue + 'px';
|
|
1592
|
+
this._container.style.height = newValue + 'px';
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
initReactivity() {
|
|
1596
|
+
if (this._disposeEffect)
|
|
1597
|
+
this._disposeEffect();
|
|
1598
|
+
if (!this._qubit)
|
|
1599
|
+
return;
|
|
1600
|
+
// MulanJS Effect: Run whenever the qubit state changes
|
|
1601
|
+
this._disposeEffect = effect(() => {
|
|
1602
|
+
const state = this._qubit.value; // Access reactive proxy
|
|
1603
|
+
if (!state || !state.amplitudes)
|
|
1604
|
+
return;
|
|
1605
|
+
// Assume Single Qubit for Visualizer (Index 0 if passed a register)
|
|
1606
|
+
// If passed a register, we visualize the first qubit's logical projection (partial trace simplified)
|
|
1607
|
+
// Or assume input IS a specific qubit projection?
|
|
1608
|
+
// For simplified demo, we assume the register is size 1 OR we visualize Q0 of the register.
|
|
1609
|
+
const amps = state.amplitudes;
|
|
1610
|
+
// Support 1-qubit visualization from N-qubit register requires partial trace.
|
|
1611
|
+
// For now, let's assume the user passes a 1-qubit register OR we visualize index 0.
|
|
1612
|
+
// |psi> = a|0> + b|1>
|
|
1613
|
+
// a = amps[0] (re, im)
|
|
1614
|
+
// b = amps[1] (re, im)
|
|
1615
|
+
// Dealing with multi-qubit registers (naive projection for visualization):
|
|
1616
|
+
// We sum up probabilities for 0xxxx vs 1xxxx to get Z-axis.
|
|
1617
|
+
// This is "marginal probability".
|
|
1618
|
+
let p0 = 0;
|
|
1619
|
+
let p1 = 0;
|
|
1620
|
+
// Calculate Probabilities
|
|
1621
|
+
for (let i = 0; i < amps.length; i++) {
|
|
1622
|
+
const mag = amps[i].re * amps[i].re + amps[i].im * amps[i].im;
|
|
1623
|
+
if ((i & 1) === 0)
|
|
1624
|
+
p0 += mag;
|
|
1625
|
+
else
|
|
1626
|
+
p1 += mag;
|
|
1627
|
+
}
|
|
1628
|
+
// Theta from Z-projection
|
|
1629
|
+
// P0 = cos^2(theta/2) -> theta = 2 * acos(sqrt(P0))
|
|
1630
|
+
const theta = 2 * Math.acos(Math.min(1, Math.sqrt(p0)));
|
|
1631
|
+
// Phi?
|
|
1632
|
+
// Phase is relative phase between |0> and |1>.
|
|
1633
|
+
// We can look at the phase of the '1' component relative to '0'.
|
|
1634
|
+
// Simple approach: Look at amps[1] phase vs amps[0] phase.
|
|
1635
|
+
// But with entanglement, pure state phase is tricky.
|
|
1636
|
+
// Let's implement full density matrix if needed, but for now:
|
|
1637
|
+
// naive: atan2(amps[1].im, amps[1].re) - atan2(amps[0].im, amps[0].re)
|
|
1638
|
+
// We use the first pair (0 and 1) as proxy if multiple.
|
|
1639
|
+
const a0 = amps[0];
|
|
1640
|
+
const a1 = amps[1]; // Valid for N>=1
|
|
1641
|
+
const phase0 = Math.atan2(a0.im, a0.re);
|
|
1642
|
+
const phase1 = Math.atan2(a1.im, a1.re);
|
|
1643
|
+
let phi = phase1 - phase0;
|
|
1644
|
+
// Update Arrow
|
|
1645
|
+
this.updateArrow(theta, phi);
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
updateArrow(theta, phi) {
|
|
1649
|
+
if (!this._arrow)
|
|
1650
|
+
return;
|
|
1651
|
+
// Convert Quantum Coords (Theta, Phi) to CSS Transforms
|
|
1652
|
+
// Theta 0 = Top (|0>)
|
|
1653
|
+
// Theta PI = Bottom (|1>)
|
|
1654
|
+
// Theta PI/2 = Equator
|
|
1655
|
+
// CSS Rotate sequence:
|
|
1656
|
+
// 1. Start pointing UP (Y or Z axis in CSS?)
|
|
1657
|
+
// Let's say Arrow starts pointing UP (Y-).
|
|
1658
|
+
// Rotate Z by Phi (Azimuth)
|
|
1659
|
+
// Rotate X by Theta (Polar) - No, that's not standard Euler.
|
|
1660
|
+
// Standard Physics:
|
|
1661
|
+
// Z is Up (in Bloch), but CSS 3D Y is usually 'Down' or 'Up'.
|
|
1662
|
+
// Let's Map:
|
|
1663
|
+
// Bloch Z+ (|0>) -> CSS Y- (Top)
|
|
1664
|
+
// Bloch Z- (|1>) -> CSS Y+ (Bottom)
|
|
1665
|
+
// Bloch X+ (|+>) -> CSS Z+ (Front)
|
|
1666
|
+
// Transform:
|
|
1667
|
+
// rotateY(phi) ? No, phi rotates around Z-axis (Vertical).
|
|
1668
|
+
// theta rotates from Z-axis down.
|
|
1669
|
+
// CSS:
|
|
1670
|
+
// rotateY(phi) -> Rotates around Vertical axis.
|
|
1671
|
+
// rotateZ(theta) -> Rotates "down" from up?
|
|
1672
|
+
// Let's simplify:
|
|
1673
|
+
// transform: rotateY(${phi}rad) rotateZ(${theta}rad)
|
|
1674
|
+
// Note: CSS rotations order matters.
|
|
1675
|
+
const degTheta = theta * (180 / Math.PI);
|
|
1676
|
+
const degPhi = phi * (180 / Math.PI);
|
|
1677
|
+
// Adjustment for visual alignment
|
|
1678
|
+
this._arrow.style.transform = `rotateY(${degPhi}deg) rotateZ(${degTheta}deg)`;
|
|
1679
|
+
// Color based on state
|
|
1680
|
+
const isSuperposition = Math.abs(theta - Math.PI / 2) < 0.1;
|
|
1681
|
+
this._arrow.style.backgroundColor = isSuperposition ? '#00ffff' : '#ff00ff';
|
|
1682
|
+
}
|
|
1683
|
+
render() {
|
|
1684
|
+
if (!this.shadowRoot)
|
|
1685
|
+
return;
|
|
1686
|
+
const size = this.getAttribute('size') || '200';
|
|
1687
|
+
this.shadowRoot.innerHTML = `
|
|
1688
|
+
<style>
|
|
1689
|
+
:host {
|
|
1690
|
+
display: inline-block;
|
|
1691
|
+
perspective: 1000px;
|
|
1692
|
+
}
|
|
1693
|
+
.sphere-container {
|
|
1694
|
+
width: ${size}px;
|
|
1695
|
+
height: ${size}px;
|
|
1696
|
+
position: relative;
|
|
1697
|
+
transform-style: preserve-3d;
|
|
1698
|
+
margin: 0 auto;
|
|
1699
|
+
}
|
|
1700
|
+
.sphere {
|
|
1701
|
+
width: 100%;
|
|
1702
|
+
height: 100%;
|
|
1703
|
+
border-radius: 50%;
|
|
1704
|
+
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
1705
|
+
position: absolute;
|
|
1706
|
+
background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.1), rgba(0, 0, 0, 0.8));
|
|
1707
|
+
box-shadow: inset 0 0 20px rgba(255, 255, 255, 0.05);
|
|
1708
|
+
transform: rotateX(15deg) rotateY(15deg); /* Initial tilt for view */
|
|
1709
|
+
}
|
|
1710
|
+
/* Equator Ring */
|
|
1711
|
+
.equator {
|
|
1712
|
+
position: absolute;
|
|
1713
|
+
top: 50%;
|
|
1714
|
+
left: 0;
|
|
1715
|
+
width: 100%;
|
|
1716
|
+
height: 100%;
|
|
1717
|
+
border: 1px dashed rgba(255, 255, 255, 0.3);
|
|
1718
|
+
border-radius: 50%;
|
|
1719
|
+
transform: rotateX(90deg);
|
|
1720
|
+
pointer-events: none;
|
|
1721
|
+
}
|
|
1722
|
+
/* Axis Lines */
|
|
1723
|
+
.axis {
|
|
1724
|
+
position: absolute;
|
|
1725
|
+
background: rgba(255, 255, 255, 0.1);
|
|
1726
|
+
}
|
|
1727
|
+
.z-axis { width: 2px; height: 100%; left: 50%; top: 0; }
|
|
1728
|
+
|
|
1729
|
+
/* The Quantum Arrow */
|
|
1730
|
+
.arrow-container {
|
|
1731
|
+
position: absolute;
|
|
1732
|
+
top: 50%;
|
|
1733
|
+
left: 50%;
|
|
1734
|
+
width: 0;
|
|
1735
|
+
height: 0;
|
|
1736
|
+
transform-style: preserve-3d;
|
|
1737
|
+
transform: rotateX(15deg) rotateY(15deg); /* Match sphere tilt */
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
.arrow-pivot {
|
|
1741
|
+
position: absolute;
|
|
1742
|
+
top: 0;
|
|
1743
|
+
left: 0;
|
|
1744
|
+
width: 4px;
|
|
1745
|
+
height: 50%; /* Length of radius */
|
|
1746
|
+
/* Pivot logic: we want to rotate around the center point */
|
|
1747
|
+
/* CSS Default transform-origin is 50% 50% */
|
|
1748
|
+
/* We construct the arrow such that it points UP from center */
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
.arrow-rod {
|
|
1752
|
+
width: 4px;
|
|
1753
|
+
height: ${parseInt(size) / 2 - 10}px;
|
|
1754
|
+
background: #ff00ff;
|
|
1755
|
+
position: absolute;
|
|
1756
|
+
bottom: 0;
|
|
1757
|
+
left: -2px;
|
|
1758
|
+
transform-origin: bottom center;
|
|
1759
|
+
transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), background-color 0.3s;
|
|
1760
|
+
border-radius: 2px;
|
|
1761
|
+
box-shadow: 0 0 10px currentColor;
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
.arrow-head {
|
|
1765
|
+
width: 0;
|
|
1766
|
+
height: 0;
|
|
1767
|
+
border-left: 6px solid transparent;
|
|
1768
|
+
border-right: 6px solid transparent;
|
|
1769
|
+
border-bottom: 12px solid #ff00ff;
|
|
1770
|
+
position: absolute;
|
|
1771
|
+
top: -10px;
|
|
1772
|
+
left: -6px;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
.label {
|
|
1776
|
+
position: absolute;
|
|
1777
|
+
color: #aaa;
|
|
1778
|
+
font-family: monospace;
|
|
1779
|
+
font-size: 10px;
|
|
1780
|
+
}
|
|
1781
|
+
.label-0 { top: 5px; left: 50%; transform: translateX(-50%); }
|
|
1782
|
+
.label-1 { bottom: 5px; left: 50%; transform: translateX(-50%); }
|
|
1783
|
+
</style>
|
|
1784
|
+
|
|
1785
|
+
<div class="sphere-container">
|
|
1786
|
+
<div class="sphere">
|
|
1787
|
+
<div class="equator"></div>
|
|
1788
|
+
<div class="axis z-axis"></div>
|
|
1789
|
+
<div class="label label-0">|0></div>
|
|
1790
|
+
<div class="label label-1">|1></div>
|
|
1791
|
+
</div>
|
|
1792
|
+
|
|
1793
|
+
<div class="arrow-container">
|
|
1794
|
+
<!-- The rod is the actual rotating element -->
|
|
1795
|
+
<div class="arrow-rod">
|
|
1796
|
+
<div class="arrow-head"></div>
|
|
1797
|
+
</div>
|
|
1798
|
+
</div>
|
|
1799
|
+
</div>
|
|
1800
|
+
`;
|
|
1801
|
+
this._container = this.shadowRoot.querySelector('.sphere-container');
|
|
1802
|
+
this._arrow = this.shadowRoot.querySelector('.arrow-rod');
|
|
1803
|
+
// Re-init reactivity if qubit was set before render
|
|
1804
|
+
if (this._qubit)
|
|
1805
|
+
this.initReactivity();
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
// Register the custom element
|
|
1809
|
+
if (typeof customElements !== 'undefined') {
|
|
1810
|
+
customElements.define('mu-bloch-sphere', MuBlochSphereElement);
|
|
1811
|
+
}
|
|
78
1812
|
|
|
79
|
-
|
|
1813
|
+
;// ./src/components/infinity-list.ts
|
|
1814
|
+
class MuInfinity extends HTMLElement {
|
|
1815
|
+
constructor() {
|
|
1816
|
+
super();
|
|
1817
|
+
this._items = [];
|
|
1818
|
+
this._itemHeight = 50; // Default height
|
|
1819
|
+
this._template = '';
|
|
1820
|
+
this.attachShadow({ mode: 'open' });
|
|
1821
|
+
// Structure:
|
|
1822
|
+
// :host { overflow-y: auto; display: block; height: 100%; }
|
|
1823
|
+
// .spacer { height: totalHeight; position: relative; }
|
|
1824
|
+
// .content { position: absolute; top: padding; width: 100%; }
|
|
1825
|
+
this.shadowRoot.innerHTML = `
|
|
1826
|
+
<style>
|
|
1827
|
+
:host {
|
|
1828
|
+
display: block;
|
|
1829
|
+
overflow-y: auto;
|
|
1830
|
+
height: 100%;
|
|
1831
|
+
position: relative;
|
|
1832
|
+
}
|
|
1833
|
+
.spacer {
|
|
1834
|
+
position: relative;
|
|
1835
|
+
width: 100%;
|
|
1836
|
+
}
|
|
1837
|
+
.content {
|
|
1838
|
+
position: absolute;
|
|
1839
|
+
top: 0;
|
|
1840
|
+
left: 0;
|
|
1841
|
+
width: 100%;
|
|
1842
|
+
}
|
|
1843
|
+
</style>
|
|
1844
|
+
<div class="spacer">
|
|
1845
|
+
<div class="content"></div>
|
|
1846
|
+
</div>
|
|
1847
|
+
`;
|
|
1848
|
+
this.container = this.shadowRoot.host; // The host itself scrolls
|
|
1849
|
+
this.spacer = this.shadowRoot.querySelector('.spacer');
|
|
1850
|
+
this.content = this.shadowRoot.querySelector('.content');
|
|
1851
|
+
this.onScroll = this.onScroll.bind(this);
|
|
1852
|
+
}
|
|
1853
|
+
static get observedAttributes() {
|
|
1854
|
+
return ['item-height'];
|
|
1855
|
+
}
|
|
1856
|
+
attributeChangedCallback(name, oldValue, newValue) {
|
|
1857
|
+
if (name === 'item-height') {
|
|
1858
|
+
this._itemHeight = parseInt(newValue, 10) || 50;
|
|
1859
|
+
this.renderVisible();
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
connectedCallback() {
|
|
1863
|
+
// Find the template provided by the user (Support both standard and branded tags)
|
|
1864
|
+
const templateTag = this.querySelector('template') || this.querySelector('mu-template');
|
|
1865
|
+
if (templateTag) {
|
|
1866
|
+
this._template = templateTag.innerHTML;
|
|
1867
|
+
}
|
|
1868
|
+
this.addEventListener('scroll', this.onScroll);
|
|
1869
|
+
// Wait for next frame to get initial height if not set
|
|
1870
|
+
requestAnimationFrame(() => this.renderVisible());
|
|
1871
|
+
}
|
|
1872
|
+
disconnectedCallback() {
|
|
1873
|
+
this.removeEventListener('scroll', this.onScroll);
|
|
1874
|
+
}
|
|
1875
|
+
set items(value) {
|
|
1876
|
+
this._items = value;
|
|
1877
|
+
this.renderVisible();
|
|
1878
|
+
}
|
|
1879
|
+
get items() { return this._items; }
|
|
1880
|
+
onScroll() {
|
|
1881
|
+
requestAnimationFrame(() => this.renderVisible());
|
|
1882
|
+
}
|
|
1883
|
+
renderVisible() {
|
|
1884
|
+
if (!this._items.length)
|
|
1885
|
+
return;
|
|
1886
|
+
const scrollTop = this.scrollTop;
|
|
1887
|
+
const hostHeight = this.clientHeight || 400; // Default fallback if not sized
|
|
1888
|
+
const totalHeight = this._items.length * this._itemHeight;
|
|
1889
|
+
this.spacer.style.height = `${totalHeight}px`;
|
|
1890
|
+
// Windowing Math
|
|
1891
|
+
const startIndex = Math.floor(scrollTop / this._itemHeight);
|
|
1892
|
+
const buffer = 5;
|
|
1893
|
+
const visibleCount = Math.ceil(hostHeight / this._itemHeight);
|
|
1894
|
+
const renderStart = Math.max(0, startIndex - buffer);
|
|
1895
|
+
const renderEnd = Math.min(this._items.length, startIndex + visibleCount + buffer);
|
|
1896
|
+
const startOffset = renderStart * this._itemHeight;
|
|
1897
|
+
this.content.style.transform = `translateY(${startOffset}px)`;
|
|
1898
|
+
// Render specific slice
|
|
1899
|
+
const visibleItems = this._items.slice(renderStart, renderEnd);
|
|
1900
|
+
// Simple string replacement template engine for the demo
|
|
1901
|
+
// In a real Mulan compilation, this would be an optimized ASTR render
|
|
1902
|
+
let html = '';
|
|
1903
|
+
visibleItems.forEach((item, index) => {
|
|
1904
|
+
const absoluteIndex = renderStart + index;
|
|
1905
|
+
// Basic mustache replacement {{ item.prop }}
|
|
1906
|
+
let rowHtml = this._template
|
|
1907
|
+
.replace(/{{\s*item\s*}}/g, String(item)) // {{ item }}
|
|
1908
|
+
.replace(/{{\s*index\s*}}/g, String(absoluteIndex)); // {{ index }}
|
|
1909
|
+
// Handle object properties: {{ item.name }}
|
|
1910
|
+
if (typeof item === 'object' && item !== null) {
|
|
1911
|
+
rowHtml = rowHtml.replace(/{{\s*item\.(\w+)\s*}}/g, (_, prop) => {
|
|
1912
|
+
return String(item[prop] || '');
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
html += `<div style="height: ${this._itemHeight}px; overflow: hidden;">${rowHtml}</div>`;
|
|
1916
|
+
});
|
|
1917
|
+
this.content.innerHTML = html;
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
// Register
|
|
1921
|
+
if (typeof customElements !== 'undefined' && !customElements.get('mu-infinity')) {
|
|
1922
|
+
customElements.define('mu-infinity', MuInfinity);
|
|
1923
|
+
}
|
|
80
1924
|
|
|
81
|
-
|
|
1925
|
+
;// ./src/core/surge.ts
|
|
1926
|
+
/**
|
|
1927
|
+
* muBurst - Adaptive Non-blocking Iterator
|
|
1928
|
+
* Processes large arrays in batches within a frame budget (typically 8-16ms)
|
|
1929
|
+
* to keep the UI responsive while executing at near-native loop speeds.
|
|
1930
|
+
*/
|
|
1931
|
+
function muBurst(array, callback, options = {}) {
|
|
1932
|
+
const { chunkSize = 1000, timeout = 8, onProgress } = options;
|
|
1933
|
+
return new Promise((resolve) => {
|
|
1934
|
+
let index = 0;
|
|
1935
|
+
const total = array.length;
|
|
1936
|
+
function process() {
|
|
1937
|
+
const start = performance.now();
|
|
1938
|
+
// Tight loop for high-speed processing
|
|
1939
|
+
while (index < total && (performance.now() - start) < timeout) {
|
|
1940
|
+
// Process in smaller bursts to allow more frequent time checks if needed
|
|
1941
|
+
const endBurst = Math.min(index + chunkSize, total);
|
|
1942
|
+
for (; index < endBurst; index++) {
|
|
1943
|
+
callback(array[index], index);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
if (onProgress) {
|
|
1947
|
+
onProgress((index / total) * 100);
|
|
1948
|
+
}
|
|
1949
|
+
if (index < total) {
|
|
1950
|
+
requestAnimationFrame(process);
|
|
1951
|
+
}
|
|
1952
|
+
else {
|
|
1953
|
+
resolve();
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
process();
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* muSurge - Truly Parallel Execution
|
|
1961
|
+
* Distributes work across CPU cores using Web Workers.
|
|
1962
|
+
* Logic must be serializable.
|
|
1963
|
+
*/
|
|
1964
|
+
function muSurge(array, taskFn, onProgress) {
|
|
1965
|
+
const n = navigator.hardwareConcurrency || 4;
|
|
1966
|
+
const chunkSize = Math.ceil(array.length / n);
|
|
1967
|
+
const results = new Array(array.length);
|
|
1968
|
+
let completedChunks = 0;
|
|
1969
|
+
let completedItems = 0;
|
|
1970
|
+
// Convert function to string if it isn't already
|
|
1971
|
+
const fnStr = typeof taskFn === 'function' ? taskFn.toString() : taskFn;
|
|
1972
|
+
const workerPart1 = `const taskFn = ${fnStr};`;
|
|
1973
|
+
const workerPart2 = `self.onmessage = function(e) {`;
|
|
1974
|
+
const workerPart3 = ` const { chunk, startIndex } = e.data;`;
|
|
1975
|
+
const workerPart4 = ` try { const results = chunk.map(taskFn); self.postMessage({ results, startIndex }); }`;
|
|
1976
|
+
const workerPart5 = ` catch (err) { self.postMessage({ error: err.message, startIndex }); }`;
|
|
1977
|
+
const workerPart6 = `};`;
|
|
1978
|
+
const workerCode = [workerPart1, workerPart2, workerPart3, workerPart4, workerPart5, workerPart6].join('\n');
|
|
1979
|
+
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
|
1980
|
+
const workerUrl = URL.createObjectURL(blob);
|
|
1981
|
+
return new Promise((resolve) => {
|
|
1982
|
+
if (array.length === 0)
|
|
1983
|
+
return resolve([]);
|
|
1984
|
+
for (let i = 0; i < n; i++) {
|
|
1985
|
+
const start = i * chunkSize;
|
|
1986
|
+
const end = Math.min(start + chunkSize, array.length);
|
|
1987
|
+
if (start >= end) {
|
|
1988
|
+
completedChunks++;
|
|
1989
|
+
continue;
|
|
1990
|
+
}
|
|
1991
|
+
const chunk = array.slice(start, end);
|
|
1992
|
+
const worker = new Worker(workerUrl);
|
|
1993
|
+
worker.onmessage = (e) => {
|
|
1994
|
+
const { results: chunkResults, startIndex } = e.data;
|
|
1995
|
+
// Merge results back into main array
|
|
1996
|
+
for (let j = 0; j < chunkResults.length; j++) {
|
|
1997
|
+
results[startIndex + j] = chunkResults[j];
|
|
1998
|
+
}
|
|
1999
|
+
completedChunks++;
|
|
2000
|
+
completedItems += chunkResults.length;
|
|
2001
|
+
if (onProgress)
|
|
2002
|
+
onProgress((completedItems / array.length) * 100);
|
|
2003
|
+
worker.terminate();
|
|
2004
|
+
if (completedChunks === n) {
|
|
2005
|
+
URL.revokeObjectURL(workerUrl);
|
|
2006
|
+
resolve(results);
|
|
2007
|
+
}
|
|
2008
|
+
};
|
|
2009
|
+
worker.postMessage({ chunk, startIndex: start, fnStr });
|
|
2010
|
+
}
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
82
2013
|
|
|
83
|
-
|
|
84
|
-
/*!******************************!*\
|
|
85
|
-
!*** ./src/core/reactive.ts ***!
|
|
86
|
-
\******************************/
|
|
87
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
2014
|
+
;// ./src/index.ts
|
|
88
2015
|
|
|
89
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Signal: () => (/* binding */ Signal),\n/* harmony export */ effect: () => (/* binding */ effect),\n/* harmony export */ reactive: () => (/* binding */ reactive),\n/* harmony export */ ref: () => (/* binding */ ref)\n/* harmony export */ });\n// MulanJS 2.0: Signal-Powered Reactivity Engine\n// \"Compatible Surface, World-Class Engine\"\nlet activeEffect = null;\nconst targetMap = new WeakMap();\n// --- Signal Core (The Engine) ---\nclass Signal {\n constructor(initialValue) {\n this._subscribers = new Set();\n this._value = initialValue;\n }\n get value() {\n if (activeEffect) {\n this._subscribers.add(activeEffect);\n }\n return this._value;\n }\n set value(newValue) {\n if (newValue !== this._value) {\n this._value = newValue;\n this.notify();\n }\n }\n notify() {\n this._subscribers.forEach(fn => fn());\n }\n}\n// --- Compatibility Layer (The Surface) ---\nfunction effect(fn) {\n let stopped = false;\n const run = () => {\n if (stopped)\n return;\n const prev = activeEffect;\n activeEffect = run;\n try {\n fn();\n }\n finally {\n activeEffect = prev;\n }\n };\n run();\n return () => {\n stopped = true;\n };\n}\nfunction track(target, key) {\n if (activeEffect) {\n let depsMap = targetMap.get(target);\n if (!depsMap) {\n targetMap.set(target, (depsMap = new Map()));\n }\n let dep = depsMap.get(key);\n if (!dep) {\n depsMap.set(key, (dep = new Set()));\n }\n dep.add(activeEffect);\n }\n}\nfunction trigger(target, key) {\n const depsMap = targetMap.get(target);\n if (!depsMap)\n return;\n const dep = depsMap.get(key);\n if (dep) {\n dep.forEach((fn) => fn());\n }\n}\n/**\n * Creates a reactive proxy object (Vue-compatible).\n * Now optimized to respect Mulan Cycle.\n */\nfunction reactive(target) {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n // IRON FORTRESS: Prototype Pollution Protection (Read)\n if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {\n return undefined;\n }\n track(obj, prop);\n const val = Reflect.get(obj, prop, receiver);\n if (val !== null && typeof val === 'object') {\n return reactive(val);\n }\n return val;\n },\n set(obj, prop, value, receiver) {\n // IRON FORTRESS: Prototype Pollution Protection\n if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') {\n console.warn(`[Iron Fortress] Blocked attempt to modify dangerous property: ${String(prop)}`);\n return false;\n }\n const result = Reflect.set(obj, prop, value, receiver);\n trigger(obj, prop);\n return result;\n },\n });\n}\n/**\n * Creates a standalone reactive reference.\n * Backed by the Mulan Signal Engine.\n */\nfunction ref(value) {\n return new Signal(value);\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/reactive.ts?\n}");
|
|
90
2016
|
|
|
91
|
-
/***/ },
|
|
92
2017
|
|
|
93
|
-
/***/ "./src/core/renderer.ts"
|
|
94
|
-
/*!******************************!*\
|
|
95
|
-
!*** ./src/core/renderer.ts ***!
|
|
96
|
-
\******************************/
|
|
97
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
98
2018
|
|
|
99
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ hydrate: () => (/* binding */ hydrate),\n/* harmony export */ render: () => (/* binding */ render),\n/* harmony export */ renderToString: () => (/* binding */ renderToString),\n/* harmony export */ sanitize: () => (/* binding */ sanitize)\n/* harmony export */ });\nfunction render(template, container) {\n // Focus Preservation (The \"Mulan Glance\" Technique)\n let focusedId = null;\n let selectionStart = null;\n let selectionEnd = null;\n let preservedValue = null;\n if (document.activeElement && container.contains(document.activeElement)) {\n const el = document.activeElement;\n if (el.hasAttribute('data-mu-id')) {\n focusedId = el.getAttribute('data-mu-id');\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n selectionStart = el.selectionStart;\n selectionEnd = el.selectionEnd;\n preservedValue = el.value;\n }\n }\n }\n // [Anima] 1. Pre-Update: Snapshot positions of animated elements\n const animationSnapshots = new Map();\n // Only query if we might have animations to save perf\n if (template.includes('mu-animate')) {\n const animatedEls = container.querySelectorAll('[mu-animate]');\n animatedEls.forEach(el => {\n const key = el.getAttribute('mu-key') || el.id;\n if (key) {\n animationSnapshots.set(key, el.getBoundingClientRect());\n }\n });\n }\n container.innerHTML = template;\n // Restore Focus and Value\n if (focusedId) {\n const el = container.querySelector(`[data-mu-id=\"${focusedId}\"]`);\n if (el) {\n // Restore value first to ensure cursor positioning works correctly\n if (preservedValue !== null && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) {\n el.value = preservedValue;\n }\n el.focus();\n if ((el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && selectionStart !== null) {\n try {\n el.setSelectionRange(selectionStart, selectionEnd);\n }\n catch (e) {\n // input types that don't support selection (e.g. number/email) might throw\n }\n }\n }\n }\n // [Anima] 2. Post-Update: FLIP (First, Last, Invert, Play)\n if (animationSnapshots.size > 0) {\n const newAnimatedEls = container.querySelectorAll('[mu-animate]');\n newAnimatedEls.forEach(el => {\n const key = el.getAttribute('mu-key') || el.id;\n if (key && animationSnapshots.has(key)) {\n const oldRect = animationSnapshots.get(key);\n const newRect = el.getBoundingClientRect();\n const dx = oldRect.left - newRect.left;\n const dy = oldRect.top - newRect.top;\n // Only animate if moved\n if (dx !== 0 || dy !== 0) {\n const htmlEl = el;\n // INVERT: Move it back to where it was instantly\n htmlEl.style.transform = `translate(${dx}px, ${dy}px)`;\n htmlEl.style.transition = 'none';\n // PLAY: Animate to zero (new position)\n requestAnimationFrame(() => {\n // Force reflow\n // void htmlEl.offsetWidth; \n htmlEl.style.transition = 'transform 500ms cubic-bezier(0.25, 0.8, 0.25, 1)';\n htmlEl.style.transform = '';\n });\n }\n }\n });\n }\n}\nfunction hydrate(template, container) {\n // In a string-based framework, hydration is often just \"take over\".\n // For now, we'll verify if the server content matches (simple check)\n // and then assume control. In a more advanced version, we'd attach listeners without re-rendering.\n if (container.innerHTML.trim() !== template.trim()) {\n console.warn('Hydration Mismatch: Server rendered content differs from Client.');\n container.innerHTML = template; // Fallback to full render\n }\n else {\n // console.log('Hydration Successful.');\n }\n // Future: Attach event listeners here if we had a mechanism for it.\n}\nfunction renderToString(template) {\n // SSR Function: returns the HTML string for the server to send.\n // Can include additional sanitization or metadata injection here.\n return template;\n}\nfunction sanitize(str) {\n // Check if we are in a browser environment\n if (typeof document !== 'undefined') {\n const temp = document.createElement('div');\n temp.textContent = str;\n return temp.innerHTML;\n }\n // Simple SSR fallback sanitizer (rudimentary)\n return str.replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/renderer.ts?\n}");
|
|
100
2019
|
|
|
101
|
-
/***/ },
|
|
102
2020
|
|
|
103
|
-
/***/ "./src/core/surge.ts"
|
|
104
|
-
/*!***************************!*\
|
|
105
|
-
!*** ./src/core/surge.ts ***!
|
|
106
|
-
\***************************/
|
|
107
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
108
2021
|
|
|
109
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ muBurst: () => (/* binding */ muBurst),\n/* harmony export */ muSurge: () => (/* binding */ muSurge)\n/* harmony export */ });\n/**\n * muBurst - Adaptive Non-blocking Iterator\n * Processes large arrays in batches within a frame budget (typically 8-16ms)\n * to keep the UI responsive while executing at near-native loop speeds.\n */\nfunction muBurst(array, callback, options = {}) {\n const { chunkSize = 1000, timeout = 8, onProgress } = options;\n return new Promise((resolve) => {\n let index = 0;\n const total = array.length;\n function process() {\n const start = performance.now();\n // Tight loop for high-speed processing\n while (index < total && (performance.now() - start) < timeout) {\n // Process in smaller bursts to allow more frequent time checks if needed\n const endBurst = Math.min(index + chunkSize, total);\n for (; index < endBurst; index++) {\n callback(array[index], index);\n }\n }\n if (onProgress) {\n onProgress((index / total) * 100);\n }\n if (index < total) {\n requestAnimationFrame(process);\n }\n else {\n resolve();\n }\n }\n process();\n });\n}\n/**\n * muSurge - Truly Parallel Execution\n * Distributes work across CPU cores using Web Workers.\n * Logic must be serializable.\n */\nfunction muSurge(array, taskFn, onProgress) {\n const n = navigator.hardwareConcurrency || 4;\n const chunkSize = Math.ceil(array.length / n);\n const results = new Array(array.length);\n let completedChunks = 0;\n let completedItems = 0;\n // Convert function to string if it isn't already\n const fnStr = typeof taskFn === 'function' ? taskFn.toString() : taskFn;\n const workerCode = `\r\n const taskFn = ${fnStr};\r\n self.onmessage = function(e) {\r\n const { chunk, startIndex } = e.data;\r\n try {\r\n const results = chunk.map(taskFn);\r\n self.postMessage({ results, startIndex });\r\n } catch (err) {\r\n self.postMessage({ error: err.message, startIndex });\r\n }\r\n };\r\n `;\n const blob = new Blob([workerCode], { type: 'application/javascript' });\n const workerUrl = URL.createObjectURL(blob);\n return new Promise((resolve) => {\n if (array.length === 0)\n return resolve([]);\n for (let i = 0; i < n; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, array.length);\n if (start >= end) {\n completedChunks++;\n continue;\n }\n const chunk = array.slice(start, end);\n const worker = new Worker(workerUrl);\n worker.onmessage = (e) => {\n const { results: chunkResults, startIndex } = e.data;\n // Merge results back into main array\n for (let j = 0; j < chunkResults.length; j++) {\n results[startIndex + j] = chunkResults[j];\n }\n completedChunks++;\n completedItems += chunkResults.length;\n if (onProgress)\n onProgress((completedItems / array.length) * 100);\n worker.terminate();\n if (completedChunks === n) {\n URL.revokeObjectURL(workerUrl);\n resolve(results);\n }\n };\n worker.postMessage({ chunk, startIndex: start, fnStr });\n }\n });\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/surge.ts?\n}");
|
|
110
2022
|
|
|
111
|
-
/***/ },
|
|
112
2023
|
|
|
113
|
-
/***/ "./src/core/vault.ts"
|
|
114
|
-
/*!***************************!*\
|
|
115
|
-
!*** ./src/core/vault.ts ***!
|
|
116
|
-
\***************************/
|
|
117
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
118
2024
|
|
|
119
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ persistent: () => (/* binding */ persistent)\n/* harmony export */ });\n/* harmony import */ var _hooks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hooks */ \"./src/core/hooks.ts\");\n/* harmony import */ var _reactive__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reactive */ \"./src/core/reactive.ts\");\n\n\n/**\n * Mulan Vault: The World's First Native Persistent State Primitive.\n */\nfunction persistent(key, initialValue, options = {}) {\n const storage = options.storage || window.localStorage;\n // 1. Load from Storage\n const stored = storage.getItem(key);\n let startVal = initialValue;\n if (stored) {\n try {\n startVal = JSON.parse(stored);\n }\n catch (e) {\n console.warn(`[Mulan Vault] Corrupt persistent data for key \"${key}\", resetting.`);\n }\n }\n // 2. Create Reactive State (Follow muState pattern for consistency)\n const isObject = typeof startVal === 'object' && startVal !== null;\n const state = isObject ? (0,_reactive__WEBPACK_IMPORTED_MODULE_1__.reactive)(startVal) : (0,_reactive__WEBPACK_IMPORTED_MODULE_1__.reactive)({ value: startVal });\n // 3. Auto-Save on Change\n (0,_hooks__WEBPACK_IMPORTED_MODULE_0__.muEffect)(() => {\n try {\n const payload = isObject ? state : state.value;\n const toSave = JSON.stringify(payload);\n // Non-obfuscated persistence to satisfy security audits\n storage.setItem(key, toSave);\n }\n catch (e) {\n console.error(`[Mulan Vault] Failed to save key \"${key}\"`);\n }\n });\n // 4. Sync across Tabs\n const sync = (e) => {\n if (e.key === key && e.newValue) {\n try {\n const newVal = JSON.parse(e.newValue);\n if (isObject) {\n Object.assign(state, newVal);\n }\n else {\n state.value = newVal;\n }\n }\n catch (e) { }\n }\n };\n window.addEventListener('storage', sync);\n // Auto-cleanup if used inside a component\n try {\n const { onMuDestroy } = __webpack_require__(/*! ./hooks */ \"./src/core/hooks.ts\");\n onMuDestroy(() => {\n window.removeEventListener('storage', sync);\n });\n }\n catch (e) {\n // muVault might be used outside component setup in some advanced cases, \n // fallback to manual or no-cleanup if so.\n }\n return state;\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/vault.ts?\n}");
|
|
120
2025
|
|
|
121
|
-
/***/ },
|
|
122
2026
|
|
|
123
|
-
/***/ "./src/index.ts"
|
|
124
|
-
/*!**********************!*\
|
|
125
|
-
!*** ./src/index.ts ***!
|
|
126
|
-
\**********************/
|
|
127
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
128
2027
|
|
|
129
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Component: () => (/* reexport safe */ _core_component__WEBPACK_IMPORTED_MODULE_1__.MuComponent),\n/* harmony export */ MuBlochSphereElement: () => (/* reexport safe */ _components_bloch_sphere__WEBPACK_IMPORTED_MODULE_11__.MuBlochSphereElement),\n/* harmony export */ MuComponent: () => (/* reexport safe */ _core_component__WEBPACK_IMPORTED_MODULE_1__.MuComponent),\n/* harmony export */ MuInfinity: () => (/* reexport safe */ _components_infinity_list__WEBPACK_IMPORTED_MODULE_12__.MuInfinity),\n/* harmony export */ MuRouter: () => (/* reexport safe */ _router_index__WEBPACK_IMPORTED_MODULE_3__.MuRouter),\n/* harmony export */ MuStore: () => (/* reexport safe */ _store_index__WEBPACK_IMPORTED_MODULE_4__.MuStore),\n/* harmony export */ Router: () => (/* reexport safe */ _router_index__WEBPACK_IMPORTED_MODULE_3__.MuRouter),\n/* harmony export */ Security: () => (/* reexport safe */ _security_sanitizer__WEBPACK_IMPORTED_MODULE_5__.Security),\n/* harmony export */ Signal: () => (/* reexport safe */ _core_reactive__WEBPACK_IMPORTED_MODULE_0__.Signal),\n/* harmony export */ activeControls: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.activeControls),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ defineComponent: () => (/* reexport safe */ _core_component__WEBPACK_IMPORTED_MODULE_1__.defineComponent),\n/* harmony export */ effect: () => (/* reexport safe */ _core_reactive__WEBPACK_IMPORTED_MODULE_0__.effect),\n/* harmony export */ getCurrentInstance: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.getCurrentInstance),\n/* harmony export */ hydrate: () => (/* reexport safe */ _core_renderer__WEBPACK_IMPORTED_MODULE_2__.hydrate),\n/* harmony export */ muBurst: () => (/* reexport safe */ _core_surge__WEBPACK_IMPORTED_MODULE_10__.muBurst),\n/* harmony export */ muControl: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muControl),\n/* harmony export */ muEffect: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muEffect),\n/* harmony export */ muEntangle: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muEntangle),\n/* harmony export */ muGate: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muGate),\n/* harmony export */ muGeom: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muGeom),\n/* harmony export */ muMeasure: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muMeasure),\n/* harmony export */ muMemo: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muMemo),\n/* harmony export */ muParallel: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muParallel),\n/* harmony export */ muPulse: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muPulse),\n/* harmony export */ muQubit: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muQubit),\n/* harmony export */ muRegister: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muRegister),\n/* harmony export */ muSearch: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muSearch),\n/* harmony export */ muState: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muState),\n/* harmony export */ muSurge: () => (/* reexport safe */ _core_surge__WEBPACK_IMPORTED_MODULE_10__.muSurge),\n/* harmony export */ muSwitch: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muSwitch),\n/* harmony export */ muTeleport: () => (/* reexport safe */ _core_quantum__WEBPACK_IMPORTED_MODULE_9__.muTeleport),\n/* harmony export */ muVault: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.muVault),\n/* harmony export */ onMuDestroy: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuDestroy),\n/* harmony export */ onMuIdle: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuIdle),\n/* harmony export */ onMuInit: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuInit),\n/* harmony export */ onMuMount: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuMount),\n/* harmony export */ onMuResume: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuResume),\n/* harmony export */ onMuShake: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuShake),\n/* harmony export */ onMuVoice: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.onMuVoice),\n/* harmony export */ persistent: () => (/* reexport safe */ _core_vault__WEBPACK_IMPORTED_MODULE_8__.persistent),\n/* harmony export */ reactive: () => (/* reexport safe */ _core_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive),\n/* harmony export */ ref: () => (/* reexport safe */ _core_reactive__WEBPACK_IMPORTED_MODULE_0__.ref),\n/* harmony export */ render: () => (/* reexport safe */ _core_renderer__WEBPACK_IMPORTED_MODULE_2__.render),\n/* harmony export */ renderToString: () => (/* reexport safe */ _core_renderer__WEBPACK_IMPORTED_MODULE_2__.renderToString),\n/* harmony export */ sanitize: () => (/* reexport safe */ _core_renderer__WEBPACK_IMPORTED_MODULE_2__.sanitize),\n/* harmony export */ setCurrentInstance: () => (/* reexport safe */ _core_hooks__WEBPACK_IMPORTED_MODULE_6__.setCurrentInstance),\n/* harmony export */ useMutation: () => (/* reexport safe */ _core_query__WEBPACK_IMPORTED_MODULE_7__.useMutation),\n/* harmony export */ useQuery: () => (/* reexport safe */ _core_query__WEBPACK_IMPORTED_MODULE_7__.useQuery)\n/* harmony export */ });\n/* harmony import */ var _core_reactive__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./core/reactive */ \"./src/core/reactive.ts\");\n/* harmony import */ var _core_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./core/component */ \"./src/core/component.ts\");\n/* harmony import */ var _core_renderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./core/renderer */ \"./src/core/renderer.ts\");\n/* harmony import */ var _router_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./router/index */ \"./src/router/index.ts\");\n/* harmony import */ var _store_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./store/index */ \"./src/store/index.ts\");\n/* harmony import */ var _security_sanitizer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./security/sanitizer */ \"./src/security/sanitizer.ts\");\n/* harmony import */ var _core_hooks__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./core/hooks */ \"./src/core/hooks.ts\");\n/* harmony import */ var _core_query__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./core/query */ \"./src/core/query.ts\");\n/* harmony import */ var _core_vault__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./core/vault */ \"./src/core/vault.ts\");\n/* harmony import */ var _core_quantum__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./core/quantum */ \"./src/core/quantum.ts\");\n/* harmony import */ var _core_surge__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./core/surge */ \"./src/core/surge.ts\");\n/* harmony import */ var _components_bloch_sphere__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./components/bloch-sphere */ \"./src/components/bloch-sphere.ts\");\n/* harmony import */ var _components_infinity_list__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./components/infinity-list */ \"./src/components/infinity-list.ts\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n// Global Mulan Object for non-module usage\n\n\n\n\n\n\n\n\n\n\n\nconst Mulan = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ reactive: _core_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive,\n effect: _core_reactive__WEBPACK_IMPORTED_MODULE_0__.effect, Component: _core_component__WEBPACK_IMPORTED_MODULE_1__.MuComponent, defineComponent: _core_component__WEBPACK_IMPORTED_MODULE_1__.defineComponent, Router: _router_index__WEBPACK_IMPORTED_MODULE_3__.MuRouter, createRouter: _router_index__WEBPACK_IMPORTED_MODULE_3__.createRouter, Store: _store_index__WEBPACK_IMPORTED_MODULE_4__.MuStore, Security: _security_sanitizer__WEBPACK_IMPORTED_MODULE_5__.Security }, _core_hooks__WEBPACK_IMPORTED_MODULE_6__), _core_query__WEBPACK_IMPORTED_MODULE_7__), _core_quantum__WEBPACK_IMPORTED_MODULE_9__), _core_surge__WEBPACK_IMPORTED_MODULE_10__), _components_infinity_list__WEBPACK_IMPORTED_MODULE_12__), { render: _core_renderer__WEBPACK_IMPORTED_MODULE_2__.render, \n // MULAN INSIGHT: Branded Logging\n log: (msg, ...args) => {\n console.log(`%c[MulanJS]%c ${msg}`, \"color: #ff3e00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;\", \"\", ...args);\n }, warn: (msg, ...args) => {\n console.warn(`%c[MulanJS]%c ${msg}`, \"color: #ffcc00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;\", \"\", ...args);\n }, error: (msg, ...args) => {\n console.error(`%c[MulanJS]%c ${msg}`, \"color: #ff0000; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;\", \"\", ...args);\n } });\n// Security: Freeze the object to prevent runtime tampering\nObject.freeze(Mulan);\nObject.freeze(Mulan.Security);\n// MULAN INSIGHT: Initialize Global Registry\nif (typeof window !== 'undefined') {\n window.__MULAN_INSIGHT__ = window.__MULAN_INSIGHT__ || { components: new Map() };\n // MULAN INSIGHT: HMR Support\n window.__MULAN_REFRESH__ = () => {\n var _a;\n const components = (_a = window.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components;\n if (components) {\n components.forEach((comp) => {\n if (comp && typeof comp.update === 'function') {\n // Force refresh\n comp.update();\n }\n });\n }\n };\n}\nif (typeof window !== 'undefined') {\n window.Mulan = Mulan;\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Mulan);\n\n\n//# sourceURL=webpack://Mulan/./src/index.ts?\n}");
|
|
2028
|
+
// Global Mulan Object for non-module usage
|
|
130
2029
|
|
|
131
|
-
/***/ },
|
|
132
2030
|
|
|
133
|
-
/***/ "./src/router/index.ts"
|
|
134
|
-
/*!*****************************!*\
|
|
135
|
-
!*** ./src/router/index.ts ***!
|
|
136
|
-
\*****************************/
|
|
137
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
138
2031
|
|
|
139
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MuRouter: () => (/* binding */ MuRouter),\n/* harmony export */ createRouter: () => (/* binding */ createRouter)\n/* harmony export */ });\n/* harmony import */ var _core_renderer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/renderer */ \"./src/core/renderer.ts\");\n/* harmony import */ var _security_sanitizer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../security/sanitizer */ \"./src/security/sanitizer.ts\");\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\n\n\nclass MuRouter {\n constructor(routes, rootContainer = null) {\n this.currentPath = '';\n this.currentComponent = null;\n this.lastRouteId = 0;\n this.routes = routes;\n this.rootContainer = rootContainer;\n this.isServer = rootContainer === null; // If no container, assume server/headless mode\n if (!this.isServer) {\n window.addEventListener('hashchange', this.handleRoute.bind(this));\n this.handleRoute(); // Initial load\n }\n }\n // SSR Method: Simulate a route visit on the server\n serverLookup(path) {\n return __awaiter(this, void 0, void 0, function* () {\n this.currentPath = path;\n const { route, params } = this.matchRoute(path);\n if (route) {\n // Run guards/resolvers here if needed\n let componentToRender = route.component;\n // Support Lazy Loading\n if (typeof componentToRender === 'function' && !componentToRender.prototype) {\n const module = yield componentToRender();\n componentToRender = module.default || module;\n }\n if (typeof componentToRender === 'function') {\n // Class component SSR\n // We need a dummy container for the component to \"render\" into its own buffer\n // For simplicity in this string-based framework, we mock the container\n const mockContainer = { innerHTML: '' };\n const instance = new componentToRender(mockContainer);\n if (instance.setParams)\n instance.setParams(params);\n // Manually trigger mount logic without DOM effects if possible, or just template()\n // Ideally, we just want the template string.\n return instance.template();\n }\n else {\n return componentToRender;\n }\n }\n return '<!-- 404 -->';\n });\n }\n matchRoute(hash) {\n // Simple exact match first\n let route = this.routes.find((r) => r.path === hash);\n if (route)\n return { route, params: {} };\n // Regex match for params e.g. /user/:id\n for (const r of this.routes) {\n const paramNames = [];\n const regexPath = r.path.replace(/:([^/]+)/g, (_, key) => {\n paramNames.push(key);\n return '([^/]+)';\n });\n const match = new RegExp(`^${regexPath}$`).exec(hash);\n if (match) {\n const params = {};\n paramNames.forEach((name, i) => {\n // SECURE: Automatically sanitize all route parameters\n params[name] = _security_sanitizer__WEBPACK_IMPORTED_MODULE_1__.Security.sanitize(match[i + 1]);\n });\n return { route: r, params };\n }\n }\n return { route: undefined, params: {} };\n }\n handleRoute() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.isServer)\n return;\n const currentRouteId = ++this.lastRouteId;\n const hash = window.location.hash.slice(1) || '/';\n const { route, params } = this.matchRoute(hash);\n // Security Check: Validate URL to prevent malicious hash injection\n if (hash !== '/' && !_security_sanitizer__WEBPACK_IMPORTED_MODULE_1__.Security.validateUrl('http://dummy.com' + hash)) {\n console.error(\"Security Alert: Malformed URL detected.\");\n return;\n }\n // Navigation Guard (Middleware)\n if (route === null || route === void 0 ? void 0 : route.beforeEnter) {\n yield new Promise((resolve) => {\n route.beforeEnter(hash, this.currentPath, (allow) => {\n if (allow)\n resolve();\n else {\n console.warn(`Navigation to ${hash} blocked by guard.`);\n // Ideally redirect or stay, here we just stop processing\n throw new Error('Navigation Blocked');\n }\n });\n }).catch(() => { return; }); // Stop execution if blocked\n }\n this.currentPath = hash;\n if (route) {\n if (route.title) {\n document.title = route.title;\n }\n else if (route.meta && route.meta.title) {\n // Fallback to meta.title if used\n document.title = route.meta.title;\n }\n if (this.rootContainer) {\n // Mulan Cycle: Destroy previous component before rendering new one\n if (this.currentComponent) {\n console.log(`[Router] Navigation from ${this.currentPath} to ${hash}. Destroying previous component.`);\n if (this.currentComponent.onDestroy) {\n this.currentComponent.onDestroy();\n }\n }\n this.rootContainer.innerHTML = ''; // Clear previous content\n }\n let componentToRender = route.component;\n // Support Lazy Loading\n if (typeof componentToRender === 'function' && !componentToRender.prototype) {\n try {\n const module = yield componentToRender();\n if (currentRouteId !== this.lastRouteId) {\n console.log(`[Router] Navigation to ${hash} interrupted by newer navigation. Abandoning.`);\n return;\n }\n componentToRender = module.default || module;\n }\n catch (e) {\n console.error(\"Failed to lazy load component\", e);\n return;\n }\n }\n if (typeof componentToRender === 'function') {\n // It's a class component\n if (this.rootContainer) {\n const instance = new componentToRender(this.rootContainer);\n this.currentComponent = instance;\n // Inject params if the component accepts them\n if (instance.setParams) {\n instance.setParams(params);\n }\n instance.mount();\n }\n }\n else if (typeof componentToRender === 'object' && componentToRender.template) {\n // Object Component (Simple SFC without script or Options API)\n const html = componentToRender.template();\n if (this.rootContainer)\n (0,_core_renderer__WEBPACK_IMPORTED_MODULE_0__.render)(html, this.rootContainer);\n this.currentComponent = null;\n }\n else {\n // Simple HTML string/template\n if (this.rootContainer)\n (0,_core_renderer__WEBPACK_IMPORTED_MODULE_0__.render)(componentToRender, this.rootContainer);\n this.currentComponent = null; // String templates don't have lifecycle instances\n }\n }\n else {\n if (this.rootContainer)\n (0,_core_renderer__WEBPACK_IMPORTED_MODULE_0__.render)('<div style=\"text-align:center; padding:50px;\"><h1>404</h1><p>Page Not Found</p></div>', this.rootContainer);\n }\n });\n }\n // [Chronos] Prefetch a route's component code in the background\n prefetch(path) {\n return __awaiter(this, void 0, void 0, function* () {\n if (this.isServer)\n return;\n const { route } = this.matchRoute(path);\n if (route) {\n let componentToRender = route.component;\n // Check if it's a lazy-loaded function that hasn't been resolved yet\n if (typeof componentToRender === 'function' && !componentToRender.prototype) {\n // If it's already a resolved module (from previous prefetch), componentToRender might be the result.\n // But typically in our simple implementation, route.component stays as the function until we replace it.\n // To avoid double-fetching, we can check if it has a specific flag or property. \n // For this implementation, we'll just run it and let the browser cache the module request (standard ES Module behavior).\n try {\n // console.log(`[Chronos] Prefetching ${path}...`);\n yield componentToRender();\n // We don't need to do anything with the result here. \n // The browser's module cache will handle the speedup when the user actually navigates.\n }\n catch (e) {\n console.warn(`[Chronos] Failed to prefetch ${path}`, e);\n }\n }\n }\n });\n }\n navigate(path) {\n if (this.isServer) {\n this.currentPath = path;\n }\n else {\n window.location.hash = path;\n }\n }\n}\n// --- Factory for Easy Usage ---\nconst createRouter = (options) => {\n // Expose the router instance globally for <mu-link> to access\n const router = new MuRouter(options.routes, options.rootContainer);\n if (typeof window !== 'undefined') {\n window.__MULAN_ROUTER__ = router;\n }\n return router;\n};\n// --- Web Component: <mu-link> ---\n// Usage: <mu-link to=\"/about\">About Us</mu-link>\nif (typeof window !== 'undefined' && !customElements.get('mu-link')) {\n class MuLink extends HTMLElement {\n constructor() {\n super();\n this.addEventListener('click', (e) => {\n e.preventDefault();\n const to = this.getAttribute('to');\n if (to) {\n // Update Hash for SPA Navigation\n window.location.hash = to;\n }\n });\n // [Chronos] Intelligent Pre-fetching\n this.addEventListener('mouseenter', () => {\n const to = this.getAttribute('to');\n if (to) {\n const router = window.__MULAN_ROUTER__;\n if (router && typeof router.prefetch === 'function') {\n router.prefetch(to);\n }\n }\n });\n // [Chronos] Also prefetch on focus for keyboard users\n this.addEventListener('focus', () => {\n const to = this.getAttribute('to');\n if (to) {\n const router = window.__MULAN_ROUTER__;\n if (router && typeof router.prefetch === 'function') {\n router.prefetch(to);\n }\n }\n });\n }\n connectedCallback() {\n this.style.cursor = 'pointer';\n this.style.color = 'var(--primary, #9C27B0)'; // Default to brand color if available\n this.style.textDecoration = 'none';\n }\n static get observedAttributes() { return ['to']; }\n }\n customElements.define('mu-link', MuLink);\n}\n\n\n//# sourceURL=webpack://Mulan/./src/router/index.ts?\n}");
|
|
140
2032
|
|
|
141
|
-
/***/ },
|
|
142
2033
|
|
|
143
|
-
/***/ "./src/security/sanitizer.ts"
|
|
144
|
-
/*!***********************************!*\
|
|
145
|
-
!*** ./src/security/sanitizer.ts ***!
|
|
146
|
-
\***********************************/
|
|
147
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
148
2034
|
|
|
149
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Security: () => (/* binding */ Security)\n/* harmony export */ });\nclass Security {\n /**\n * IRON FORTRESS PROTOCOL\n * Strictly escapes all HTML entities to prevent XSS.\n * Use `mu-raw` attribute in templates to bypass this for trusted content.\n */\n static sanitize(input) {\n // 1. Basic entity encoding\n let secure = input\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n // 2. Remove dangerous events (extra layer if encoding fails)\n const dangerousEvents = ['onload', 'onclick', 'onerror', 'onmouseover', 'onfocus'];\n dangerousEvents.forEach(event => {\n const regex = new RegExp(event, 'gi');\n secure = secure.replace(regex, 'data-blocked-' + event);\n });\n return secure;\n }\n /**\n * Generates a strict Content Security Policy header value.\n * @param options Configuration for allowed sources\n */\n static generateCSP(options = {}) {\n const scriptSrc = [\"'self'\", ...(options.scriptSrc || [])].join(\" \");\n const styleSrc = [\"'self'\", \"'unsafe-inline'\", ...(options.styleSrc || [])].join(\" \");\n return `default-src 'self'; script-src ${scriptSrc}; style-src ${styleSrc}; object-src 'none'; base-uri 'self';`;\n }\n static validateUrl(url) {\n // Basic URL validation\n const pattern = new RegExp('^(https?:\\\\/\\\\/)?' + // protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // domain name\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*' + // port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // query string\n '(\\\\#[-a-z\\\\d_]*)?$', 'i'); // fragment locator\n return !!pattern.test(url);\n }\n /**\n * Prevents XSS by sanitizing common input fields on blur.\n * Can be used as a utility in forms.\n */\n static preventXSS(inputElement) {\n inputElement.addEventListener('blur', (e) => {\n const target = e.target;\n target.value = Security.sanitize(target.value);\n });\n }\n}\n\n\n//# sourceURL=webpack://Mulan/./src/security/sanitizer.ts?\n}");
|
|
150
2035
|
|
|
151
|
-
/***/ },
|
|
152
2036
|
|
|
153
|
-
/***/ "./src/store/index.ts"
|
|
154
|
-
/*!****************************!*\
|
|
155
|
-
!*** ./src/store/index.ts ***!
|
|
156
|
-
\****************************/
|
|
157
|
-
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
158
2037
|
|
|
159
|
-
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MuStore: () => (/* binding */ MuStore)\n/* harmony export */ });\n/* harmony import */ var _core_reactive__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/reactive */ \"./src/core/reactive.ts\");\n\nclass MuStore {\n constructor(initialState, options) {\n this.subscribers = [];\n // Load from local storage if persist is true\n let loadedState = initialState;\n if (options === null || options === void 0 ? void 0 : options.persist) {\n const key = options.key || 'mulan-store';\n try {\n const stored = localStorage.getItem(key);\n if (stored) {\n loadedState = Object.assign(Object.assign({}, initialState), JSON.parse(stored));\n }\n }\n catch (e) {\n console.error(\"Failed to load state\", e);\n }\n // Auto-save effect\n (0,_core_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(() => {\n localStorage.setItem(key, JSON.stringify(this.state));\n });\n }\n this.state = (0,_core_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)(loadedState);\n }\n // Subscribe to changes\n subscribe(fn) {\n this.subscribers.push(fn);\n (0,_core_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(() => {\n fn(this.state);\n });\n }\n // Action dispatcher pattern\n dispatch(action) {\n const result = action(this.state);\n if (result instanceof Promise) {\n result.then(() => {\n // Optional: Notify subscribers of async completion if needed manually?\n // But reactive() handles updates automatically.\n });\n }\n }\n}\n\n\n//# sourceURL=webpack://Mulan/./src/store/index.ts?\n}");
|
|
160
2038
|
|
|
161
|
-
/***/ }
|
|
162
2039
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
/******/ __webpack_require__.d = (exports, definition) => {
|
|
200
|
-
/******/ for(var key in definition) {
|
|
201
|
-
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
|
|
202
|
-
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
|
203
|
-
/******/ }
|
|
204
|
-
/******/ }
|
|
205
|
-
/******/ };
|
|
206
|
-
/******/ })();
|
|
207
|
-
/******/
|
|
208
|
-
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
|
209
|
-
/******/ (() => {
|
|
210
|
-
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
|
|
211
|
-
/******/ })();
|
|
212
|
-
/******/
|
|
213
|
-
/******/ /* webpack/runtime/make namespace object */
|
|
214
|
-
/******/ (() => {
|
|
215
|
-
/******/ // define __esModule on exports
|
|
216
|
-
/******/ __webpack_require__.r = (exports) => {
|
|
217
|
-
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
|
|
218
|
-
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
219
|
-
/******/ }
|
|
220
|
-
/******/ Object.defineProperty(exports, '__esModule', { value: true });
|
|
221
|
-
/******/ };
|
|
222
|
-
/******/ })();
|
|
223
|
-
/******/
|
|
224
|
-
/************************************************************************/
|
|
225
|
-
/******/
|
|
226
|
-
/******/ // startup
|
|
227
|
-
/******/ // Load entry module and return exports
|
|
228
|
-
/******/ // This entry module can't be inlined because the eval devtool is used.
|
|
229
|
-
/******/ var __webpack_exports__ = __webpack_require__("./src/index.ts");
|
|
230
|
-
/******/ __webpack_exports__ = __webpack_exports__["default"];
|
|
231
|
-
/******/
|
|
2040
|
+
const Mulan = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ reactive: reactive,
|
|
2041
|
+
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,
|
|
2042
|
+
// MULAN INSIGHT: Branded Logging
|
|
2043
|
+
log: (msg, ...args) => {
|
|
2044
|
+
console.log(`%c[MulanJS]%c ${msg}`, "color: #ff3e00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
|
|
2045
|
+
}, warn: (msg, ...args) => {
|
|
2046
|
+
console.warn(`%c[MulanJS]%c ${msg}`, "color: #ffcc00; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
|
|
2047
|
+
}, error: (msg, ...args) => {
|
|
2048
|
+
console.error(`%c[MulanJS]%c ${msg}`, "color: #ff0000; font-weight: bold; background: #222; padding: 2px 4px; border-radius: 3px;", "", ...args);
|
|
2049
|
+
} });
|
|
2050
|
+
// Security: Freeze the object to prevent runtime tampering
|
|
2051
|
+
Object.freeze(Mulan);
|
|
2052
|
+
Object.freeze(Mulan.Security);
|
|
2053
|
+
// MULAN INSIGHT: Initialize Global Registry
|
|
2054
|
+
if (typeof window !== 'undefined') {
|
|
2055
|
+
window.__MULAN_INSIGHT__ = window.__MULAN_INSIGHT__ || { components: new Map() };
|
|
2056
|
+
// MULAN INSIGHT: HMR Support
|
|
2057
|
+
window.__MULAN_REFRESH__ = () => {
|
|
2058
|
+
var _a;
|
|
2059
|
+
const components = (_a = window.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components;
|
|
2060
|
+
if (components) {
|
|
2061
|
+
components.forEach((comp) => {
|
|
2062
|
+
if (comp && typeof comp.update === 'function') {
|
|
2063
|
+
// Force refresh
|
|
2064
|
+
comp.update();
|
|
2065
|
+
}
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
if (typeof window !== 'undefined') {
|
|
2071
|
+
window.Mulan = Mulan;
|
|
2072
|
+
}
|
|
2073
|
+
/* harmony default export */ const src = (Mulan);
|
|
2074
|
+
|
|
2075
|
+
__webpack_exports__ = __webpack_exports__["default"];
|
|
232
2076
|
/******/ return __webpack_exports__;
|
|
233
2077
|
/******/ })()
|
|
234
2078
|
;
|
|
235
|
-
});
|
|
2079
|
+
});
|
|
2080
|
+
//# sourceMappingURL=mulan.js.map
|