@virid/core 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -1,19 +1,22 @@
1
1
  # @virid/core
2
2
 
3
- `@virid/core` is the logical heart of the entire Virid ecosystem. It provides a deterministic message distribution and scheduling mechanism designed to decouple business logic from complex UI frameworks and runtime environments.
3
+ `@virid/core` serves as the logical heartbeat of the entire Virid ecosystem. It provides a deterministic message distribution and scheduling mechanism, designed to completely decouple business logic from complex UI frameworks and runtime environments.
4
4
 
5
- ## 🌟 Core Design Philosophy
5
+ ⚠️ **Warning:** This framework heavily incorporates design philosophies from **Rust**, **Bevy**, and **NestJS**. It has a steep learning curve and requires the configuration of `reflect-metadata` with experimental metadata support enabled.
6
6
 
7
- - **Absolute Environment Independence**: This package does not depend on any browser, Node.js specific APIs, or third-party libraries (relying only on `reflect-metadata` for decorator functionality). This ensures the core can run seamlessly in Electron main processes, Worker threads, Web rendering layers, or even pure server environments.
8
- - **Deterministic Scheduling**: It introduces a "Tick" mechanism similar to game engines, utilizing a double-buffered message pool to ensure the predictability of logic execution order.
7
+ ### 🌟 Core Design Philosophy
8
+
9
+ - **Absolute Environment Independence:** This package does not rely on any browser-specific APIs, Node.js internals, or third-party libraries (with the sole exception of `reflect-metadata` for decorator functionality). This ensures the kernel can run seamlessly within Electron main processes, Worker threads, Web rendering layers, or even pure server-side environments.
10
+ - **Deterministic Scheduling:** By introducing a game-engine-inspired **Tick mechanism**, the framework utilizes double-buffered message pools to ensure the execution order of logic remains strictly predictable.
11
+ - **Strong Typing & Ownership:** All systems are built with robust type safety, enforcing the use of modern TypeScript types and classes as unique identifiers. It features a runtime "modification shield" to intercept any illegal write operations. Move beyond a reliance on hot-reloading; as the saying goes: *If it compiles, it works.*
9
12
 
10
13
  ## 🛠️ Core Functional Overview
11
14
 
12
15
  ### 1. Message-Driven & Dispatcher Mechanism
13
16
 
14
- In Virid, all state changes must be triggered by sending a `Message` command.
17
+ In `Virid`, all state changes must be triggered by sending a `Message` command.
15
18
 
16
- - **Automatic Scheduling**: By defining specific types of `Message` and corresponding `System` handlers, the engine automatically invokes the registered logic in the next microtask cycle (Tick).
19
+ - **Automatic Scheduling**: By defining specific types of `Message` and corresponding `System` handlers, the engine automatically invokes the registered logic in the next microtask cycle (`Tick`).
17
20
  - **Message Types**:
18
21
  - **`SingleMessage`**: Messages of the same type within the same Tick are automatically merged, suitable for state synchronization.
19
22
  - **`EventMessage`**: Sequentially appended, ensuring the integrity of action sequences.
@@ -23,13 +26,11 @@ In Virid, all state changes must be triggered by sending a `Message` command.
23
26
 
24
27
  ### 2. Dependency Injection System (DI)
25
28
 
26
- Virid implements a lightweight, decorator-based DI system, allowing Systems to access data entities with minimal effort.
29
+ `Virid` implements a lightweight, decorator-based DI system, allowing Systems to access data entities with minimal effort.
27
30
 
28
31
  - **Data Entities (Component)**: Classes marked with the `@Component()` decorator are defined as data containers.
29
32
  - **Automatic Injection**: Once registered via `app.bindComponent()`, the Dispatcher automatically injects the corresponding instances based on the parameter types of the System function.
30
33
 
31
- TypeScript
32
-
33
34
  ```ts
34
35
  class IncrementMessage extends SingleMessage {
35
36
  constructor(public amount: number) {
@@ -96,102 +97,137 @@ MyMessage.send(); // Parameters correspond to the constructor
96
97
  - **Logic**: Sequential, no merging. Every `EventMessage` triggers a System execution strictly.
97
98
  - **Example**: Same as `EventMessage`
98
99
 
100
+ ## 3. Data & Logic Definitions (Decorators)
101
+
102
+ ### `@Controller()`
103
+
104
+ - **Function:** Marks a class as a UI Controller. Instances of this class are tied to the lifecycle of Vue components—created when the component is mounted and destroyed when it is unmounted. For details, see `@virid/vue`.
105
+
106
+ - **Design:** Used in conjunction with `bindController`. Once registered, instances can be retrieved in `@virid/vue` using the `useController` hook.
107
+
108
+ - **Example:**
109
+
110
+ ```ts
111
+ @Controller()
112
+ class PageController {}
113
+
114
+ // Registration is required before use
115
+ app.bindController(PageController);
116
+ ```
117
+
99
118
  ------
100
119
 
101
- ### 3. Data & Logic Definitions (Decorators)
120
+ ### `@Component()`
102
121
 
103
- #### `@Component()`
122
+ - **Function:** Marks a class as a Data Entity. This class acts as a global singleton and persists throughout the application lifecycle.
104
123
 
105
- - **Function**: Marks a class as a **Data Entity**.
106
- - **Usage**: Used with `bindComponent` to enable dependency injection in Systems.
107
- - **Example**:
124
+ - **Design:** Used with `bindComponent`. Once registered, it can be declared as a parameter type in a `@System` to enable automatic Dependency Injection (DI).
125
+
126
+ - **Example:**
108
127
 
109
128
  ```ts
110
129
  @Component()
111
130
  class CounterComponent {
112
- public count = 0;
131
+ public count = 0;
113
132
  }
133
+
134
+ // Registration is required before use
135
+ app.bindComponent(CounterComponent);
114
136
  ```
115
137
 
116
- #### `@System(params?)`
138
+ ------
139
+
140
+ ### `@System(params?)`
141
+
142
+ - **Function:** Registers a static method as a business logic processor. It implements **"Automatic Dependency Wiring."** By simply specifying the `Component` type in the parameters, the engine automatically injects the corresponding instance during execution.
143
+
144
+ - **Parameters:**
145
+
146
+ - `priority`: Execution priority. Higher values execute earlier within the same **Tick**.
147
+ - `messageClass`: The specific message type that triggers this System. (Cannot be used simultaneously with the `@Message` decorator on parameters).
148
+
149
+ - **Example:**
117
150
 
118
- - **Function**: Registers a static method as a logic handler with automatic dependency assembly.
119
- - **Parameters**:
120
- - `priority`: Higher values execute earlier in a Tick.
121
- - `messageClass`: The message type that triggers this System (cannot coexist with `@Message`).
122
- - **Note**: Returning a Message (or array) from a System implements automatic logic chaining.
123
- - **Examples**:
124
151
 
125
152
  ```ts
126
- import {
127
- System,
128
- Message,
129
- } from "@virid/core";
153
+ import { System, Message } from "@virid/core";
130
154
 
131
155
  class CounterSystem {
132
- // Priority can be set for the system
133
- @System({ priority: 0})
134
- static onIncrement(
135
- @Message(IncrementMessage) message: IncrementMessage,
136
- count: CounterComponent,
137
- ) {
138
- count.count += message.amount;
139
- }
140
- //You don't need to use @ Message if you already used messageClass
141
- @System({messageClass:IncrementMessage})
142
- static onIncrement(
143
- count: CounterComponent,
144
- ) {
145
- count.count += 1;
146
- }
147
- @System()
148
- static onProcess(msg: SomeMessage) {
149
- // Directly return the message to achieve logical chain triggering, without the need to //manually call the Message Writer
150
- // You can also return a message array to trigger continuously
151
- return new NextStepMessage();
152
- }
156
+ // Setting priority; CounterComponent is automatically injected
157
+ @System({ priority: 0 })
158
+ static onIncrement(
159
+ @Message(IncrementMessage) message: IncrementMessage,
160
+ count: CounterComponent,
161
+ ) {
162
+ count.count += message.amount;
163
+ }
164
+
165
+ // Alternative: Define messageClass in the System decorator
166
+ @System({ messageClass: IncrementMessage })
167
+ static onQuickAdd(count: CounterComponent) {
168
+ count.count += 1;
169
+ }
170
+
171
+ @System()
172
+ static onProcess(msg: SomeMessage) {
173
+ // Return a message (or an array of messages) to trigger a logic chain
174
+ // This removes the need to manually call a MessageWriter
175
+ return new NextStepMessage();
153
176
  }
154
- //Send messages directly through. send
177
+ }
178
+
179
+ // Triggering logic via the .send() method
155
180
  IncrementMessage.send(5);
