@mulanjs/mulanjs 1.0.1-dev.20260212143840
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/LICENSE +21 -0
- package/README.md +1 -0
- package/dist/compiler/compiler.js +90 -0
- package/dist/compiler/script-compiler.js +314 -0
- package/dist/compiler/sfc-parser.js +93 -0
- package/dist/compiler/style-compiler.js +56 -0
- package/dist/compiler/template-compiler.js +442 -0
- package/dist/components/bloch-sphere.js +252 -0
- package/dist/core/component.js +145 -0
- package/dist/core/hooks.js +229 -0
- package/dist/core/quantum.js +284 -0
- package/dist/core/query.js +63 -0
- package/dist/core/reactive.js +105 -0
- package/dist/core/renderer.js +70 -0
- package/dist/core/vault.js +81 -0
- package/dist/index.js +52 -0
- package/dist/mulan.esm.js +1948 -0
- package/dist/mulan.js +215 -0
- package/dist/router/index.js +210 -0
- package/dist/security/sanitizer.js +47 -0
- package/dist/store/index.js +42 -0
- package/dist/types/compiler/compiler.d.ts +7 -0
- package/dist/types/compiler/script-compiler.d.ts +8 -0
- package/dist/types/compiler/sfc-parser.d.ts +21 -0
- package/dist/types/compiler/style-compiler.d.ts +7 -0
- package/dist/types/compiler/template-compiler.d.ts +7 -0
- package/dist/types/compiler.d.ts +7 -0
- package/dist/types/components/bloch-sphere.d.ts +16 -0
- package/dist/types/core/component.d.ts +54 -0
- package/dist/types/core/hooks.d.ts +49 -0
- package/dist/types/core/quantum.d.ts +50 -0
- package/dist/types/core/query.d.ts +14 -0
- package/dist/types/core/reactive.d.ts +21 -0
- package/dist/types/core/renderer.d.ts +4 -0
- package/dist/types/core/vault.d.ts +12 -0
- package/dist/types/index.d.ts +70 -0
- package/dist/types/router/index.d.ts +24 -0
- package/dist/types/script-compiler.d.ts +8 -0
- package/dist/types/security/sanitizer.d.ts +17 -0
- package/dist/types/sfc-parser.d.ts +21 -0
- package/dist/types/store/index.d.ts +10 -0
- package/dist/types/style-compiler.d.ts +7 -0
- package/dist/types/template-compiler.d.ts +7 -0
- package/package.json +64 -0
- package/src/cli/extensions/mulanjs-vscode-1.0.0.vsix +0 -0
- package/src/cli/index.js +600 -0
- package/src/compiler/compiler.ts +102 -0
- package/src/compiler/script-compiler.ts +336 -0
- package/src/compiler/sfc-parser.ts +118 -0
- package/src/compiler/style-compiler.ts +66 -0
- package/src/compiler/template-compiler.ts +519 -0
- package/src/compiler/tsconfig.json +13 -0
- package/src/loader/index.js +81 -0
package/dist/mulan.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
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
|
+
(function webpackUniversalModuleDefinition(root, factory) {
|
|
10
|
+
if(typeof exports === 'object' && typeof module === 'object')
|
|
11
|
+
module.exports = factory();
|
|
12
|
+
else if(typeof define === 'function' && define.amd)
|
|
13
|
+
define([], factory);
|
|
14
|
+
else if(typeof exports === 'object')
|
|
15
|
+
exports["Mulan"] = factory();
|
|
16
|
+
else
|
|
17
|
+
root["Mulan"] = factory();
|
|
18
|
+
})(this, () => {
|
|
19
|
+
return /******/ (() => { // webpackBootstrap
|
|
20
|
+
/******/ "use strict";
|
|
21
|
+
/******/ var __webpack_modules__ = ({
|
|
22
|
+
|
|
23
|
+
/***/ "./src/components/bloch-sphere.ts"
|
|
24
|
+
/*!****************************************!*\
|
|
25
|
+
!*** ./src/components/bloch-sphere.ts ***!
|
|
26
|
+
\****************************************/
|
|
27
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
28
|
+
|
|
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
|
+
|
|
31
|
+
/***/ },
|
|
32
|
+
|
|
33
|
+
/***/ "./src/core/component.ts"
|
|
34
|
+
/*!*******************************!*\
|
|
35
|
+
!*** ./src/core/component.ts ***!
|
|
36
|
+
\*******************************/
|
|
37
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
38
|
+
|
|
39
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MuComponent: () => (/* binding */ MuComponent),\n/* harmony export */ defineComponent: () => (/* binding */ defineComponent)\n/* harmony export */ });\n/* harmony import */ var _renderer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./renderer */ \"./src/core/renderer.ts\");\n/* harmony import */ var _hooks__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hooks */ \"./src/core/hooks.ts\");\n/* harmony import */ var _reactive__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./reactive */ \"./src/core/reactive.ts\");\n\n\n\n// Or a simple component that returns an object of state/methods used by template? \n// For Mulan 2.0, let's say functional component returns a template string render function explicitly.\nclass MuComponent {\n constructor(container) {\n this._hooks = {};\n this._effects = [];\n this._isDestroyed = false;\n this._propsQueue = [];\n this._eventQueue = [];\n this.container = container;\n this.state = {};\n this.$uid = 'mu_' + Math.random().toString(36).substr(2, 9);\n // MULAN INSIGHT: Global Registry for Debugging\n if (typeof window !== 'undefined') {\n const global = window;\n global.__MULAN_INSIGHT__ = global.__MULAN_INSIGHT__ || { components: new Map() };\n global.__MULAN_INSIGHT__.components.set(this.$uid, this);\n }\n // Setup context for hooks\n (0,_hooks__WEBPACK_IMPORTED_MODULE_1__.setCurrentInstance)(this);\n this.setup();\n (0,_hooks__WEBPACK_IMPORTED_MODULE_1__.setCurrentInstance)(null);\n }\n // Optional setup method for class components wanting to use hooks\n setup() { }\n onMount() {\n var _a, _c;\n // Mulan Cycle: Init\n (_a = this._hooks.onMuInit) === null || _a === void 0 ? void 0 : _a.forEach(fn => fn());\n // Mulan Cycle: Mount (Simulated immediately after init for now in this version)\n (_c = this._hooks.onMuMount) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());\n }\n onUpdate() { }\n onDestroy() {\n var _a, _c;\n if (this._isDestroyed)\n return;\n this._isDestroyed = true;\n console.log(`[Mulan Cycle] Destroying component ${this.$uid} (${this.constructor.name})`);\n // MULAN INSIGHT: Cleanup\n if (typeof window !== 'undefined') {\n const global = window;\n (_a = global.__MULAN_INSIGHT__) === null || _a === void 0 ? void 0 : _a.components.delete(this.$uid);\n }\n // Mulan Cycle: Stop all effects to prevent leaks\n console.log(`[Mulan Cycle] Stopping ${this._effects.length} effects for ${this.$uid}`);\n this._effects.forEach(stop => stop());\n this._effects = [];\n // Mulan Cycle: Destroy hooks\n (_c = this._hooks.onMuDestroy) === null || _c === void 0 ? void 0 : _c.forEach(fn => fn());\n }\n // Helper for compiler to register property bindings\n _b(id, prop, value) {\n this._propsQueue.push([id, prop, value]);\n return \"\";\n }\n // Helper for compiler to register event bindings\n _e(id, type, handler) {\n this._eventQueue.push([id, type, handler]);\n return \"\";\n }\n mount() {\n console.log(`[Mulan Cycle] Mounting component ${this.$uid}`);\n const stop = (0,_reactive__WEBPACK_IMPORTED_MODULE_2__.effect)(() => {\n console.log(`[Mulan Reactivity] Triggering update for ${this.$uid}`);\n this.update();\n });\n this._effects.push(stop);\n this.onMount();\n }\n update() {\n if (this._isDestroyed) {\n console.warn(`[Mulan Warning] Update called on destroyed component ${this.$uid}. Blocking render.`);\n return;\n }\n // Clear queues before render\n this._propsQueue = [];\n this._eventQueue = [];\n const template = this.template();\n // Render HTML\n (0,_renderer__WEBPACK_IMPORTED_MODULE_0__.render)(template, this.container);\n // Flush Side Effects\n this.flushProps();\n this.flushEvents();\n this.onUpdate();\n }\n flushProps() {\n for (const [id, prop, value] of this._propsQueue) {\n const el = this.container.querySelector(`[data-mu-id=\"${id}\"]`);\n if (el) {\n // @ts-ignore\n el[prop] = value;\n }\n }\n this._propsQueue = [];\n }\n flushEvents() {\n for (const [id, type, handler] of this._eventQueue) {\n const el = this.container.querySelector(`[data-mu-id=\"${id}\"]`);\n if (el) {\n // Bind handler to this component instance to ensure 'this' works in methods\n el.addEventListener(type, handler.bind(this));\n }\n }\n this._eventQueue = [];\n }\n}\n// Helper to create functional components wrapped in the class system\n// Helper to create functional components wrapped in the class system\n// Supports both () => render and { setup() } signatures\nfunction defineComponent(optionsOrSetup) {\n return class UniversalComponent extends MuComponent {\n constructor(container) {\n super(container);\n // setup() is called by super constructor\n }\n setup() {\n let setupResult;\n if (typeof optionsOrSetup === 'function') {\n // It's a setup function returning render fn\n setupResult = optionsOrSetup.call(this);\n }\n else if (typeof optionsOrSetup === 'object' && optionsOrSetup.setup) {\n // It's an options object with setup()\n setupResult = optionsOrSetup.setup.call(this);\n }\n // Handle result\n if (typeof setupResult === 'function') {\n // It's a render function\n this.template = setupResult;\n }\n else if (setupResult && typeof setupResult === 'object') {\n // It's bindings\n Object.assign(this, setupResult);\n // We assume template is assigned to prototype by compiler\n }\n }\n template() {\n return '';\n }\n };\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/component.ts?\n}");
|
|
40
|
+
|
|
41
|
+
/***/ },
|
|
42
|
+
|
|
43
|
+
/***/ "./src/core/hooks.ts"
|
|
44
|
+
/*!***************************!*\
|
|
45
|
+
!*** ./src/core/hooks.ts ***!
|
|
46
|
+
\***************************/
|
|
47
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
48
|
+
|
|
49
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getCurrentInstance: () => (/* binding */ getCurrentInstance),\n/* harmony export */ muEffect: () => (/* binding */ muEffect),\n/* harmony export */ muGeom: () => (/* binding */ muGeom),\n/* harmony export */ muMemo: () => (/* binding */ muMemo),\n/* harmony export */ muPulse: () => (/* binding */ muPulse),\n/* harmony export */ muState: () => (/* binding */ muState),\n/* harmony export */ muVault: () => (/* binding */ muVault),\n/* harmony export */ onMuDestroy: () => (/* binding */ onMuDestroy),\n/* harmony export */ onMuIdle: () => (/* binding */ onMuIdle),\n/* harmony export */ onMuInit: () => (/* binding */ onMuInit),\n/* harmony export */ onMuMount: () => (/* binding */ onMuMount),\n/* harmony export */ onMuResume: () => (/* binding */ onMuResume),\n/* harmony export */ onMuShake: () => (/* binding */ onMuShake),\n/* harmony export */ onMuVoice: () => (/* binding */ onMuVoice),\n/* harmony export */ setCurrentInstance: () => (/* binding */ setCurrentInstance)\n/* harmony export */ });\n/* harmony import */ var _reactive__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reactive */ \"./src/core/reactive.ts\");\n/* harmony import */ var _vault__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vault */ \"./src/core/vault.ts\");\n\n\n// Global context to track the current component instance\nlet currentInstance = null;\nfunction setCurrentInstance(instance) {\n currentInstance = instance;\n}\nfunction getCurrentInstance() {\n return currentInstance;\n}\n// --- Mulan Unique Reactivity Hooks ---\nfunction muState(initialValue) {\n if (typeof initialValue === 'object' && initialValue !== null) {\n return (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)(initialValue);\n }\n // Core reactive state container for primitives\n return (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)({ value: initialValue });\n}\nfunction muMemo(computeFn) {\n const signal = (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)({ value: undefined });\n const stop = (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(() => {\n signal.value = computeFn();\n });\n const instance = getCurrentInstance();\n if (instance) {\n if (!instance._effects)\n instance._effects = [];\n instance._effects.push(stop);\n }\n return signal;\n}\nfunction muEffect(fn) {\n const stop = (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(fn);\n const instance = getCurrentInstance();\n if (instance) {\n if (!instance._effects)\n instance._effects = [];\n instance._effects.push(stop);\n }\n}\n// --- The \"Mulan Cycle\" (Lifecycle) ---\nfunction onMuInit(fn) {\n const instance = getCurrentInstance();\n if (instance) {\n if (!instance._hooks)\n instance._hooks = {};\n if (!instance._hooks.onMuInit)\n instance._hooks.onMuInit = [];\n instance._hooks.onMuInit.push(fn);\n }\n else {\n console.warn('onMuInit called outside of component setup context.');\n }\n}\nfunction onMuMount(fn) {\n // New hook for when component is actually in DOM (simulated for now via update)\n const instance = getCurrentInstance();\n if (instance) {\n if (!instance._hooks)\n instance._hooks = {};\n if (!instance._hooks.onMuMount)\n instance._hooks.onMuMount = [];\n instance._hooks.onMuMount.push(fn);\n }\n}\nfunction onMuDestroy(fn) {\n const instance = getCurrentInstance();\n if (instance) {\n if (!instance._hooks)\n instance._hooks = {};\n if (!instance._hooks.onMuDestroy)\n instance._hooks.onMuDestroy = [];\n instance._hooks.onMuDestroy.push(fn);\n }\n}\n/**\n * onMuIdle - The \"Environment Life\" Hook.\n * Executes heavy logic ONLY when the browser is taking a nap (idle).\n */\nfunction onMuIdle(fn) {\n const instance = getCurrentInstance();\n // Polyfill for Safari/Old Browsers\n const requestIdleCallback = window.requestIdleCallback || function (cb) {\n return setTimeout(() => {\n cb({\n didTimeout: false,\n timeRemaining: function () { return 50; }\n });\n }, 1);\n };\n const cancelIdleCallback = window.cancelIdleCallback || function (id) {\n clearTimeout(id);\n };\n const idleId = requestIdleCallback(() => {\n fn();\n });\n // Auto-cleanup if component dies before idle time\n if (instance) {\n onMuDestroy(() => {\n cancelIdleCallback(idleId);\n });\n }\n}\n/**\n * onMuResume - The \"Tab Life\" Hook.\n * Executes when the user switches BACK to this tab.\n * Perfect for refreshing data or resuming animations to save battery.\n */\nfunction onMuResume(fn) {\n const handler = () => {\n if (document.visibilityState === 'visible') {\n fn();\n }\n };\n document.addEventListener('visibilitychange', handler);\n onMuDestroy(() => document.removeEventListener('visibilitychange', handler));\n}\n/**\n * onMuShake - The \"Physical Life\" Hook.\n * Executes when the device is shaken.\n * Usage: Undo, Refresh, or \"Rage Quit\" easter eggs.\n */\nfunction onMuShake(fn) {\n // Threshold for shake detection\n const threshold = 15;\n let lastX = 0, lastY = 0, lastZ = 0;\n let lastTime = 0;\n const handler = (e) => {\n const current = e.accelerationIncludingGravity;\n if (!current)\n return;\n const time = Date.now();\n if ((time - lastTime) > 100) {\n const diffTime = time - lastTime;\n lastTime = time;\n const x = current.x || 0;\n const y = current.y || 0;\n const z = current.z || 0;\n const speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;\n if (speed > threshold) {\n fn();\n }\n lastX = x;\n lastY = y;\n lastZ = z;\n }\n };\n if (window.DeviceMotionEvent) {\n window.addEventListener('devicemotion', handler);\n onMuDestroy(() => window.removeEventListener('devicemotion', handler));\n }\n else {\n console.warn(\"[MulanJS] Device Motion not supported on this device.\");\n }\n}\n/**\n * onMuVoice - The \"Sound Life\" Hook.\n * Executes when a specific word is spoken.\n * @param command The word to listen for (e.g., \"save\", \"next\")\n * @param fn The action to take\n */\nfunction onMuVoice(command, fn) {\n const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;\n if (!SpeechRecognition) {\n console.warn(\"[MulanJS] Voice Control (Web Speech API) not supported in this browser.\");\n return;\n }\n const recognition = new SpeechRecognition();\n recognition.continuous = true;\n recognition.lang = 'en-US';\n recognition.interimResults = false;\n recognition.onresult = (event) => {\n const last = event.results.length - 1;\n const spoken = event.results[last][0].transcript.trim().toLowerCase();\n console.log(`[Mulan Voice] Heard: \"${spoken}\"`);\n if (spoken.includes(command.toLowerCase())) {\n fn();\n }\n };\n recognition.start();\n // Auto-restart if it stops (Continuous listening)\n recognition.onend = () => {\n // Simple check to see if we should still be listening\n // In a real app we might want more control\n // recognition.start(); \n };\n onMuDestroy(() => {\n recognition.stop();\n });\n}\n// --- \"Outside The Box\" Hooks (Mulan Exclusives) ---\n/**\n * muGeom - Tracks window or element dimensions reactively.\n */\nfunction muGeom() {\n const dims = muState({ width: window.innerWidth, height: window.innerHeight });\n const handler = () => {\n dims.width = window.innerWidth;\n dims.height = window.innerHeight;\n };\n window.addEventListener('resize', handler);\n // Auto-cleanup\n onMuDestroy(() => {\n window.removeEventListener('resize', handler);\n });\n return dims;\n}\n/**\n * muPulse - Reactive network status.\n */\nfunction muPulse() {\n const status = muState({ online: navigator.onLine });\n const setOnline = () => status.online = true;\n const setOffline = () => status.online = false;\n window.addEventListener('online', setOnline);\n window.addEventListener('offline', setOffline);\n onMuDestroy(() => {\n window.removeEventListener('online', setOnline);\n window.removeEventListener('offline', setOffline);\n });\n return status;\n}\n/**\n * muVault - Secure reactive LocalStorage wrapper.\n * Powered by the Iron Fortress persistent primitive.\n */\nfunction muVault(key, initial, options = {}) {\n return (0,_vault__WEBPACK_IMPORTED_MODULE_1__.persistent)(key, initial, options);\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/hooks.ts?\n}");
|
|
50
|
+
|
|
51
|
+
/***/ },
|
|
52
|
+
|
|
53
|
+
/***/ "./src/core/quantum.ts"
|
|
54
|
+
/*!*****************************!*\
|
|
55
|
+
!*** ./src/core/quantum.ts ***!
|
|
56
|
+
\*****************************/
|
|
57
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
58
|
+
|
|
59
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ muEntangle: () => (/* binding */ muEntangle),\n/* harmony export */ muGate: () => (/* binding */ muGate),\n/* harmony export */ muMeasure: () => (/* binding */ muMeasure),\n/* harmony export */ muQubit: () => (/* binding */ muQubit),\n/* harmony export */ muRegister: () => (/* binding */ muRegister),\n/* harmony export */ muSearch: () => (/* binding */ muSearch),\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 * 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 // Helper: Check if all control bits are 1\n const checkControl = (index, ctrl) => {\n if (ctrl === undefined)\n return true;\n if (typeof ctrl === 'number') {\n return ((index >> ctrl) & 1) === 1;\n }\n return ctrl.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 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, control))\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, control))\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, control))\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, control))\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\n//# sourceURL=webpack://Mulan/./src/core/quantum.ts?\n}");
|
|
60
|
+
|
|
61
|
+
/***/ },
|
|
62
|
+
|
|
63
|
+
/***/ "./src/core/query.ts"
|
|
64
|
+
/*!***************************!*\
|
|
65
|
+
!*** ./src/core/query.ts ***!
|
|
66
|
+
\***************************/
|
|
67
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
68
|
+
|
|
69
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ useMutation: () => (/* binding */ useMutation),\n/* harmony export */ useQuery: () => (/* binding */ useQuery)\n/* harmony export */ });\n/* harmony import */ var _reactive__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reactive */ \"./src/core/reactive.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\nfunction useQuery(queryFn, options = { enabled: true }) {\n const state = (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)({\n data: null,\n isLoading: false,\n error: null\n });\n const execute = () => __awaiter(this, void 0, void 0, function* () {\n state.isLoading = true;\n state.error = null;\n try {\n const result = yield queryFn();\n state.data = result;\n }\n catch (err) {\n state.error = err;\n }\n finally {\n state.isLoading = false;\n }\n });\n if (options.enabled) {\n // Run automatically\n (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.effect)(() => {\n // Basic effect wrapper to allow reactivity if queryFn relies on signals\n execute();\n });\n }\n return Object.assign(Object.assign({}, state), { refetch: execute });\n}\nfunction useMutation(mutationFn) {\n const state = (0,_reactive__WEBPACK_IMPORTED_MODULE_0__.reactive)({\n data: null,\n isLoading: false,\n error: null\n });\n const mutate = (args) => __awaiter(this, void 0, void 0, function* () {\n state.isLoading = true;\n state.error = null;\n try {\n const result = yield mutationFn(args);\n state.data = result;\n return result;\n }\n catch (err) {\n state.error = err;\n throw err;\n }\n finally {\n state.isLoading = false;\n }\n });\n return Object.assign(Object.assign({}, state), { mutate });\n}\n\n\n//# sourceURL=webpack://Mulan/./src/core/query.ts?\n}");
|
|
70
|
+
|
|
71
|
+
/***/ },
|
|
72
|
+
|
|
73
|
+
/***/ "./src/core/reactive.ts"
|
|
74
|
+
/*!******************************!*\
|
|
75
|
+
!*** ./src/core/reactive.ts ***!
|
|
76
|
+
\******************************/
|
|
77
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
78
|
+
|
|
79
|
+
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}");
|
|
80
|
+
|
|
81
|
+
/***/ },
|
|
82
|
+
|
|
83
|
+
/***/ "./src/core/renderer.ts"
|
|
84
|
+
/*!******************************!*\
|
|
85
|
+
!*** ./src/core/renderer.ts ***!
|
|
86
|
+
\******************************/
|
|
87
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
88
|
+
|
|
89
|
+
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 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}\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}");
|
|
90
|
+
|
|
91
|
+
/***/ },
|
|
92
|
+
|
|
93
|
+
/***/ "./src/core/vault.ts"
|
|
94
|
+
/*!***************************!*\
|
|
95
|
+
!*** ./src/core/vault.ts ***!
|
|
96
|
+
\***************************/
|
|
97
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
98
|
+
|
|
99
|
+
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\nconst MULAN_SECRET = 'b3ast_mulan_s3cur1ty_k3y';\nfunction beastXOR(str) {\n let result = '';\n for (let i = 0; i < str.length; i++) {\n result += String.fromCharCode(str.charCodeAt(i) ^ MULAN_SECRET.charCodeAt(i % MULAN_SECRET.length));\n }\n return btoa(result);\n}\nfunction beastDecode(encoded) {\n const str = atob(encoded);\n let result = '';\n for (let i = 0; i < str.length; i++) {\n result += String.fromCharCode(str.charCodeAt(i) ^ MULAN_SECRET.charCodeAt(i % MULAN_SECRET.length));\n }\n return result;\n}\n/**\n * Mulan Vault: The World's First Native Persistent State Primitive.\n * Now fortified with Iron Fortress Obfuscation.\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 const raw = options.encrypt ? beastDecode(stored) : stored;\n startVal = JSON.parse(raw);\n }\n catch (e) {\n console.warn(`[Iron Fortress] 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 raw = JSON.stringify(payload);\n const toSave = options.encrypt ? beastXOR(raw) : raw;\n storage.setItem(key, toSave);\n }\n catch (e) {\n console.error(`[Iron Fortress] 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 raw = options.encrypt ? beastDecode(e.newValue) : e.newValue;\n const newVal = JSON.parse(raw);\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}");
|
|
100
|
+
|
|
101
|
+
/***/ },
|
|
102
|
+
|
|
103
|
+
/***/ "./src/index.ts"
|
|
104
|
+
/*!**********************!*\
|
|
105
|
+
!*** ./src/index.ts ***!
|
|
106
|
+
\**********************/
|
|
107
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
108
|
+
|
|
109
|
+
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_10__.MuBlochSphereElement),\n/* harmony export */ MuComponent: () => (/* reexport safe */ _core_component__WEBPACK_IMPORTED_MODULE_1__.MuComponent),\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 */ \"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 */ 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 */ 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 */ 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 _components_bloch_sphere__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./components/bloch-sphere */ \"./src/components/bloch-sphere.ts\");\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\nconst Mulan = 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, 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__), { \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}\nwindow.Mulan = Mulan;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Mulan);\n\n\n//# sourceURL=webpack://Mulan/./src/index.ts?\n}");
|
|
110
|
+
|
|
111
|
+
/***/ },
|
|
112
|
+
|
|
113
|
+
/***/ "./src/router/index.ts"
|
|
114
|
+
/*!*****************************!*\
|
|
115
|
+
!*** ./src/router/index.ts ***!
|
|
116
|
+
\*****************************/
|
|
117
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
118
|
+
|
|
119
|
+
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 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 return new MuRouter(options.routes, options.rootContainer);\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 }\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}");
|
|
120
|
+
|
|
121
|
+
/***/ },
|
|
122
|
+
|
|
123
|
+
/***/ "./src/security/sanitizer.ts"
|
|
124
|
+
/*!***********************************!*\
|
|
125
|
+
!*** ./src/security/sanitizer.ts ***!
|
|
126
|
+
\***********************************/
|
|
127
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
128
|
+
|
|
129
|
+
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 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}");
|
|
130
|
+
|
|
131
|
+
/***/ },
|
|
132
|
+
|
|
133
|
+
/***/ "./src/store/index.ts"
|
|
134
|
+
/*!****************************!*\
|
|
135
|
+
!*** ./src/store/index.ts ***!
|
|
136
|
+
\****************************/
|
|
137
|
+
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
|
|
138
|
+
|
|
139
|
+
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}");
|
|
140
|
+
|
|
141
|
+
/***/ }
|
|
142
|
+
|
|
143
|
+
/******/ });
|
|
144
|
+
/************************************************************************/
|
|
145
|
+
/******/ // The module cache
|
|
146
|
+
/******/ var __webpack_module_cache__ = {};
|
|
147
|
+
/******/
|
|
148
|
+
/******/ // The require function
|
|
149
|
+
/******/ function __webpack_require__(moduleId) {
|
|
150
|
+
/******/ // Check if module is in cache
|
|
151
|
+
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
152
|
+
/******/ if (cachedModule !== undefined) {
|
|
153
|
+
/******/ return cachedModule.exports;
|
|
154
|
+
/******/ }
|
|
155
|
+
/******/ // Check if module exists (development only)
|
|
156
|
+
/******/ if (__webpack_modules__[moduleId] === undefined) {
|
|
157
|
+
/******/ var e = new Error("Cannot find module '" + moduleId + "'");
|
|
158
|
+
/******/ e.code = 'MODULE_NOT_FOUND';
|
|
159
|
+
/******/ throw e;
|
|
160
|
+
/******/ }
|
|
161
|
+
/******/ // Create a new module (and put it into the cache)
|
|
162
|
+
/******/ var module = __webpack_module_cache__[moduleId] = {
|
|
163
|
+
/******/ // no module.id needed
|
|
164
|
+
/******/ // no module.loaded needed
|
|
165
|
+
/******/ exports: {}
|
|
166
|
+
/******/ };
|
|
167
|
+
/******/
|
|
168
|
+
/******/ // Execute the module function
|
|
169
|
+
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
170
|
+
/******/
|
|
171
|
+
/******/ // Return the exports of the module
|
|
172
|
+
/******/ return module.exports;
|
|
173
|
+
/******/ }
|
|
174
|
+
/******/
|
|
175
|
+
/************************************************************************/
|
|
176
|
+
/******/ /* webpack/runtime/define property getters */
|
|
177
|
+
/******/ (() => {
|
|
178
|
+
/******/ // define getter functions for harmony exports
|
|
179
|
+
/******/ __webpack_require__.d = (exports, definition) => {
|
|
180
|
+
/******/ for(var key in definition) {
|
|
181
|
+
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
|
|
182
|
+
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
|
183
|
+
/******/ }
|
|
184
|
+
/******/ }
|
|
185
|
+
/******/ };
|
|
186
|
+
/******/ })();
|
|
187
|
+
/******/
|
|
188
|
+
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
|
189
|
+
/******/ (() => {
|
|
190
|
+
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
|
|
191
|
+
/******/ })();
|
|
192
|
+
/******/
|
|
193
|
+
/******/ /* webpack/runtime/make namespace object */
|
|
194
|
+
/******/ (() => {
|
|
195
|
+
/******/ // define __esModule on exports
|
|
196
|
+
/******/ __webpack_require__.r = (exports) => {
|
|
197
|
+
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
|
|
198
|
+
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
199
|
+
/******/ }
|
|
200
|
+
/******/ Object.defineProperty(exports, '__esModule', { value: true });
|
|
201
|
+
/******/ };
|
|
202
|
+
/******/ })();
|
|
203
|
+
/******/
|
|
204
|
+
/************************************************************************/
|
|
205
|
+
/******/
|
|
206
|
+
/******/ // startup
|
|
207
|
+
/******/ // Load entry module and return exports
|
|
208
|
+
/******/ // This entry module can't be inlined because the eval devtool is used.
|
|
209
|
+
/******/ var __webpack_exports__ = __webpack_require__("./src/index.ts");
|
|
210
|
+
/******/ __webpack_exports__ = __webpack_exports__["default"];
|
|
211
|
+
/******/
|
|
212
|
+
/******/ return __webpack_exports__;
|
|
213
|
+
/******/ })()
|
|
214
|
+
;
|
|
215
|
+
});
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { render } from '../core/renderer';
|
|
11
|
+
import { Security } from '../security/sanitizer';
|
|
12
|
+
export class MuRouter {
|
|
13
|
+
constructor(routes, rootContainer = null) {
|
|
14
|
+
this.currentPath = '';
|
|
15
|
+
this.currentComponent = null;
|
|
16
|
+
this.lastRouteId = 0;
|
|
17
|
+
this.routes = routes;
|
|
18
|
+
this.rootContainer = rootContainer;
|
|
19
|
+
this.isServer = rootContainer === null; // If no container, assume server/headless mode
|
|
20
|
+
if (!this.isServer) {
|
|
21
|
+
window.addEventListener('hashchange', this.handleRoute.bind(this));
|
|
22
|
+
this.handleRoute(); // Initial load
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// SSR Method: Simulate a route visit on the server
|
|
26
|
+
serverLookup(path) {
|
|
27
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
28
|
+
this.currentPath = path;
|
|
29
|
+
const { route, params } = this.matchRoute(path);
|
|
30
|
+
if (route) {
|
|
31
|
+
// Run guards/resolvers here if needed
|
|
32
|
+
let componentToRender = route.component;
|
|
33
|
+
// Support Lazy Loading
|
|
34
|
+
if (typeof componentToRender === 'function' && !componentToRender.prototype) {
|
|
35
|
+
const module = yield componentToRender();
|
|
36
|
+
componentToRender = module.default || module;
|
|
37
|
+
}
|
|
38
|
+
if (typeof componentToRender === 'function') {
|
|
39
|
+
// Class component SSR
|
|
40
|
+
// We need a dummy container for the component to "render" into its own buffer
|
|
41
|
+
// For simplicity in this string-based framework, we mock the container
|
|
42
|
+
const mockContainer = { innerHTML: '' };
|
|
43
|
+
const instance = new componentToRender(mockContainer);
|
|
44
|
+
if (instance.setParams)
|
|
45
|
+
instance.setParams(params);
|
|
46
|
+
// Manually trigger mount logic without DOM effects if possible, or just template()
|
|
47
|
+
// Ideally, we just want the template string.
|
|
48
|
+
return instance.template();
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
return componentToRender;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return '<!-- 404 -->';
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
matchRoute(hash) {
|
|
58
|
+
// Simple exact match first
|
|
59
|
+
let route = this.routes.find((r) => r.path === hash);
|
|
60
|
+
if (route)
|
|
61
|
+
return { route, params: {} };
|
|
62
|
+
// Regex match for params e.g. /user/:id
|
|
63
|
+
for (const r of this.routes) {
|
|
64
|
+
const paramNames = [];
|
|
65
|
+
const regexPath = r.path.replace(/:([^/]+)/g, (_, key) => {
|
|
66
|
+
paramNames.push(key);
|
|
67
|
+
return '([^/]+)';
|
|
68
|
+
});
|
|
69
|
+
const match = new RegExp(`^${regexPath}$`).exec(hash);
|
|
70
|
+
if (match) {
|
|
71
|
+
const params = {};
|
|
72
|
+
paramNames.forEach((name, i) => {
|
|
73
|
+
// SECURE: Automatically sanitize all route parameters
|
|
74
|
+
params[name] = Security.sanitize(match[i + 1]);
|
|
75
|
+
});
|
|
76
|
+
return { route: r, params };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { route: undefined, params: {} };
|
|
80
|
+
}
|
|
81
|
+
handleRoute() {
|
|
82
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
83
|
+
if (this.isServer)
|
|
84
|
+
return;
|
|
85
|
+
const currentRouteId = ++this.lastRouteId;
|
|
86
|
+
const hash = window.location.hash.slice(1) || '/';
|
|
87
|
+
const { route, params } = this.matchRoute(hash);
|
|
88
|
+
// Security Check: Validate URL to prevent malicious hash injection
|
|
89
|
+
if (hash !== '/' && !Security.validateUrl('http://dummy.com' + hash)) {
|
|
90
|
+
console.error("Security Alert: Malformed URL detected.");
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
// Navigation Guard (Middleware)
|
|
94
|
+
if (route === null || route === void 0 ? void 0 : route.beforeEnter) {
|
|
95
|
+
yield new Promise((resolve) => {
|
|
96
|
+
route.beforeEnter(hash, this.currentPath, (allow) => {
|
|
97
|
+
if (allow)
|
|
98
|
+
resolve();
|
|
99
|
+
else {
|
|
100
|
+
console.warn(`Navigation to ${hash} blocked by guard.`);
|
|
101
|
+
// Ideally redirect or stay, here we just stop processing
|
|
102
|
+
throw new Error('Navigation Blocked');
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}).catch(() => { return; }); // Stop execution if blocked
|
|
106
|
+
}
|
|
107
|
+
this.currentPath = hash;
|
|
108
|
+
if (route) {
|
|
109
|
+
if (route.title) {
|
|
110
|
+
document.title = route.title;
|
|
111
|
+
}
|
|
112
|
+
else if (route.meta && route.meta.title) {
|
|
113
|
+
// Fallback to meta.title if used
|
|
114
|
+
document.title = route.meta.title;
|
|
115
|
+
}
|
|
116
|
+
if (this.rootContainer) {
|
|
117
|
+
// Mulan Cycle: Destroy previous component before rendering new one
|
|
118
|
+
if (this.currentComponent) {
|
|
119
|
+
console.log(`[Router] Navigation from ${this.currentPath} to ${hash}. Destroying previous component.`);
|
|
120
|
+
if (this.currentComponent.onDestroy) {
|
|
121
|
+
this.currentComponent.onDestroy();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
this.rootContainer.innerHTML = ''; // Clear previous content
|
|
125
|
+
}
|
|
126
|
+
let componentToRender = route.component;
|
|
127
|
+
// Support Lazy Loading
|
|
128
|
+
if (typeof componentToRender === 'function' && !componentToRender.prototype) {
|
|
129
|
+
try {
|
|
130
|
+
const module = yield componentToRender();
|
|
131
|
+
if (currentRouteId !== this.lastRouteId) {
|
|
132
|
+
console.log(`[Router] Navigation to ${hash} interrupted by newer navigation. Abandoning.`);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
componentToRender = module.default || module;
|
|
136
|
+
}
|
|
137
|
+
catch (e) {
|
|
138
|
+
console.error("Failed to lazy load component", e);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (typeof componentToRender === 'function') {
|
|
143
|
+
// It's a class component
|
|
144
|
+
if (this.rootContainer) {
|
|
145
|
+
const instance = new componentToRender(this.rootContainer);
|
|
146
|
+
this.currentComponent = instance;
|
|
147
|
+
// Inject params if the component accepts them
|
|
148
|
+
if (instance.setParams) {
|
|
149
|
+
instance.setParams(params);
|
|
150
|
+
}
|
|
151
|
+
instance.mount();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else if (typeof componentToRender === 'object' && componentToRender.template) {
|
|
155
|
+
// Object Component (Simple SFC without script or Options API)
|
|
156
|
+
const html = componentToRender.template();
|
|
157
|
+
if (this.rootContainer)
|
|
158
|
+
render(html, this.rootContainer);
|
|
159
|
+
this.currentComponent = null;
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
// Simple HTML string/template
|
|
163
|
+
if (this.rootContainer)
|
|
164
|
+
render(componentToRender, this.rootContainer);
|
|
165
|
+
this.currentComponent = null; // String templates don't have lifecycle instances
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
if (this.rootContainer)
|
|
170
|
+
render('<div style="text-align:center; padding:50px;"><h1>404</h1><p>Page Not Found</p></div>', this.rootContainer);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
navigate(path) {
|
|
175
|
+
if (this.isServer) {
|
|
176
|
+
this.currentPath = path;
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
window.location.hash = path;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// --- Factory for Easy Usage ---
|
|
184
|
+
export const createRouter = (options) => {
|
|
185
|
+
return new MuRouter(options.routes, options.rootContainer);
|
|
186
|
+
};
|
|
187
|
+
// --- Web Component: <mu-link> ---
|
|
188
|
+
// Usage: <mu-link to="/about">About Us</mu-link>
|
|
189
|
+
if (typeof window !== 'undefined' && !customElements.get('mu-link')) {
|
|
190
|
+
class MuLink extends HTMLElement {
|
|
191
|
+
constructor() {
|
|
192
|
+
super();
|
|
193
|
+
this.addEventListener('click', (e) => {
|
|
194
|
+
e.preventDefault();
|
|
195
|
+
const to = this.getAttribute('to');
|
|
196
|
+
if (to) {
|
|
197
|
+
// Update Hash for SPA Navigation
|
|
198
|
+
window.location.hash = to;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
connectedCallback() {
|
|
203
|
+
this.style.cursor = 'pointer';
|
|
204
|
+
this.style.color = 'var(--primary, #9C27B0)'; // Default to brand color if available
|
|
205
|
+
this.style.textDecoration = 'none';
|
|
206
|
+
}
|
|
207
|
+
static get observedAttributes() { return ['to']; }
|
|
208
|
+
}
|
|
209
|
+
customElements.define('mu-link', MuLink);
|
|
210
|
+
}
|