156
181
  ```
157
182
 
158
- #### `@Message(Class, single?)`
183
+ ------
159
184
 
160
- - **Function**: Parameter decorator defining the message type for the System.
161
- - **Batch Mode**: Set `single: false` to receive an array of all messages of that type in the current Tick (ideal for high-performance batch processing).
162
- - **Example**: Same as `System`
185
+ ### `@Message(Class, single?)`
163
186
 
164
- #### @Observer(callback)
187
+ - **Function:** A parameter-level decorator that explicitly defines which message type the System is listening to.
188
+ - **Batch Mode:** If `single: false` is set, the System receives an **array** of all messages of that type sent within the current Tick. This is ideal for high-performance batch processing (e.g., physics calculations or log aggregation).
189
+ - **Example:** See the `@System` section above.
190
+
191
+ ------
192
+
193
+ ### `@Observer(callback)`
194
+
195
+ - **Function:** A property-level decorator for change detection, used to handle "non-command-driven" side effects.
196
+
197
+ - **Logic:** When a decorated property in a `Component` changes, the engine automatically triggers the specified callback function.
198
+
199
+ - **Example:**
165
200
 
166
- - **Function** : Attribute level change monitoring, used to handle side effects that are not instruction driven
167
- - **Logic** : When the attribute marked in 'Component' changes, the engine will automatically trigger the specified callback function.
168
- - **Example** :
169
201
 
170
202
  ```ts
171
203
  @Component()
172
204
  class PlayerComponent {
173
- //Automatically send a synchronization message or execute a callback when progress changes
174
- @Observer((old, val) => new SyncLyricMessage(val))
175
- public progress = 0;
205
+ // Automatically send a sync message or execute a callback when 'progress' changes
206
+ @Observer((old, val) => new SyncLyricMessage(val))
207
+ public progress = 0;
176
208
  }
177
209
  ```
178
210
 
179
- #### `@Safe()`
211
+ ------
212
+
213
+ ### `@Safe()`
214
+
215
+ - **Function:** A method access modifier. In Virid, external environments (UI layers) are strictly prohibited from directly modifying logic-layer data; all modifications and method calls are intercepted by default. However, "read-only" or "safe calculation" methods can be explicitly authorized via `@Safe()`, allowing the view layer to call them directly.
216
+
217
+ - **Design:** Primarily serves external projection layers like `@virid/vue`. See **Deep Shield** in the `@virid/vue` documentation for more details.
218
+
219
+ - **Example:**
180
220
 
181
- - **Function**: Method access marking. In Virid, The UI layer is restricted from directly modifying logic data. `@Safe()` explicitly authorizes the view layer to call specific "read-only" or "safe-calculation" methods.
182
- - **Example** :
183
221
 
184
222
  ```ts
185
223
  @Component()
186
224
  class PlayerComponent {
187
- // 如果不加Safe,virid将会禁止在任何vue的controller中调用该方法
188
- @Safe()
189
- public someMethod(){}
225
+ // Without @Safe, Virid will block calls to this method from any Vue Controller
226
+ @Safe()
227
+ public someMethod() {}
190
228
  }
191
229
  ```
192
230
 
193
- ------
194
-
195
231
  ### 4. Dispatcher & Hooks
196
232
 
197
233
  - **Double-Buffered Flip**: Each execution locks current messages; new messages generated during execution enter the next cycle.
@@ -250,7 +286,7 @@ app.onAfterTick((context) => {
250
286
 
251
287
  ------
252
288
 
253
- ### 🔬 Advanced: Atomic Operations
289
+ ### 🔬 Advanced
254
290
 
255
291
  #### **AtomicModifyMessage**
256
292
 
@@ -270,4 +306,45 @@ AtomicModifyMessage.send(
270
306
  );
271
307
  ```
272
308
 
273
- ------
309
+ #### **DebounceMessage**
310
+
311
+ **Function:** Provides a framework-level native debouncing solution with built-in lifecycle management.
312
+
313
+ **Scenario:** When you need to throttle the frequency of message triggers or merge the data content of consecutive messages, this class offers an out-of-the-box mechanism to handle "intent evolution" without manual timer management.
314
+
315
+ **Example:**
316
+
317
+ ```ts
318
+ // Derive your own message from the DebounceMessage class
319
+ class MoveMessage extends DebounceMessage {
320
+ readonly debounceTime = 100; // Set the debounce window to 100ms
321
+
322
+ constructor(
323
+ public x: number,
324
+ public y: number,
325
+ ) {
326
+ super();
327
+ }
328
+
329
+ // This callback is triggered when debouncing occurs,
330
+ // providing the instance of the previously sent Message.
331
+ debounceCallback(previousMessage: MoveMessage) {
332
+ console.log(
333
+ `[Debounce] Merge displacement: Original(${previousMessage.x}, ${previousMessage.y}) -> New(${this.x}, ${this.y})`,
334
+ );
335
+ // Accumulate the state from the previous message
336
+ this.x += previousMessage.x;
337
+ this.y += previousMessage.y;
338
+ }
339
+ }
340
+
341
+ // Usage:
342
+ // Only the "evolved" message with a combined value will
343
+ // reach the System after the user stops sending for 100ms.
344
+ MoveMessage.send(10, 0);
345
+ ```
346
+
347
+
348
+
349
+
350
+
package/README.zh.md CHANGED
@@ -2,10 +2,13 @@
2
2
 
3
3
  `@virid/core` 是整个 Virid 生态系统的逻辑心脏。它提供了一套确定性的消息分发与调度机制,旨在将业务逻辑从复杂的 UI 框架与运行环境中彻底剥离。
4
4
 
5
+ ⚠️本框架吸收了大量Rust、Bevy、Nestjs设计哲学,上手难度较高,且需要配置`reflect-metadata`并开启元数据支持。
6
+
5
7
  ## 🌟 核心设计理念
6
8
 
7
9
  - **环境绝对独立**:本包不依赖任何浏览器、Node.js 的特殊 API 或第三方库(仅依赖 `reflect-metadata` 实现装饰器功能)。这确保了内核可以无缝运行在 Electron 主进程、Worker 线程、Web 渲染层甚至纯服务器环境中。
8
10
  - **确定性调度**:引入了类似游戏引擎的 `Tick` 机制,通过双缓冲消息池确保逻辑执行顺序的可预测性。
11
+ - **强类型与所有权**:所有的系统使用强类型构建,强制使用现代TS类型和类本身作为标识,且拥有运行时修改护盾检查拦截任何非法写操作。**摆脱热更新依赖,If it compiles, it works**
9
12
 
10
13
  ## 🛠️ 核心功能详解
11
14
 
@@ -13,31 +16,34 @@
13
16
 
14
17
  在 Virid 中,所有的状态变更都必须通过发送一个 `Message` 指令来触发。
15
18
 
16
- - **自动调度**:通过定义特定类型的 `Message` 和对应的 `System` 处理函数,引擎会自动在下一个微任务周期(Tick)内调用已注册的逻辑。
19
+ - **自动调度**:通过定义特定类型的 `Message` 和对应的 `System` 处理函数,引擎会自动在下一个微任务周期(`Tick`)内调用已注册的逻辑。
17
20
  - **消息类型**:
18
21
  - `SingleMessage`:同一 Tick 内的同类消息会自动合并,适用于状态同步。
19
22
  - `EventMessage`:顺序追加,确保动作序列的完整性。
20
- - `ErrorMessage`:顺序追加,错误也是一种消息类型,拥有默认处理System
21
- - `WarnMessage`:顺序追加,警告也是一种消息类型,拥有默认处理System
22
- - `InfoMessage`:顺序追加,信息也是一种消息类型,拥有默认处理System
23
+ - `ErrorMessage`:顺序追加,错误也是一种消息类型,拥有默认处理`System`。
24
+ - `WarnMessage`:顺序追加,警告也是一种消息类型,拥有默认处理`System`。
25
+ - `InfoMessage`:顺序追加,信息也是一种消息类型,拥有默认处理`System`。
23
26
 
24
27
  ### 2. 依赖注入系统 (Dependency Injection)
25
28
 
26
- Virid 实现了基于装饰器的轻量依赖注入,使 System 能够以极简的方式访问数据实体。
29
+ `Virid` 实现了基于装饰器的轻量依赖注入,使 `System` 能够以极简的方式访问数据实体。
27
30
 
28
31
  - **数据实体 (Component)**:通过 `@Component()` 装饰器标记 class,将其定义为数据容器。
29
32
  - **自动注入**:使用 `app.bindComponent()` 注册后,Dispatcher 会根据 System 函数的参数类型自动注入对应的实例。
30
33
 
31
34
  ```ts
35
+ //定义消息
32
36
  class IncrementMessage extends SingleMessage {
33
37
  constructor(public amount: number) {
34
38
  super();
35
39
  }
36
40
  }
37
41
 
42
+ //定义数据
38
43
  @Component()
39
44
  class CounterComponent { public count = 0; }
40
45
 
46
+ //纯静态static,当消息发送时引擎自动调用onIncrement
41
47
  class CounterSystem {
42
48
  @System()
43
49
  static onIncrement(
@@ -51,14 +57,14 @@ class CounterSystem {
51
57
 
52
58
  ### 3. 系统调度与钩子 (Lifecycle Hooks)
53
59
 
54
- Dispatcher 提供了完备的生命周期监控能力:
60
+ `Dispatcher` 提供了完备的生命周期监控能力:
55
61
 
56
62
  - **执行钩子**:支持 `onBeforeExecute` 和 `onAfterExecute`,允许在逻辑执行前后插入全局审计或过滤逻辑。
57
63
  - **周期钩子**:`onBeforeTick` 与 `onAfterTick` 用于监控每一轮逻辑帧的起止。
58
64
 
59
65
  ### 4. 工业级健壮性
60
66
 
61
- - **死循环防御**:Dispatcher 内部设有 `internalDepth` 计数器。若逻辑链路产生超过 100 层的递归触发,系统将自动熔断并报错,防止环境假死。
67
+ - **死循环熔断**:`Dispatcher` 内部设有 `internalDepth` 计数器。若逻辑链路产生超过 100 层的递归触发,系统将自动熔断并报错,防止环境假死。
62
68
  - **执行优先级**:支持通过 `@System({ priority: number })` 明确多个系统处理同一消息时的先后顺序。
63
69
 
64
70
  ## 🛠️ @virid/core 核心 API 概览
@@ -73,7 +79,7 @@ Dispatcher 提供了完备的生命周期监控能力:
73
79
 
74
80
  ### 2. 指令与消息 (Messages)
75
81
 
76
- 消息是驱动系统的唯一原因。Virid 区分了两种不同的执行范式:
82
+ 消息是驱动系统的唯一原因。`Virid` 区分了两种不同的执行范式:
77
83
 
78
84
  #### `SingleMessage`
79
85
 
@@ -85,11 +91,13 @@ Dispatcher 提供了完备的生命周期监控能力:
85
91
 
86
92
  ```ts
87
93
  import {SingleMessage} form "@virid/core"
88
- class MyMessage extends SingleMessage{}
94
+ class MyMessage extends SingleMessage{
95
+ construter(public someData:SomeType)
96
+ }
89
97
 
90
98
  //在任何的地方,只要发送
91
99
  //send内的参数为MyMessage的构造函数可以接受的参数
92
- MyMessage.send()
100
+ MyMessage.send(someData)
93
101
  ```
94
102
 
95
103
  #### `EventMessage`
@@ -102,9 +110,22 @@ Dispatcher 提供了完备的生命周期监控能力:
102
110
 
103
111
  ### 3. 数据与逻辑定义 (Decorators)
104
112
 
113
+ #### `@Controller()`
114
+
115
+ - **功能**:标记一个类为**UI控制器**,该类将会随着每个`vue`组件的创建而创建,销毁而销毁。详情见`@virid/vue`。
116
+ - **设计**:配合 `bindController` 使用,注册后可以在`@virid/vue`中使用`useController`获得实例。
117
+ - **示例:**
118
+
119
+ ```ts
120
+ @Controller()
121
+ class PageController {}
122
+ // 使用之前要注册
123
+ app.bindController(PageController)
124
+ ```
125
+
105
126
  #### `@Component()`
106
127
 
107
- - **功能**:标记一个类为**数据实体**。
128
+ - **功能**:标记一个类为**数据实体**,该类将作为全局单例,并一直存在。
108
129
  - **设计**:配合 `bindComponent` 使用,注册后可以在System中声明类型以获得依赖注入功能。
109
130
  - **示例:**
110
131
 
@@ -113,11 +134,13 @@ Dispatcher 提供了完备的生命周期监控能力:
113
134
  class CounterComponent {
114
135
  public count = 0;
115
136
  }
137
+ // 使用之前要注册
138
+ app.bindController(CounterComponent)
116
139
  ```
117
140
 
118
141
  #### `@System(params?)`
119
142
 
120
- - **功能**:将静态方法注册为业务逻辑处理器。它实现了“依赖自动装配”。你只需要在参数里写上对应的 `Component` 类型,引擎就会在执行时自动注入实例。
143
+ - **功能**:将静态方法注册为业务逻辑处理器。它实现了“依赖自动装配”。只需要在参数里写上对应的 `Component` 类型,引擎就会在执行时自动注入实例。
121
144
  - **参数**:
122
145
  - `priority`: 执行优先级。数值越大,在同一个 `Tick` 中执行越早。
123
146
  - `messageClass`: 触发该System需要的消息类型,不能与`@Message`共存
@@ -180,8 +203,8 @@ class PlayerComponent {
180
203
 
181
204
  ### `@Safe()`
182
205
 
183
- - **功能**:方法访问权限标记,在virid中外部环境(UI 层)严禁直接修改逻辑层数据。但对于某些“只读类”或“安全计算类”方法,可以通过 `@Safe()` 显式授权,允许视图层直接调用。
184
- - **设计**:主要服务于 `@virid/vue` 等外部投影层,详情请前往vue适配层文档。
206
+ - **功能**:方法访问权限标记,在`Virid`中外部环境(UI 层)严禁直接修改逻辑层数据,所有的修改和方法调用都会被拦截。但对于某些“只读类”或“安全计算类”方法,可以通过 `@Safe()` 显式授权,允许视图层直接调用。
207
+ - **设计**:主要服务于 `@virid/vue` 等外部投影层,详情见`@virid/vue`中的`Deep Shield`
185
208
  - **示例**:
186
209
 
187
210
  ```ts
@@ -235,7 +258,7 @@ app.onAfterTick((context) => {
235
258
 
236
259
  ------
237
260
 
238
- ## 🔬 进阶:原子化修改 (Atomic Operations)
261
+ ## 🔬 进阶
239
262
 
240
263
  #### `AtomicModifyMessage`
241
264
 
@@ -253,3 +276,32 @@ app.onAfterTick((context) => {
253
276
  );
254
277
  ```
255
278
 
279
+ #### `DebounceMessage`
280
+
281
+ - **功能**:框架级原生防抖功能,提供简易的防抖触发和简单的防抖回调。
282
+ - **场景**:当你需要限制Message触发频率,或者需要融合前后两次Message的内容时使用,即可0行代码获得框架级原生支持。
283
+ - **示例**:
284
+
285
+ ```ts
286
+ // 从DebounceMessage类型派生一个自己的消息
287
+ class MoveMessage extends DebounceMessage {
288
+ readonly debounceTime = 100; // 设置防抖时间为100ms
289
+
290
+ constructor(
291
+ public x: number,
292
+ public y: number,
293
+ ) {
294
+ super();
295
+ }
296
+
297
+ // 当触发防抖时,该回调会被调用,并传入上次发送的Message实例
298
+ debounceCallback(previousMessage: MoveMessage) {
299
+ console.log(
300
+ `[Debounce] Merge displacement: Original(${previousMessage.x}, ${previousMessage.y}) -> New(${this.x}, ${this.y})`,
301
+ );
302
+ this.x += previousMessage.x;
303
+ this.y += previousMessage.y;
304
+ }
305
+ }
306
+ ```
307
+
package/dist/index.cjs CHANGED
@@ -1,32 +1,32 @@
1
1
  /**
2
- * @virid/core v0.0.1
2
+ * @virid/core v0.1.3
3
3
  * A lightweight and powerful message core built using dependency injection and CCS concepts
4
4
  */
5
- var C=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var pe=(s,e,t)=>e in s?C(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var o=(s,e)=>C(s,"name",{value:e,configurable:!0});var ge=(s,e)=>{for(var t in e)C(s,t,{get:e[t],enumerable:!0})},me=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!fe.call(s,n)&&n!==t&&C(s,n,{get:()=>e[n],enumerable:!(r=ue(e,n))||r.enumerable});return s};var ye=s=>me(C({},"__esModule",{value:!0}),s);var i=(s,e,t)=>pe(s,typeof e!="symbol"?e+"":e,t);var He={};ge(He,{AtomicModifyMessage:()=>w,BaseMessage:()=>y,Component:()=>$e,Controller:()=>Ae,ErrorMessage:()=>v,EventMessage:()=>p,InfoMessage:()=>S,Message:()=>we,MessageInternal:()=>M,MessageRegistry:()=>E,MessageWriter:()=>a,Observer:()=>Me,Safe:()=>Ee,SingleMessage:()=>x,System:()=>ke,VIRID_METADATA:()=>g,WarnMessage:()=>b,activateInstance:()=>J,bindObservers:()=>R,createVirid:()=>Ce,handleResult:()=>A,publisher:()=>oe});module.exports=ye(He);var j=class j{static send(...e){a.write(this,...e)}};o(j,"BaseMessage");var y=j,L=class L extends y{constructor(){super();i(this,"__kind","SingleMessage")}};o(L,"SingleMessage");var x=L,W=class W extends y{constructor(){super();i(this,"__kind","EventMessage")}};o(W,"EventMessage");var p=W,F=class F extends p{constructor(t,r){super();i(this,"error");i(this,"context");this.error=t,this.context=r}};o(F,"ErrorMessage");var v=F,Q=class Q extends p{constructor(t){super();i(this,"context");this.context=t}};o(Q,"WarnMessage");var b=Q,z=class z extends p{constructor(t){super();i(this,"context");this.context=t}};o(z,"InfoMessage");var S=z,U=class U extends p{constructor(t,r,n){super();i(this,"ComponentClass");i(this,"recipe");i(this,"label");this.ComponentClass=t,this.recipe=r,this.label=n}};o(U,"AtomicModifyMessage");var w=U;var D=null;function J(s){D=s}o(J,"activateInstance");var oe=new Proxy({},{get(s,e){return e==="dispatch"?t=>{if(!D){console.error(`[Virid] Message dispatched before system init: ${t.constructor.name}`);return}return D.dispatch(t)}:Reflect.get(D||{},e)}}),Y=class Y{static write(e,...t){let r=typeof e=="function"?new e(...t):e;oe.dispatch(r)}static error(e,t=""){this.write(new v(e,t))}static warn(e){this.write(new b(e))}static info(e){this.write(new S(e))}};o(Y,"MessageWriter");var a=Y;var q=class q{constructor(e){i(this,"dirtySignalTypes",new Set);i(this,"eventQueue",[]);i(this,"isRunning",!1);i(this,"globalTick",0);i(this,"internalDepth",0);i(this,"eventHub");i(this,"tickPayload",{});i(this,"beforeExecuteHooks",[]);i(this,"afterExecuteHooks",[]);i(this,"beforeTickHooks",[]);i(this,"afterTickHooks",[]);this.eventHub=e}addBeforeExecute(e,t,r){r?this.beforeExecuteHooks.unshift({type:e,handler:t}):this.beforeExecuteHooks.push({type:e,handler:t})}addAfterExecute(e,t,r){r?this.afterExecuteHooks.unshift({type:e,handler:t}):this.afterExecuteHooks.push({type:e,handler:t})}addBeforeTick(e,t){t?this.beforeTickHooks.unshift(e):this.beforeTickHooks.push(e)}addAfterTick(e,t){t?this.afterTickHooks.unshift(e):this.afterTickHooks.push(e)}markDirty(e){e instanceof p?this.eventQueue.push(e):e instanceof x&&this.dirtySignalTypes.add(e.constructor)}tick(e){if(!(this.isRunning||this.dirtySignalTypes.size===0&&this.eventQueue.length===0)){if(this.internalDepth>100){this.internalDepth=0,this.dirtySignalTypes.clear(),this.eventQueue=[],this.eventHub.reset(),a.error(new Error("[Virid Dispatcher] Deadlock: Recursive loop detected \u{1F4A5}."));return}this.isRunning=!0,this.internalDepth++,queueMicrotask(()=>{let t,r;try{this.internalDepth==0&&(this.tickPayload={},this.executeTickHooks(this.beforeTickHooks));let n=this.prepareSnapshot();t=n.signalSnapshot,r=n.eventSnapshot;let u=this.collectTasks(r,t,e);this.executeTasks(u)}catch(n){a.error(n,"[Virid Dispatcher] Unhandled Error")}finally{t&&r&&this.clear(r,t),this.isRunning=!1,this.dirtySignalTypes.size>0||this.eventQueue.length>0?this.tick(e):(this.executeTickHooks(this.afterTickHooks),this.globalTick++,this.internalDepth=0)}})}}collectTasks(e,t,r){let n=[];for(let l of e)(r.get(l.constructor)||[]).forEach(f=>{n.push(new P(f.fn,f.priority,l,{context:f.fn.systemContext,tick:this.globalTick,payload:{}}))});let u=new Set;for(let l of t)(r.get(l)||[]).forEach(f=>{u.has(f.fn)||(n.push(new P(f.fn,f.priority,this.eventHub.peekSignal(l),{context:f.fn.systemContext,tick:this.globalTick,payload:{}})),u.add(f.fn))});return n}executeTasks(e){e.sort((t,r)=>r.priority-t.priority);for(let t of e)try{let r=t.execute(this.beforeExecuteHooks,this.afterExecuteHooks);r instanceof Promise&&r.catch(n=>a.error(n,`[Virid Dispatcher]: Async System Error.
5
+ var C=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var xe=(s,e,t)=>e in s?C(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var o=(s,e)=>C(s,"name",{value:e,configurable:!0});var be=(s,e)=>{for(var t in e)C(s,t,{get:e[t],enumerable:!0})},ve=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!ye.call(s,n)&&n!==t&&C(s,n,{get:()=>e[n],enumerable:!(r=ge(e,n))||r.enumerable});return s};var Se=s=>ve(C({},"__esModule",{value:!0}),s);var i=(s,e,t)=>xe(s,typeof e!="symbol"?e+"":e,t);var De={};be(De,{AtomicModifyMessage:()=>k,BaseMessage:()=>x,Component:()=>Re,Controller:()=>He,DebounceMessage:()=>W,ErrorMessage:()=>b,EventMessage:()=>p,InfoMessage:()=>S,Message:()=>$e,MessageInternal:()=>M,MessageRegistry:()=>E,MessageWriter:()=>a,Observer:()=>Ce,Safe:()=>Te,SingleMessage:()=>y,System:()=>Ae,VIRID_METADATA:()=>g,WarnMessage:()=>v,activateInstance:()=>X,bindObservers:()=>R,createVirid:()=>Ie,handleResult:()=>A,publisher:()=>le});module.exports=Se(De);var F=class F{static send(...e){a.write(this,...e)}};o(F,"BaseMessage");var x=F,Q=class Q extends x{constructor(){super();i(this,"__kind","SingleMessage")}};o(Q,"SingleMessage");var y=Q,z=class z extends x{constructor(){super();i(this,"__kind","EventMessage")}};o(z,"EventMessage");var p=z,U=class U extends p{constructor(t,r){super();i(this,"error");i(this,"context");this.error=t,this.context=r}};o(U,"ErrorMessage");var b=U,J=class J extends p{constructor(t){super();i(this,"context");this.context=t}};o(J,"WarnMessage");var v=J,Y=class Y extends p{constructor(t){super();i(this,"context");this.context=t}};o(Y,"InfoMessage");var S=Y,q=class q extends p{constructor(t,r,n){super();i(this,"ComponentClass");i(this,"recipe");i(this,"label");this.ComponentClass=t,this.recipe=r,this.label=n}};o(q,"AtomicModifyMessage");var k=q,j=new Map,L=new Map,K=class K extends y{constructor(){super()}static send(...e){let t=new this(...e),r=t.debounceTime,n=j.get(this);if(n){t.debounceCallback(n);let c=L.get(this);c&&clearTimeout(c)}j.set(this,t);let h=setTimeout(()=>{j.delete(this),L.delete(this)},r);L.set(this,h),a.write(t)}debounceCallback(e){}};o(K,"DebounceMessage");var W=K;var D=null;function X(s){D=s}o(X,"activateInstance");var le=new Proxy({},{get(s,e){return e==="dispatch"?t=>{if(!D){console.error(`[Virid] Message dispatched before system init: ${t.constructor.name}`);return}return D.dispatch(t)}:Reflect.get(D||{},e)}}),Z=class Z{static write(e,...t){let r=typeof e=="function"?new e(...t):e;le.dispatch(r)}static error(e,t=""){this.write(new b(e,t))}static warn(e){this.write(new v(e))}static info(e){this.write(new S(e))}};o(Z,"MessageWriter");var a=Z;var ee=class ee{constructor(e){i(this,"dirtySignalTypes",new Set);i(this,"eventQueue",[]);i(this,"isRunning",!1);i(this,"globalTick",0);i(this,"internalDepth",0);i(this,"eventHub");i(this,"tickPayload",{});i(this,"beforeExecuteHooks",[]);i(this,"afterExecuteHooks",[]);i(this,"beforeTickHooks",[]);i(this,"afterTickHooks",[]);this.eventHub=e}addBeforeExecute(e,t,r){r?this.beforeExecuteHooks.unshift({type:e,handler:t}):this.beforeExecuteHooks.push({type:e,handler:t})}addAfterExecute(e,t,r){r?this.afterExecuteHooks.unshift({type:e,handler:t}):this.afterExecuteHooks.push({type:e,handler:t})}addBeforeTick(e,t){t?this.beforeTickHooks.unshift(e):this.beforeTickHooks.push(e)}addAfterTick(e,t){t?this.afterTickHooks.unshift(e):this.afterTickHooks.push(e)}markDirty(e){e instanceof p?this.eventQueue.push(e):e instanceof y&&this.dirtySignalTypes.add(e.constructor)}tick(e){if(!(this.isRunning||this.dirtySignalTypes.size===0&&this.eventQueue.length===0)){if(this.internalDepth>100){this.internalDepth=0,this.dirtySignalTypes.clear(),this.eventQueue=[],this.eventHub.reset(),a.error(new Error("[Virid Dispatcher] Deadlock: Recursive loop detected \u{1F4A5}."));return}this.isRunning=!0,this.internalDepth++,queueMicrotask(()=>{let t,r;try{this.internalDepth==0&&(this.tickPayload={},this.executeTickHooks(this.beforeTickHooks));let n=this.prepareSnapshot();t=n.signalSnapshot,r=n.eventSnapshot;let h=this.collectTasks(r,t,e);this.executeTasks(h)}catch(n){a.error(n,"[Virid Dispatcher] Unhandled Error")}finally{t&&r&&this.clear(r,t),this.isRunning=!1,this.dirtySignalTypes.size>0||this.eventQueue.length>0?this.tick(e):(this.executeTickHooks(this.afterTickHooks),this.globalTick++,this.internalDepth=0)}})}}collectTasks(e,t,r){let n=[];for(let c of e)(r.get(c.constructor)||[]).forEach(f=>{n.push(new P(f.fn,f.priority,c,{context:f.fn.systemContext,tick:this.globalTick,payload:{}}))});let h=new Set;for(let c of t)(r.get(c)||[]).forEach(f=>{h.has(f.fn)||(n.push(new P(f.fn,f.priority,this.eventHub.peekSignal(c),{context:f.fn.systemContext,tick:this.globalTick,payload:{}})),h.add(f.fn))});return n}executeTasks(e){e.sort((t,r)=>r.priority-t.priority);for(let t of e)try{let r=t.execute(this.beforeExecuteHooks,this.afterExecuteHooks);r instanceof Promise&&r.catch(n=>a.error(n,`[Virid Dispatcher]: Async System Error.
6
6
  SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
7
7
  MessageName: ${t.message.constructor.name}
8
8
  MessageData: ${JSON.stringify(t.message)}`))}catch(r){a.error(r,`[Virid Dispatcher]: Sync System Error.
9
9
  SystemLocation: ${t.hookContext.context.targetClass.name}.${t.hookContext.context.methodName}
10
10
  MessageName: ${t.message.constructor.name}
11
- MessageData: ${JSON.stringify(t.message)}`)}}prepareSnapshot(){this.eventHub.flip();let e=new Set(this.dirtySignalTypes),t=[...this.eventQueue];return this.dirtySignalTypes.clear(),this.eventQueue=[],{signalSnapshot:e,eventSnapshot:t}}clear(e,t){let r=new Set(t);e.forEach(n=>r.add(n.constructor)),this.eventHub.clearSignals(r),this.eventHub.clearEvents()}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(r=>r(t))}};o(q,"Dispatcher");var O=q,K=class K{constructor(e,t,r,n){i(this,"fn");i(this,"priority");i(this,"message");i(this,"hookContext");this.fn=e,this.priority=t,this.message=r,this.hookContext=n}triggerHooks(e){let t=Array.isArray(this.message)?this.message[0]:this.message;if(t){for(let r of e)if(t instanceof r.type)try{let n=r.handler(this.message,this.hookContext);n instanceof Promise&&n.catch(u=>{a.error(u,`[Virid Hook] Async Hook Error:
11
+ MessageData: ${JSON.stringify(t.message)}`)}}prepareSnapshot(){this.eventHub.flip();let e=new Set(this.dirtySignalTypes),t=[...this.eventQueue];return this.dirtySignalTypes.clear(),this.eventQueue=[],{signalSnapshot:e,eventSnapshot:t}}clear(e,t){let r=new Set(t);e.forEach(n=>r.add(n.constructor)),this.eventHub.clearSignals(r),this.eventHub.clearEvents()}executeTickHooks(e){let t={tick:this.globalTick,timestamp:Date.now(),payload:this.tickPayload};e.forEach(r=>r(t))}};o(ee,"Dispatcher");var O=ee,te=class te{constructor(e,t,r,n){i(this,"fn");i(this,"priority");i(this,"message");i(this,"hookContext");this.fn=e,this.priority=t,this.message=r,this.hookContext=n}triggerHooks(e){let t=Array.isArray(this.message)?this.message[0]:this.message;if(t){for(let r of e)if(t instanceof r.type)try{let n=r.handler(this.message,this.hookContext);n instanceof Promise&&n.catch(h=>{a.error(h,`[Virid Hook] Async Hook Error:
12
12
  It is prohibited to use asynchronous hooks within Hook:
13
13
  ${r.type.name}`)})}catch(n){a.error(n,`[Virid Hook] Hook Execute Failed:
14
14
  Triggered by: ${t.constructor.name}
15
- Registered type: ${r.type.name}`)}}}execute(e,t){this.triggerHooks(e);let r=o(()=>this.triggerHooks(t),"runAfter");try{let n=this.fn(this.message);return n instanceof Promise?n.finally(()=>r()):(r(),n)}catch(n){throw r(),n}}};o(K,"ExecutionTask");var P=K;var X=class X{constructor(){i(this,"signalActive",new Map);i(this,"signalStaging",new Map);i(this,"eventActive",[]);i(this,"eventStaging",[])}push(e){if(e instanceof x){let t=e.constructor;this.signalStaging.has(t)||this.signalStaging.set(t,[]),this.signalStaging.get(t).push(e)}else e instanceof p?this.eventStaging.push(e):a.error(new Error(`[Virid Message] Invalid Message:
16
- ${e.constructor.name} must extend SingleMessage or EventMessage`))}flip(){this.signalActive=this.signalStaging,this.signalStaging=new Map,this.eventActive=this.eventStaging,this.eventStaging=[]}peekSignal(e){return this.signalActive.get(e)||[]}getEventStream(){return this.eventActive}peekEventAt(e){return this.eventActive[e]}clearSignals(e){e.forEach(t=>this.signalActive.delete(t))}clearEvents(){this.eventActive=[]}reset(){this.signalActive.clear(),this.signalStaging.clear(),this.eventActive=[],this.eventStaging=[]}};o(X,"EventHub");var N=X;var Z=class Z{constructor(){i(this,"systemTaskMap",new Map)}register(e,t,r=0){let n=this.systemTaskMap.get(e)||[];if(n.findIndex(l=>l.fn===t)===-1)n.push({fn:t,priority:r}),n.sort((l,d)=>d.priority-l.priority),this.systemTaskMap.set(e,n);else{let l=t.name||"Anonymous";return a.error(new Error(`[Virid Error] System Already Registered:
15
+ Registered type: ${r.type.name}`)}}}execute(e,t){this.triggerHooks(e);let r=o(()=>this.triggerHooks(t),"runAfter");try{let n=this.fn(this.message);return n instanceof Promise?n.finally(()=>r()):(r(),n)}catch(n){throw r(),n}}};o(te,"ExecutionTask");var P=te;var re=class re{constructor(){i(this,"signalActive",new Map);i(this,"signalStaging",new Map);i(this,"eventActive",[]);i(this,"eventStaging",[])}push(e){if(e instanceof y){let t=e.constructor;this.signalStaging.has(t)||this.signalStaging.set(t,[]),this.signalStaging.get(t).push(e)}else e instanceof p?this.eventStaging.push(e):a.error(new Error(`[Virid Message] Invalid Message:
16
+ ${e.constructor.name} must extend SingleMessage or EventMessage`))}flip(){this.signalActive=this.signalStaging,this.signalStaging=new Map,this.eventActive=this.eventStaging,this.eventStaging=[]}peekSignal(e){return this.signalActive.get(e)||[]}getEventStream(){return this.eventActive}peekEventAt(e){return this.eventActive[e]}clearSignals(e){e.forEach(t=>this.signalActive.delete(t))}clearEvents(){this.eventActive=[]}reset(){this.signalActive.clear(),this.signalStaging.clear(),this.eventActive=[],this.eventStaging=[]}};o(re,"EventHub");var N=re;var se=class se{constructor(){i(this,"systemTaskMap",new Map)}register(e,t,r=0){let n=this.systemTaskMap.get(e)||[];if(n.findIndex(c=>c.fn===t)===-1)n.push({fn:t,priority:r}),n.sort((c,d)=>d.priority-c.priority),this.systemTaskMap.set(e,n);else{let c=t.name||"Anonymous";return a.error(new Error(`[Virid Error] System Already Registered:
17
17
  Class ${e.name}
18
- Function ${l}`)),()=>{}}return()=>{let l=this.systemTaskMap.get(e);if(l){let d=l.findIndex(f=>f.fn===t);d!==-1&&(l.splice(d,1),l.length===0&&this.systemTaskMap.delete(e))}}}};o(Z,"MessageRegistry");var E=Z;var ee=class ee{constructor(){i(this,"eventHub",new N);i(this,"dispatcher",new O(this.eventHub));i(this,"registry",new E);i(this,"middlewares",[]);J(this)}useMiddleware(e,t){this.middlewares.push(e)}onBeforeExecute(e,t,r){this.dispatcher.addBeforeExecute(e,t,r)}onAfterExecute(e,t,r){this.dispatcher.addAfterExecute(e,t,r)}onBeforeTick(e,t){this.dispatcher.addBeforeTick(e,t)}onAfterTick(e,t){this.dispatcher.addAfterTick(e,t)}dispatch(e){if(!(e instanceof y)){a.error(new Error(`[Virid Dispatch] Type Error: Message must be an instance of BaseMessage,message:${e}`));return}this.pipeline(e,()=>{if(!this.registry.systemTaskMap.has(e.constructor)){a.error(new Error(`[Virid Dispatch] No handler for message: ${e.constructor.name}`));return}this.eventHub.push(e),this.dispatcher.markDirty(e),this.dispatcher.tick(this.registry.systemTaskMap)})}pipeline(e,t){let r=0,n=o(()=>{r<this.middlewares.length?this.middlewares[r++](e,n):t()},"next");n()}register(e,t,r=0){return this.registry.register(e,t,r)}};o(ee,"MessageInternal");var M=ee;var te=class te{constructor(){i(this,"bindings",new Map);i(this,"singletonInstances",new Map)}bind(e){let t={type:"transient",ctor:e};return this.bindings.set(e,t),{toSelf:o(()=>({inSingletonScope:o(()=>(t.type="singleton",{onActivation:o(r=>{},"onActivation")}),"inSingletonScope")}),"toSelf")}}get(e,t){let r=this.bindings.get(e);if(!r)throw new Error(`[Virid Container] Unbound Constructor: No binding found for ${e.name}`);let n=r.ctor;if(r.type==="singleton"){if(!this.singletonInstances.has(e)){let l=new n,d=t(l);this.singletonInstances.set(e,d)}return this.singletonInstances.get(e)}let u=new n;return t(u)}};o(te,"ViridContainer");var _=te;var c={reset:"\x1B[0m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",green:"\x1B[32m"};function B(s,e,t){let r={params:s,targetClass:Object,methodName:t,originalMethod:e};return e.ccsContext=r,e}o(B,"withContext");var xe=o(s=>{let e=`${c.green}${c.bold} \u2714 [Virid Info] ${c.reset}`,t=`${c.magenta}${s.context}${c.reset}`;console.log(`${e}${c.gray}Global Info Caught:${c.reset}
19
- ${c.green}Details:${c.reset}`,s.context||"unknown Info")},"globalInfoHandler"),ve=o(s=>{let e=`${c.red}${c.bold} \u2716 [Virid Error] ${c.reset}`,t=`${c.magenta}${s.context}${c.reset}`;console.error(`${e}${c.gray}Global Error Caught:${c.reset}
20
- ${c.red}Context:${c.reset} ${t}
21
- ${c.red}Details:${c.reset}`,s.error||s||"unknown Error")},"globalErrorHandler"),be=o(s=>{let e=`${c.yellow}${c.bold} \u26A0 [Virid Warn] ${c.reset}`,t=`${c.cyan}${s.context}${c.reset}`;console.warn(`${e}${c.gray}Global Warn Caught:${c.reset}
22
- ${c.yellow}Context:${c.reset} ${t}`)},"globalWarnHandler"),Se=o(s=>{let e=H.get(s.ComponentClass);if(!e){console.error(`[Virid Modify] Component Not Found:
18
+ Function ${c}`)),()=>{}}return()=>{let c=this.systemTaskMap.get(e);if(c){let d=c.findIndex(f=>f.fn===t);d!==-1&&(c.splice(d,1),c.length===0&&this.systemTaskMap.delete(e))}}}};o(se,"MessageRegistry");var E=se;var ne=class ne{constructor(){i(this,"eventHub",new N);i(this,"dispatcher",new O(this.eventHub));i(this,"registry",new E);i(this,"middlewares",[]);X(this)}useMiddleware(e,t){this.middlewares.push(e)}onBeforeExecute(e,t,r){this.dispatcher.addBeforeExecute(e,t,r)}onAfterExecute(e,t,r){this.dispatcher.addAfterExecute(e,t,r)}onBeforeTick(e,t){this.dispatcher.addBeforeTick(e,t)}onAfterTick(e,t){this.dispatcher.addAfterTick(e,t)}dispatch(e){if(!(e instanceof x)){a.error(new Error(`[Virid Dispatch] Type Error: Message must be an instance of BaseMessage,message:${e}`));return}this.pipeline(e,()=>{if(!this.registry.systemTaskMap.has(e.constructor)){a.error(new Error(`[Virid Dispatch] No handler for message: ${e.constructor.name}`));return}this.eventHub.push(e),this.dispatcher.markDirty(e),this.dispatcher.tick(this.registry.systemTaskMap)})}pipeline(e,t){let r=0,n=o(()=>{r<this.middlewares.length?this.middlewares[r++](e,n):t()},"next");n()}register(e,t,r=0){return this.registry.register(e,t,r)}};o(ne,"MessageInternal");var M=ne;var oe=class oe{constructor(){i(this,"bindings",new Map);i(this,"singletonInstances",new Map)}bind(e){let t={type:"transient",ctor:e};return this.bindings.set(e,t),{toSelf:o(()=>({inSingletonScope:o(()=>(t.type="singleton",{onActivation:o(r=>{},"onActivation")}),"inSingletonScope")}),"toSelf")}}get(e,t){let r=this.bindings.get(e);if(!r)throw new Error(`[Virid Container] Unbound Constructor: No binding found for ${e.name}`);let n=r.ctor;if(r.type==="singleton"){if(!this.singletonInstances.has(e)){let c=new n,d=t(c);this.singletonInstances.set(e,d)}return this.singletonInstances.get(e)}let h=new n;return t(h)}};o(oe,"ViridContainer");var _=oe;var l={reset:"\x1B[0m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",green:"\x1B[32m"};function B(s,e,t){let r={params:s,targetClass:Object,methodName:t,originalMethod:e};return e.ccsContext=r,e}o(B,"withContext");var we=o(s=>{let e=`${l.green}${l.bold} \u2714 [Virid Info] ${l.reset}`,t=`${l.magenta}${s.context}${l.reset}`;console.log(`${e}${l.gray}Global Info Caught:${l.reset}
19
+ ${l.green}Details:${l.reset}`,s.context||"unknown Info")},"globalInfoHandler"),ke=o(s=>{let e=`${l.red}${l.bold} \u2716 [Virid Error] ${l.reset}`,t=`${l.magenta}${s.context}${l.reset}`;console.error(`${e}${l.gray}Global Error Caught:${l.reset}
20
+ ${l.red}Context:${l.reset} ${t}
21
+ ${l.red}Details:${l.reset}`,s.error||s||"unknown Error")},"globalErrorHandler"),Ee=o(s=>{let e=`${l.yellow}${l.bold} \u26A0 [Virid Warn] ${l.reset}`,t=`${l.cyan}${s.context}${l.reset}`;console.warn(`${e}${l.gray}Global Warn Caught:${l.reset}
22
+ ${l.yellow}Context:${l.reset} ${t}`)},"globalWarnHandler"),Me=o(s=>{let e=H.get(s.ComponentClass);if(!e){console.error(`[Virid Modify] Component Not Found:
23
23
  Component ${s.ComponentClass.name} not found in Registry.`);return}try{s.recipe(e),a.warn(`[Virid Modify] Successfully:
24
24
  Modify on ${s.ComponentClass.name}
25
25
  label: ${s.label}`)}catch(t){a.error(t,`[Virid Error] Modify Failed:
26
- ${s.label}`)}},"atomicModifyHandler");function ie(s){s.register(w,B(w,Se,"GlobalAtomicModifier"),1e3),s.register(b,B(b,be,"GlobalWarnHandler"),-999),s.register(v,B(v,ve,"GlobalErrorHandler"),-999),s.register(S,B(S,xe,"GlobalInfoHandler"),-999),H=s}o(ie,"initializeGlobalSystems");var H=null,ht=new Proxy({},{get(s,e){return(...t)=>{if(!H){console.warn(`[Virid Vue] App method "${String(e)}" called before initialization.`);return}let r=H[e];if(typeof r=="function")return r.apply(H,t)}}});var ae=new Set,se=class se{constructor(){i(this,"container",new _);i(this,"messageInternal",new M);i(this,"activationHooks",[])}addActivationHook(e){this.activationHooks.push(e)}get(e){return e.length>0&&a.error(new Error(`[Virid Container] Violation: Component "${e.name}" should not have constructor arguments. Dependency Injection is only allowed in Systems.`)),this.container.get(e,t=>this.handleActivation(t))}handleActivation(e){return e&&this.activationHooks.reduce((t,r)=>{try{let n=r(t);return n===void 0&&a.warn(`[Virid Container] Hook Does Bot Return A Value: Hook "${r.name}" should return a instance to continue.`),n!==void 0?n:t}catch(n){return a.error(n,"[Virid Container] Activation Hook Failed"),t}},e)}bindController(e){return this.container.bind(e).toSelf(),{inSingletonScope:o(()=>({onActivation:o(()=>{},"onActivation")}),"inSingletonScope")}}bindComponent(e){return this.container.bind(e).toSelf().inSingletonScope(),{onActivation:o(()=>{},"onActivation")}}useMiddleware(e,t=!1){this.messageInternal.useMiddleware(e,t)}onBeforeExecute(e,t,r=!1){this.messageInternal.onBeforeExecute(e,t,r)}onAfterExecute(e,t,r=!1){this.messageInternal.onAfterExecute(e,t,r)}onBeforeTick(e,t=!1){this.messageInternal.onBeforeTick(e,t)}onAfterTick(e,t=!1){this.messageInternal.onAfterTick(e,t)}register(e,t,r=0){return this.messageInternal.register(e,t,r)}use(e,t){if(ae.has(e.name))return a.warn(`[Virid Plugin] Duplicate Installation: Plugin ${e.name} has already been installed.`),this;try{e.install(this,t),ae.add(e.name)}catch(r){a.error(r,`[Virid Plugin]: Install Failed: ${e.name}`)}return this}};o(se,"ViridApp");var re=se,k=new re;k.addActivationHook(R);ie(k);var g={SYSTEM:"virid:core:system",MESSAGE:"virid:core:message",CONTROLLER:"virid:core:controller",COMPONENT:"virid:core:component",SAFE:"virid:core:safe",OBSERVER:"virid:core:observer"};var A=o(s=>{if(!s)return;(Array.isArray(s)?s:[s]).forEach(t=>{t instanceof y?a.write(t):a.warn("[Virid HandleResult] Invalid Return Type: Must return Message or Message[].")})},"handleResult");function ke(s={priority:0,messageClass:null}){return(e,t,r)=>{let n=r.value,u=Reflect.getMetadata("design:paramtypes",e,t),l=Reflect.getMetadata(g.MESSAGE,e,t)||null;if(!u){let h=new Error(`[Virid System] System Parameter Loss:
27
- Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);a.error(h);return}if(u.some(h=>h===void 0)){let h=new Error(`[Virid System] Parameter Metadata Loss in "${t}":
26
+ ${s.label}`)}},"atomicModifyHandler");function he(s){s.register(k,B(k,Me,"GlobalAtomicModifier"),1e3),s.register(v,B(v,Ee,"GlobalWarnHandler"),-999),s.register(b,B(b,ke,"GlobalErrorHandler"),-999),s.register(S,B(S,we,"GlobalInfoHandler"),-999),H=s}o(he,"initializeGlobalSystems");var H=null,pt=new Proxy({},{get(s,e){return(...t)=>{if(!H){console.warn(`[Virid Vue] App method "${String(e)}" called before initialization.`);return}let r=H[e];if(typeof r=="function")return r.apply(H,t)}}});var ue=new Set,ae=class ae{constructor(){i(this,"container",new _);i(this,"messageInternal",new M);i(this,"activationHooks",[])}addActivationHook(e){this.activationHooks.push(e)}get(e){return e.length>0&&a.error(new Error(`[Virid Container] Violation: Component "${e.name}" should not have constructor arguments. Dependency Injection is only allowed in Systems.`)),this.container.get(e,t=>this.handleActivation(t))}handleActivation(e){return e&&this.activationHooks.reduce((t,r)=>{try{let n=r(t);return n===void 0&&a.warn(`[Virid Container] Hook Does Bot Return A Value: Hook "${r.name}" should return a instance to continue.`),n!==void 0?n:t}catch(n){return a.error(n,"[Virid Container] Activation Hook Failed"),t}},e)}bindController(e){return this.container.bind(e).toSelf(),{inSingletonScope:o(()=>({onActivation:o(()=>{},"onActivation")}),"inSingletonScope")}}bindComponent(e){return this.container.bind(e).toSelf().inSingletonScope(),{onActivation:o(()=>{},"onActivation")}}useMiddleware(e,t=!1){this.messageInternal.useMiddleware(e,t)}onBeforeExecute(e,t,r=!1){this.messageInternal.onBeforeExecute(e,t,r)}onAfterExecute(e,t,r=!1){this.messageInternal.onAfterExecute(e,t,r)}onBeforeTick(e,t=!1){this.messageInternal.onBeforeTick(e,t)}onAfterTick(e,t=!1){this.messageInternal.onAfterTick(e,t)}register(e,t,r=0){return this.messageInternal.register(e,t,r)}use(e,t){if(ue.has(e.name))return a.warn(`[Virid Plugin] Duplicate Installation: Plugin ${e.name} has already been installed.`),this;try{e.install(this,t),ue.add(e.name)}catch(r){a.error(r,`[Virid Plugin]: Install Failed: ${e.name}`)}return this}};o(ae,"ViridApp");var ie=ae,w=new ie;w.addActivationHook(R);he(w);var g={SYSTEM:"virid:core:system",MESSAGE:"virid:core:message",CONTROLLER:"virid:core:controller",COMPONENT:"virid:core:component",SAFE:"virid:core:safe",OBSERVER:"virid:core:observer"};var A=o(s=>{if(!s)return;(Array.isArray(s)?s:[s]).forEach(t=>{t instanceof x?a.write(t):a.warn("[Virid HandleResult] Invalid Return Type: Must return Message or Message[].")})},"handleResult");function Ae(s={priority:0,messageClass:null}){return(e,t,r)=>{let n=r.value,h=Reflect.getMetadata("design:paramtypes",e,t),c=Reflect.getMetadata(g.MESSAGE,e,t)||null;if(!h){let u=new Error(`[Virid System] System Parameter Loss:
27
+ Unable to recognize system parameters, please confirm if import "reflection-metadata" was introduced at the beginning!`);a.error(u);return}if(h.some(u=>u===void 0)){let u=new Error(`[Virid System] Parameter Metadata Loss in "${t}":
28
28
  One or more parameters have 'undefined' types.
29
29
  This usually happens when you forget to add a type annotation to a decorated parameter.
30
- Check parameter at index: ${u.indexOf(void 0)}`);a.error(h);return}if(s.messageClass&&l){a.error(new Error(`[Virid System] Multiple Messages Are Not Allowed: Cannot use @ message() and SystemParams simultaneously in ${t}`));return}if(!s.messageClass&&!l){a.error(new Error(`[Virid System] System Parameter Loss:
31
- Please declare the message type using the Message decorator`));return}let d=o(h=>{let $=u.map((V,ce)=>{if(l&&l.index==ce){let{messageClass:G,single:le}=l,I=Array.isArray(h)?h[0]:h;if(!(I instanceof G)){let he=I.constructor.name;throw new Error(`[Virid System] Type Mismatch: Expected ${G.name}, but received ${he}`)}if(I instanceof x)return le?Array.isArray(h)?h[h.length-1]:h:Array.isArray(h)?h:[h];if(I instanceof p)return h;throw new Error(`[Virid System] unknown Message Types: Message ${G.name} is not a subclass of SingleMessage or EventMessage!`)}let ne=k.get(V);if(!ne)throw new Error(`[Virid System] unknown Inject Data Types: ${V.name} is not registered in the container!`);return ne}),T=n.apply(e,$);return T instanceof Promise?T.then(A):A(T)},"wrappedSystem"),f={params:u,targetClass:e,methodName:t,originalMethod:n};d.systemContext=f,r.value=d;let m=s.messageClass||l.messageClass;k.register(m,d,s.priority)}}o(ke,"System");function we(s,e=!0){return(t,r,n)=>{if(Reflect.hasOwnMetadata(g.MESSAGE,t,r)){a.error(new Error(`[Virid Message] Multiple Messages Are Not Allowed: ${r} has multiple @Message() decorators!`));return}let u={index:n,messageClass:s,single:e};Reflect.defineMetadata(g.MESSAGE,u,t,r)}}o(we,"Message");function Ee(){return(s,e,t)=>{let r=Reflect.getMetadata(g.SAFE,s)||new Set;r.add(e),Reflect.defineMetadata(g.SAFE,r,s)}}o(Ee,"Safe");function Me(s,[]){return(e,t)=>{let r=Reflect.getMetadata(g.OBSERVER,e)||[];r.push({key:t,callback:s}),Reflect.defineMetadata(g.OBSERVER,r,e)}}o(Me,"Observer");function Ae(){return s=>{Reflect.defineMetadata(g.CONTROLLER,!0,s)}}o(Ae,"Controller");function $e(){return s=>{Reflect.defineMetadata(g.COMPONENT,!0,s)}}o($e,"Component");var Te=["push","pop","shift","unshift","splice","sort","reverse"];function R(s){return!s||typeof s!="object"||Object.prototype.hasOwnProperty.call(s,"__virid_observer_processed__")||(Object.defineProperty(s,"__virid_observer_processed__",{value:!0,enumerable:!1,configurable:!0}),(Reflect.getMetadata(g.OBSERVER,s.constructor)||[]).forEach(({propertyKey:t,callback:r})=>{let n={value:s[t]},u=new Proxy(n,{get(d,f){let m=d.value;return Array.isArray(m)&&Te.includes(f)?(...h)=>{let $=[...m],T=m[f].apply(m,h),V=r.call(s,$,m);return A(V),T}:m},set(d,f,m){let h=d.value;if(m===h)return!0;d.value=m;let $=r.call(s,h,m);return A($),!0}}),l=o(()=>u.value,"getter");l.__virid_box__=n,Object.defineProperty(s,t,{get:l,set:o(d=>{u.value=d},"set"),enumerable:!0,configurable:!0}),n.value&&typeof n.value=="object"&&R(n.value)}),Reflect.ownKeys(s).forEach(t=>{if(t==="__virid_observer_processed__")return;let r=Object.getOwnPropertyDescriptor(s,t);if(r&&r.get)return;let n=s[t];n&&typeof n=="object"&&R(n)})),s}o(R,"bindObservers");function Ce(){return k}o(Ce,"createVirid");0&&(module.exports={AtomicModifyMessage,BaseMessage,Component,Controller,ErrorMessage,EventMessage,InfoMessage,Message,MessageInternal,MessageRegistry,MessageWriter,Observer,Safe,SingleMessage,System,VIRID_METADATA,WarnMessage,activateInstance,bindObservers,createVirid,handleResult,publisher});
30
+ Check parameter at index: ${h.indexOf(void 0)}`);a.error(u);return}if(s.messageClass&&c){a.error(new Error(`[Virid System] Multiple Messages Are Not Allowed: Cannot use @ message() and SystemParams simultaneously in ${t}`));return}if(!s.messageClass&&!c){a.error(new Error(`[Virid System] System Parameter Loss:
31
+ Please declare the message type using the Message decorator`));return}let d=o(u=>{let $=h.map((V,de)=>{if(c&&c.index==de){let{messageClass:G,single:fe}=c,I=Array.isArray(u)?u[0]:u;if(!(I instanceof G)){let pe=I.constructor.name;throw new Error(`[Virid System] Type Mismatch: Expected ${G.name}, but received ${pe}`)}if(I instanceof y)return fe?Array.isArray(u)?u[u.length-1]:u:Array.isArray(u)?u:[u];if(I instanceof p)return u;throw new Error(`[Virid System] unknown Message Types: Message ${G.name} is not a subclass of SingleMessage or EventMessage!`)}let ce=w.get(V);if(!ce)throw new Error(`[Virid System] unknown Inject Data Types: ${V.name} is not registered in the container!`);return ce}),T=n.apply(e,$);return T instanceof Promise?T.then(A):A(T)},"wrappedSystem"),f={params:h,targetClass:e,methodName:t,originalMethod:n};d.systemContext=f,r.value=d;let m=s.messageClass||c.messageClass;w.register(m,d,s.priority)}}o(Ae,"System");function $e(s,e=!0){return(t,r,n)=>{if(Reflect.hasOwnMetadata(g.MESSAGE,t,r)){a.error(new Error(`[Virid Message] Multiple Messages Are Not Allowed: ${r} has multiple @Message() decorators!`));return}let h={index:n,messageClass:s,single:e};Reflect.defineMetadata(g.MESSAGE,h,t,r)}}o($e,"Message");function Te(){return(s,e,t)=>{let r=Reflect.getMetadata(g.SAFE,s)||new Set;r.add(e),Reflect.defineMetadata(g.SAFE,r,s)}}o(Te,"Safe");function Ce(s,[]){return(e,t)=>{let r=Reflect.getMetadata(g.OBSERVER,e)||[];r.push({key:t,callback:s}),Reflect.defineMetadata(g.OBSERVER,r,e)}}o(Ce,"Observer");function He(){return s=>{Reflect.defineMetadata(g.CONTROLLER,!0,s)}}o(He,"Controller");function Re(){return s=>{Reflect.defineMetadata(g.COMPONENT,!0,s)}}o(Re,"Component");var Ve=["push","pop","shift","unshift","splice","sort","reverse"];function R(s){return!s||typeof s!="object"||Object.prototype.hasOwnProperty.call(s,"__virid_observer_processed__")||(Object.defineProperty(s,"__virid_observer_processed__",{value:!0,enumerable:!1,configurable:!0}),(Reflect.getMetadata(g.OBSERVER,s.constructor)||[]).forEach(({propertyKey:t,callback:r})=>{let n={value:s[t]},h=new Proxy(n,{get(d,f){let m=d.value;return Array.isArray(m)&&Ve.includes(f)?(...u)=>{let $=[...m],T=m[f].apply(m,u),V=r.call(s,$,m);return A(V),T}:m},set(d,f,m){let u=d.value;if(m===u)return!0;d.value=m;let $=r.call(s,u,m);return A($),!0}}),c=o(()=>h.value,"getter");c.__virid_box__=n,Object.defineProperty(s,t,{get:c,set:o(d=>{h.value=d},"set"),enumerable:!0,configurable:!0}),n.value&&typeof n.value=="object"&&R(n.value)}),Reflect.ownKeys(s).forEach(t=>{if(t==="__virid_observer_processed__")return;let r=Object.getOwnPropertyDescriptor(s,t);if(r&&r.get)return;let n=s[t];n&&typeof n=="object"&&R(n)})),s}o(R,"bindObservers");function Ie(){return w}o(Ie,"createVirid");0&&(module.exports={AtomicModifyMessage,BaseMessage,Component,Controller,DebounceMessage,ErrorMessage,EventMessage,InfoMessage,Message,MessageInternal,MessageRegistry,MessageWriter,Observer,Safe,SingleMessage,System,VIRID_METADATA,WarnMessage,activateInstance,bindObservers,createVirid,handleResult,publisher});
32
32
  //# sourceMappingURL=index.cjs.map