@xpell/core 2.0.1 → 2.0.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/dist/FPSCalc.d.ts +18 -0
- package/dist/XDataModule.d.ts +12 -0
- package/dist/XObject.d.ts +24 -1
- package/dist/XUtils.d.ts +93 -18
- package/dist/Xpell.d.ts +1 -1
- package/dist/xpell-core.cjs.js +3 -2
- package/dist/xpell-core.es.js +884 -507
- package/docs/AGENTS.md +10 -0
- package/package.json +2 -2
- package/docs/Codex.md +0 -138
- package/docs/Codex_Skills/SKILL.md +0 -184
- package/docs/Codex_Skills/SKILL_API_MAP.md +0 -122
- package/docs/Codex_Skills/SKILL_CHECKLIST.md +0 -18
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FPS Calculator (cross-platform + stable)
|
|
3
|
+
*
|
|
4
|
+
* - Works in browser + node (performance.now() else Date.now()).
|
|
5
|
+
* - Smooths frame time via EMA (ms/frame).
|
|
6
|
+
* - Deadband prevents 119↔120 flicker.
|
|
7
|
+
*
|
|
8
|
+
* Notes:
|
|
9
|
+
* - If your engine runs at 1 FPS on node, this will naturally converge to ~1.
|
|
10
|
+
* - This is O(1) work per frame (a few ops) and will not affect frame rate.
|
|
11
|
+
*/
|
|
12
|
+
export declare class FPSCalc {
|
|
13
|
+
#private;
|
|
14
|
+
constructor(alpha?: number, deadband?: number);
|
|
15
|
+
private now;
|
|
16
|
+
calc(): number;
|
|
17
|
+
reset(): void;
|
|
18
|
+
}
|
package/dist/XDataModule.d.ts
CHANGED
|
@@ -38,4 +38,16 @@ export declare class XDataModule extends XModule {
|
|
|
38
38
|
_ok: boolean;
|
|
39
39
|
_result: boolean;
|
|
40
40
|
}>;
|
|
41
|
+
_get_path(xcmd: XCommand): Promise<{
|
|
42
|
+
_ok: boolean;
|
|
43
|
+
_result: any;
|
|
44
|
+
}>;
|
|
45
|
+
_log(xcmd: XCommand): Promise<{
|
|
46
|
+
_ok: boolean;
|
|
47
|
+
_result: {
|
|
48
|
+
key: string;
|
|
49
|
+
path: string | undefined;
|
|
50
|
+
value: any;
|
|
51
|
+
};
|
|
52
|
+
}>;
|
|
41
53
|
}
|
package/dist/XObject.d.ts
CHANGED
|
@@ -54,6 +54,24 @@ export type XObjectOnEventHandler = ((xObject: XObject, data?: any) => void) | s
|
|
|
54
54
|
export interface XObjectOnEventIndex {
|
|
55
55
|
[eventName: string]: XObjectOnEventHandler;
|
|
56
56
|
}
|
|
57
|
+
export type XArtifactStrategy = "canonical" | "merge" | "generator";
|
|
58
|
+
export type XArtifactIntent = {
|
|
59
|
+
_id?: string;
|
|
60
|
+
_name?: string;
|
|
61
|
+
_label?: string;
|
|
62
|
+
_text?: string;
|
|
63
|
+
_title?: string;
|
|
64
|
+
_description?: string;
|
|
65
|
+
_entity?: string;
|
|
66
|
+
_action?: string;
|
|
67
|
+
_flow_id?: string;
|
|
68
|
+
_payload?: Record<string, any>;
|
|
69
|
+
[key: string]: any;
|
|
70
|
+
};
|
|
71
|
+
export type XArtifactValidationResult = {
|
|
72
|
+
_ok: boolean;
|
|
73
|
+
_errors: string[];
|
|
74
|
+
};
|
|
57
75
|
type XObjectHandler = Function | string | XCommandData | XObjectHandler[];
|
|
58
76
|
export type XObjectData = {
|
|
59
77
|
[k: string]: XValue;
|
|
@@ -119,6 +137,11 @@ export declare class XObject {
|
|
|
119
137
|
static getOwnNanoCommands(): XNanoCommandPack;
|
|
120
138
|
static getNanoCommands(): XNanoCommandPack;
|
|
121
139
|
static getNanoCommandSkills(): XpellSkillCommand[];
|
|
140
|
+
static getArtifactStrategy(): XArtifactStrategy;
|
|
141
|
+
static generateArtifact(intent?: XArtifactIntent): XObjectData;
|
|
142
|
+
protected static cloneArtifact<T>(value: T): T;
|
|
143
|
+
protected static applyArtifactIntent<T extends XObjectData>(artifact: T, intent?: XArtifactIntent): T;
|
|
144
|
+
static validateArtifact(data: XObjectData): XArtifactValidationResult;
|
|
122
145
|
/**
|
|
123
146
|
* XObject constructor is creating the object and adding all the data keys to the XObject instance
|
|
124
147
|
* @param data constructor input data (object)
|
|
@@ -138,7 +161,7 @@ export declare class XObject {
|
|
|
138
161
|
parseEvents(options?: XEventListenerOptions): void;
|
|
139
162
|
addEventListener(eventName: string, handler: XObjectOnEventHandler | string | any, options?: XEventListenerOptions): string;
|
|
140
163
|
removeEventListener(eventName: string): void;
|
|
141
|
-
removeAllEventListeners(): void;
|
|
164
|
+
removeAllEventListeners(eventName?: string): void;
|
|
142
165
|
/**
|
|
143
166
|
* Append a child XObject to this XObject
|
|
144
167
|
* @param xobject
|
package/dist/XUtils.d.ts
CHANGED
|
@@ -52,6 +52,7 @@ export declare class _XUtils {
|
|
|
52
52
|
* @param force - overwrite existing values
|
|
53
53
|
*/
|
|
54
54
|
mergeDefaultsWithData(data: any, defaults: any, force?: boolean): any;
|
|
55
|
+
deepMergeDefaults<T>(data: Partial<T> | undefined, defaults: T): T;
|
|
55
56
|
/**
|
|
56
57
|
* Encode string to Base64 (UTF-8 safe, cross-platform)
|
|
57
58
|
*/
|
|
@@ -77,7 +78,10 @@ export declare class _XUtils {
|
|
|
77
78
|
createDefaultScheduler(_target_fps?: number): XFrameScheduler;
|
|
78
79
|
to_iso_now(): string;
|
|
79
80
|
is_plain_object(value: unknown): value is Record<string, any>;
|
|
81
|
+
ensure_object(value: unknown, field: string): Record<string, any>;
|
|
80
82
|
ensure_string(value: unknown, field: string): string;
|
|
83
|
+
ensure_boolean(value: unknown, field: string): boolean;
|
|
84
|
+
ensure_number(value: unknown, field: string): number;
|
|
81
85
|
ensure_params(raw: unknown): Record<string, any>;
|
|
82
86
|
/**
|
|
83
87
|
* Copy keys from source to target only when value is not null/undefined.
|
|
@@ -110,26 +114,97 @@ export declare class _XUtils {
|
|
|
110
114
|
* Returns epoch ms (now + delta).
|
|
111
115
|
*/
|
|
112
116
|
calculateExpiration(exp: string): number;
|
|
117
|
+
normalize_prompt(prompt: unknown): string;
|
|
118
|
+
normalize_prompt_key(prompt: unknown): string;
|
|
119
|
+
is_non_empty_string(value: unknown): value is string;
|
|
120
|
+
has_value(value: unknown): boolean;
|
|
121
|
+
ensure_array<T = any>(value: unknown): T[];
|
|
122
|
+
to_record(value: unknown): Record<string, any>;
|
|
123
|
+
safe_json_parse<T = any>(value: unknown, fallback: T): T;
|
|
124
|
+
safe_json_stringify(value: unknown, fallback?: string): string;
|
|
125
|
+
clone_json<T>(value: T): T;
|
|
126
|
+
get_path(obj: unknown, path: string | string[], fallback?: any): any;
|
|
127
|
+
set_path(obj: Record<string, any>, path: string | string[], value: any): Record<string, any>;
|
|
128
|
+
pick_defined(source: Record<string, any>, keys: string[]): Record<string, any>;
|
|
129
|
+
omit_undefined(source: Record<string, any>): Record<string, any>;
|
|
130
|
+
escape_regexp(value: string): string;
|
|
131
|
+
matches_keyword(prompt: string, keyword: string): boolean;
|
|
132
|
+
match_keywords(prompt: string, keywords: string[]): string[];
|
|
133
|
+
contains_keyword(prompt: string, keywords: string[]): boolean;
|
|
134
|
+
read_optional_string(value: unknown, field_name: string): string | undefined;
|
|
135
|
+
read_optional_boolean(value: unknown, field_name: string): boolean | undefined;
|
|
136
|
+
read_optional_number(value: unknown, field_name: string): number | undefined;
|
|
137
|
+
read_optional_object(value: unknown, field_name: string): Record<string, any> | undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Returns unique string values while preserving insertion order.
|
|
140
|
+
*
|
|
141
|
+
* Example:
|
|
142
|
+
* ["a", "b", "a"] -> ["a", "b"]
|
|
143
|
+
*/
|
|
144
|
+
unique_strings(values: string[]): string[];
|
|
145
|
+
/**
|
|
146
|
+
* Normalizes IDs (trim + lowercase) and removes duplicates.
|
|
147
|
+
*
|
|
148
|
+
* Example:
|
|
149
|
+
* [" User ", "user", "ADMIN"] -> ["user", "admin"]
|
|
150
|
+
*/
|
|
151
|
+
unique_normalized_ids(ids: string[]): string[];
|
|
152
|
+
/**
|
|
153
|
+
* Truncates long text while preserving the beginning.
|
|
154
|
+
* Appends a truncation marker when the text exceeds max_chars.
|
|
155
|
+
*/
|
|
156
|
+
truncate_text(value: string, max_chars: number): string;
|
|
157
|
+
/**
|
|
158
|
+
* Serializes a value as formatted JSON and truncates the result
|
|
159
|
+
* when it exceeds the specified character limit.
|
|
160
|
+
*/
|
|
161
|
+
compact_json(value: unknown, max_chars?: number): string;
|
|
162
|
+
/**
|
|
163
|
+
* Serializes a value as compact single-line JSON and truncates
|
|
164
|
+
* the result when it exceeds the specified character limit.
|
|
165
|
+
*/
|
|
166
|
+
compact_inline_json(value: unknown, max_chars?: number): string;
|
|
167
|
+
/**
|
|
168
|
+
* Safe version of compact_inline_json().
|
|
169
|
+
* Returns an empty string when serialization fails.
|
|
170
|
+
*/
|
|
171
|
+
safe_compact_inline_json(value: unknown, max_chars?: number): string;
|
|
172
|
+
/**
|
|
173
|
+
* Returns the first max_items items from an array.
|
|
174
|
+
* Returns an empty array for non-array values.
|
|
175
|
+
*/
|
|
176
|
+
compact_array<T = any>(value: unknown, max_items?: number): T[];
|
|
177
|
+
/**
|
|
178
|
+
* Normalizes arbitrary text into a stable identifier.
|
|
179
|
+
*
|
|
180
|
+
* Example:
|
|
181
|
+
* "User Profile" -> "user-profile"
|
|
182
|
+
* "user_profile" -> "user-profile"
|
|
183
|
+
*/
|
|
184
|
+
normalize_id(value: unknown): string | undefined;
|
|
185
|
+
/**
|
|
186
|
+
* Normalizes an array of identifiers and removes duplicates.
|
|
187
|
+
*
|
|
188
|
+
* Example:
|
|
189
|
+
* ["User Profile", "user-profile"]
|
|
190
|
+
* -> ["user-profile"]
|
|
191
|
+
*/
|
|
192
|
+
normalize_id_array(value: unknown): string[];
|
|
193
|
+
/**
|
|
194
|
+
* @deprecated Use normalize_id_array().
|
|
195
|
+
*/
|
|
196
|
+
normalize_string_array(value: unknown): string[];
|
|
197
|
+
/**
|
|
198
|
+
* Returns only plain object items from an array.
|
|
199
|
+
* Non-object values, nulls, and arrays are ignored.
|
|
200
|
+
*/
|
|
201
|
+
ensure_object_array<T extends Record<string, any> = Record<string, any>>(value: unknown): T[];
|
|
202
|
+
/**
|
|
203
|
+
* @deprecated Use ensure_object_array().
|
|
204
|
+
*/
|
|
205
|
+
read_object_array<T extends Record<string, any> = Record<string, any>>(value: unknown): T[];
|
|
113
206
|
}
|
|
114
207
|
declare const XUtils: _XUtils;
|
|
115
208
|
declare const _xu: _XUtils;
|
|
116
209
|
export { XUtils, _xu };
|
|
117
210
|
export default XUtils;
|
|
118
|
-
/**
|
|
119
|
-
* FPS Calculator (cross-platform + stable)
|
|
120
|
-
*
|
|
121
|
-
* - Works in browser + node (performance.now() else Date.now()).
|
|
122
|
-
* - Smooths frame time via EMA (ms/frame).
|
|
123
|
-
* - Deadband prevents 119↔120 flicker.
|
|
124
|
-
*
|
|
125
|
-
* Notes:
|
|
126
|
-
* - If your engine runs at 1 FPS on node, this will naturally converge to ~1.
|
|
127
|
-
* - This is O(1) work per frame (a few ops) and will not affect frame rate.
|
|
128
|
-
*/
|
|
129
|
-
export declare class FPSCalc {
|
|
130
|
-
#private;
|
|
131
|
-
constructor(alpha?: number, deadband?: number);
|
|
132
|
-
private now;
|
|
133
|
-
calc(): number;
|
|
134
|
-
reset(): void;
|
|
135
|
-
}
|
package/dist/Xpell.d.ts
CHANGED
|
@@ -153,7 +153,7 @@ export { XParser } from "./XParser";
|
|
|
153
153
|
export { XCommand, type XCommandData } from "./XCommand";
|
|
154
154
|
export { XLogger, XLogger as _xlog, _XLogger } from "./XLogger";
|
|
155
155
|
export { XModule, type XModuleData, } from "./XModule";
|
|
156
|
-
export { XObject, XObjectPack, type XValue, type IXData, type XDataXporter, type XDataXporterHandler, type XObjectData, type XObjectOnEventIndex, type XObjectOnEventHandler } from "./XObject";
|
|
156
|
+
export { XObject, XObjectPack, type XValue, type IXData, type XDataXporter, type XDataXporterHandler, type XObjectData, type XObjectOnEventIndex, type XObjectOnEventHandler, type XArtifactIntent, type XArtifactValidationResult, type XArtifactStrategy } from "./XObject";
|
|
157
157
|
export { XObjectManager } from "./XObjectManager";
|
|
158
158
|
export { setXEventManager, getXEventManager, _XEventManager, type XEventListener, type XEventListenerOptions, } from "./XEventManager.js";
|
|
159
159
|
export { XEventManagerModule } from "./XEvenetManagerModule";
|
package/dist/xpell-core.cjs.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
"use strict";var B=i=>{throw TypeError(i)};var W=(i,e,t)=>e.has(i)||B("Cannot "+t);var p=(i,e,t)=>(W(i,e,"read from private field"),t?t.call(i):e.get(i)),J=(i,e,t)=>e.has(i)?B("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),V=(i,e,t,s)=>(W(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class H{createIgnoreList(e,t){if(!e)return t;const s=e.split(",").map(n=>n.trim()).filter(Boolean);for(const n of s)t[n]="";return t}guid(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const o=new Uint8Array(16);t.getRandomValues(o),o[6]=o[6]&15|64,o[8]=o[8]&63|128;const a=Array.from(o,_=>_.toString(16).padStart(2,"0"));return a.slice(0,4).join("")+"-"+a.slice(4,6).join("")+"-"+a.slice(6,8).join("")+"-"+a.slice(8,10).join("")+"-"+a.slice(10,16).join("")}const s="0123456789abcdef".split(""),n=[];let r;n[8]=n[13]=n[18]=n[23]="-",n[14]="4";for(let o=0;o<36;o++)n[o]||(r=(0|Math.random()*16)>>>0,n[o]=s[o===19?r&3|8:r&15]);return n.join("")}mergeDefaultsWithData(e,t,s=!1){if(!e)return t;e._id||(e._id=e.id??this.guid());for(const n of Object.keys(t))(!(n in e)||s)&&(e[n]=t[n]);return e}encode(e){const t=globalThis;if(typeof t.btoa=="function"){const s=encodeURIComponent(String(e)).replace(/%([0-9A-F]{2})/g,(n,r)=>String.fromCharCode(parseInt(r,16)));return t.btoa(s)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"utf8").toString("base64");throw new Error("Base64 encode not supported in this environment")}decode(e){const t=globalThis;if(typeof t.atob=="function"){const s=t.atob(String(e)),n=Array.prototype.map.call(s,r=>"%"+r.charCodeAt(0).toString(16).padStart(2,"0")).join("");return decodeURIComponent(n)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"base64").toString("utf8");throw new Error("Base64 decode not supported in this environment")}getRandomInt(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}getParam(e,t,s=0){return e?._params?.[t]??s}createDefaultScheduler(e){const t=globalThis;if(typeof t.requestAnimationFrame=="function")return r=>t.requestAnimationFrame(r);const s=typeof e=="number"&&isFinite(e)&&e>0?e:60;if(typeof t.setImmediate=="function"&&(!e||e>=60))return r=>t.setImmediate(r);const n=Math.max(1,Math.round(1e3/s));return r=>t.setTimeout(r,n)}to_iso_now(){return new Date().toISOString()}is_plain_object(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}ensure_string(e,t){if(typeof e!="string"||!e.trim())throw new Error(`Invalid '${t}'`);return e.trim()}ensure_params(e){return this.is_plain_object(e)?e:{}}addIfNotNull(e,t,s){if(!(!e||!t||!Array.isArray(s)))for(const n of s){const r=e[n];r!=null&&(t[n]=r)}}als(e){const t=String(e??"");return t.endsWith("/")?t:t+"/"}cls(e){const t=String(e??"");return t.endsWith("/")?t.slice(0,-1):t}afs(e){const t=String(e??"");return t.startsWith("/")?t:"/"+t}cfs(e){const t=String(e??"");return t.startsWith("/")?t.slice(1):t}calculateExpiration(e){const s=String(e??"").trim().match(/^(\d+)([hdy])$/);if(!s)throw new Error("Invalid expiration format. Use: 1h | 2d | 3y");const n=Number.parseInt(s[1],10),r=s[2],o=Date.now();let a=0;switch(r){case"h":a=n*60*60*1e3;break;case"d":a=n*24*60*60*1e3;break;case"y":a=n*365*24*60*60*1e3;break}return o+a}}const Q=new H,l=Q;class oe{#e=0;#t=0;#s=0;#n;#r;constructor(e=.05,t=1){const s=Number(e);this.#n=Number.isFinite(s)?Math.min(1,Math.max(.001,s)):.05;const n=Number(t);this.#r=Number.isFinite(n)?Math.max(0,Math.floor(n)):1}now(){const e=globalThis.performance;return e&&typeof e.now=="function"?e.now():Date.now()}calc(){const e=this.now();if(this.#s===0)return this.#s=e,this.#e;const t=e-this.#s;if(this.#s=e,!Number.isFinite(t)||t<=0)return this.#e;this.#t===0?this.#t=t:this.#t=(1-this.#n)*this.#t+this.#n*t;const s=1e3/this.#t;if(!Number.isFinite(s)||s<=0)return this.#e;const n=Math.round(s);return this.#e!==0&&this.#r>0&&Math.abs(n-this.#e)<this.#r?this.#e:(this.#e=n,this.#e)}reset(){this.#e=0,this.#t=0,this.#s=0}}class z{constructor(e){this._enabled=!0,this._show_date=!1,this._show_time=!0,this._debug=!1,e&&this.configure(e)}configure(e){typeof e._enabled=="boolean"&&(this._enabled=e._enabled),typeof e._show_date=="boolean"&&(this._show_date=e._show_date),typeof e._show_time=="boolean"&&(this._show_time=e._show_time),typeof e._debug=="boolean"&&(this._debug=e._debug)}_dt(){const e=new Date,t=this._show_date?`${e.getDate()}.${e.getMonth()}.${e.getFullYear()} `:"",s=this._show_time?`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()}|`:"";return t+s}log(e,...t){this._enabled&&console.log(this._dt(),e,...t)}warn(e,...t){this._enabled&&console.warn(this._dt(),e,...t)}error(e,...t){this._enabled&&console.error(this._dt(),e,...t)}debug(e,...t){!this._enabled||!this._debug||console.debug(this._dt(),e,...t)}}const c=new z,Y=typeof process<"u"&&!!process?.env&&process.env.NODE_ENV==="production";Y||console.info("[Xpell] _xlog is redirected to console in development mode. Tip: enable 'Show timestamps' in DevTools → Console for timed logs.");const j=Y?c:console;class Z{constructor(){this._objects={},this._listeners=new Map,this._any_listeners=new Set,this._compat_writes=!0,this._warn_legacy_writes=!0,this._verbose=!1,this._compat_legacy_keys=!0,this._o_proxy=null,this._objects={}}get _o(){return!this._compat_writes&&!this._warn_legacy_writes?this._objects:(this._o_proxy||(this._o_proxy=new Proxy(this._objects,{set:(e,t,s)=>{const n=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy write: _o["${n}"] = ... ; prefer XData.set("${n}", value).`),this._compat_writes?this.set(n,s,{source:"legacy:_o"}):e[n]=s,!0},deleteProperty:(e,t)=>{const s=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy delete: delete _o["${s}"] ; prefer XData.delete("${s}").`),this._compat_writes?this.delete(s,{source:"legacy:_o"}):delete e[s],!0}})),this._o_proxy)}get(e){return this._objects[e]}set(e,t,s){const n=this._objects[e];this._objects[e]=t,this._emit({key:e,value:t,prev:n,ts:Date.now(),op:"set",meta:s})}patch(e,t,s){const n=this._objects[e],o={...n&&typeof n=="object"?n:{},...t};this._objects[e]=o,this._emit({key:e,value:o,prev:n,ts:Date.now(),op:"patch",meta:s})}touch(e,t){const s=this._objects[e];this._emit({key:e,value:s,prev:s,ts:Date.now(),op:"touch",meta:t})}has(e){return Object.prototype.hasOwnProperty.call(this._objects,e)}delete(e,t){const s=this._objects[e];delete this._objects[e],this._emit({key:e,value:void 0,prev:s,ts:Date.now(),op:"delete",meta:t})}pick(e,t){const s=this._objects[e];return this.delete(e,t),s}clean(){this._objects={}}on(e,t){let s=this._listeners.get(e);return s||this._listeners.set(e,s=new Set),s.add(t),()=>this.off(e,t)}off(e,t){const s=this._listeners.get(e);s&&(s.delete(t),s.size===0&&this._listeners.delete(e))}onAny(e){return this._any_listeners.add(e),()=>this._any_listeners.delete(e)}_emit(e){this._verbose&&e.meta?.trace&&(e.stack=new Error().stack);const t=this._listeners.get(e.key);if(t)for(const s of t)s(e);for(const s of this._any_listeners)s(e)}}const v=new Z,m=v;class A{constructor(e){e&&Object.keys(e).forEach(t=>{this[t]=e[t]}),this.d||(this.d=Date.now())}getParam(e,t,s){return this._params?.hasOwnProperty(t)?this._params[t]:this._params?.hasOwnProperty(e)?this._params[e]:s}}const M={type:"_type",children:"_children"},y=class y{static addHtml2XpellMapItem(e,t){y.html2XMap.elements[e]=t}static parse(e,t){const s=e.split(" ");let n=new A;if(t?(n._module=t,n._op=s[0]):(n._module=s[0],n._op=s[1]),n._params={},s.length>1)for(let r=2;r<s.length;++r){const o=s[r];if(o.indexOf(":")>-1){const _=o.split(":");n._params[_[0]]=_[1]}else n._params[r-1]=s[r]}return n}static replaceSpacesInQuotes(e,t="_%20_"){return e.replace(/(['"])(.*?)\1/g,(s,n,r)=>{const o=String(r).replace(/\s/g,t);return`${n}${o}${n}`})}static parseObjectCommand(e,t){e=y.replaceSpacesInQuotes(e);const s=e.trim().split(/\s+/),n=t||s.shift();if(!n)throw new Error("Missing module name");let r;if(s[0]?.startsWith("#")&&(r=s.shift().slice(1),!r))throw new Error("Invalid object selector '#'. Use '#<id>'");const o=s.shift();if(!o)throw new Error("Missing operation");const a={};let _=null,h=null;if(s.forEach(u=>{if(h){if(h+=` ${u}`,u.endsWith(h[0])){const f=h.slice(1,-1).replace(/_%20_/g," ");a[_]=f,h=null}return}if(u.startsWith('"')||u.startsWith("'")){if(h=u,u.endsWith(u[0])&&u.length>1){const f=u.slice(1,-1).replace(/_%20_/g," ");a[_]=f,h=null}return}if(u.includes(":")){const f=u.split(":"),X=f[0],re=f.slice(1).join(":").replace(/_%20_/g," ");a[X]=re,_=null;return}_=u.replace(/_%20_/g," ")}),h)throw new Error("Unclosed quoted parameter value");return{_module:n,_object:r,_op:o,_params:a}}static xmlString2Xpell(e){const s=new DOMParser().parseFromString(e,"text/xml");return s.childNodes.length>0?y.xml2Xpell(s.childNodes[0]):{}}static xml2Xpell(e,t){const s=y.html2XMap;let n={};n._children=[];const r=e.nodeName,o=e.nodeName;let a=t;if(t?(n[M.type]="xhtml",n._html_ns="http://www.w3.org/2000/svg"):n._type=s.elements[r]?s.elements[r]:r,e.attributes)for(let _=0;_<e.attributes.length;++_){const h=e.attributes[_],u=s.attributes[h.name]?s.attributes[h.name]:h.name;n[u]=h.value}if(e?.firstChild?.nodeValue&&(n.text=e?.firstChild.nodeValue.trim()),n[M.type]=="xhtml"?n._html_tag=o:n[M.type]=="svg"&&(a=!0,n._html_ns="http://www.w3.org/2000/svg"),e?.childNodes.length>0)for(let _=0;_<e.childNodes.length;++_){const h=e.childNodes[_];h.nodeName.startsWith("#")||n[M.children].push(y.xml2Xpell(h,a))}return n}};y.html2XMap={elements:{div:"view",a:"link",b:"xhtml",h1:"xhtml",h2:"xhtml",h3:"xhtml",h4:"xhtml",h5:"xhtml",p:"xhtml",small:"xhtml",aside:"xhtml",span:"xhtml",table:"xhtml",th:"xhtml",td:"xhtml",tr:"xhtml",thead:"xhtml",tbody:"xhtml",ul:"xhtml",li:"xhtml",ol:"xhtml",canvas:"xhtml",img:"image"},attributes:{id:"_id"}};let w=y;class ee{#e;#t;#s;constructor(){this.#e={},this.#t={},this.#s={}}get _objects(){return this.#t}hasObject(e){return this.#t.hasOwnProperty(e)}registerObjects(e){Object.keys(e).forEach(s=>this.registerObject(s,e[s]))}registerObject(e,t){this.#e[e]=t}hasObjectClass(e){return this.#e.hasOwnProperty(e)}getObjectClass(e){return this.#e[e]}getAllClasses(){return this.getObjectClasses()}getObjectClasses(){return this.#e}get _classes(){return this.#e}addObject(e){e&&e._id?(this.#t[e._id]=e,(!e._name||e._name.length==0)&&(e._name=e._id),this.#s[e._name]=e._id):c.log("unable to add object")}removeObject(e){const t=this.#t[e];t&&(delete this.#s[t?._name],delete this.#t[e])}getObject(e){return this.#t[e]}go(e){return this.getObject(e)}getObjectByName(e){return this.#s[e]?this.getObject(this.#s[e]):null}}class ie{constructor(){this._log_rules={register:!1,remove:!1,fire:!1},this._events={},this._listener_index={}}on(e,t,s={},n){this._events[e]||(this._events[e]=[]);const r=s?._owner??n,o=l.guid(),a={_id:o,_callback:t,_options:s,_owner:r,_tag:s?._tag};return this._events[e].push(a),this._listener_index[o]=e,this._log_rules.register&&j.log("XEM Register",e,o),o}once(e,t,s){return this.on(e,t,{_once:!0,_owner:s})}async fire(e,t){const s=this._events[e];if(!s||s.length===0)return;this._log_rules.fire&&j.log("XEM Fire",e,t);const n=s.slice(),r=[];for(const o of n){try{o&&o._callback&&o._callback(t)}catch(a){j.error(a)}o?._options?._once&&r.push(o._id)}for(const o of r)this.remove(o)}remove(e){const t=this._listener_index[e];if(!t)return;const s=this._events[t];if(s&&s.length){const n=s.findIndex(r=>r?._id===e);n>=0&&s.splice(n,1),s.length===0&&delete this._events[t]}delete this._listener_index[e],this._log_rules.remove&&j.log("XEM Remove",t,e)}removeOwner(e){if(!e)return;const t=[];for(const s of Object.values(this._events))for(const n of s)(n?._owner??n?._options?._owner)===e&&t.push(n._id);t.forEach(s=>this.remove(s))}clear(){this._events={},this._listener_index={}}}let $;function ae(i){$=i}function x(){if(!$)throw new Error("XEventManager not set");return $}const ce=["_nano_commands","_cache_cmd_txt","_cache_jcmd","_xporter","_event_listeners_ids","_parent","_children"];function F(i){return ce.includes(i)}function K(i){if(!i||typeof i!="object"||Array.isArray(i))return!1;const e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function g(i,e){return i._skill=e,i.getSkill=()=>e,i}const G={info:g((i,e)=>{c.log("XObject id "+e?._id)},{_name:"info",_scope:"object",_description:"Logs the current object's id."}),log:g((i,e)=>{i._params&&i._params[1]?c.log(i._params[1]):c.log(e)},{_name:"log",_scope:"object",_description:"Logs a message or the current object.",_params:{1:"Optional message to log."}}),fire:g((i,e)=>{i._params&&i._params[1]?x().fire(String(i._params[1]),i._params[2]):i._params&&i._params.event&&x().fire(String(i._params.event),i._params.data)},{_name:"fire",_scope:"object",_description:"Fires an XEventManager event.",_params:{event:"Event name.",data:"Optional event payload.",1:"Event name shorthand.",2:"Event payload shorthand."},_example:{_op:"fire",_params:{event:"user:login",data:{source:"button"}}}}),noop:g(()=>{},{_name:"noop",_scope:"object",_description:"No-op command. Useful as a placeholder in sequences."}),"set-field":g((i,e)=>{const t=i._params?.name,s=i._params?.value;if(!(!e||typeof t!="string"||t.length===0)){if(F(t)){c.error(`set-field denied for protected field: ${t}`);return}e[t]=s}},{_name:"set-field",_scope:"object",_description:"Sets a runtime field directly on the current object.",_params:{name:"Field name.",value:"Value to assign."},_example:{_op:"set-field",_params:{name:"_text",value:"Hello"}}}),"delete-field":g((i,e)=>{const t=i._params?.name;if(!(!e||typeof t!="string"||t.length===0)){if(F(t)){c.error(`delete-field denied for protected field: ${t}`);return}delete e[t]}},{_name:"delete-field",_scope:"object",_description:"Deletes a runtime field from the current object.",_params:{name:"Field name to delete."}}),"toggle-field":g((i,e)=>{const t=i._params?.name;if(!e||typeof t!="string"||t.length===0)return;if(F(t)){c.error(`toggle-field denied for protected field: ${t}`);return}const s=e[t];typeof s=="boolean"?e[t]=!s:s==null?e[t]=!0:e[t]=!1},{_name:"toggle-field",_scope:"object",_description:"Toggles a runtime field using boolean-first semantics.",_params:{name:"Field name to toggle."}}),merge:g((i,e)=>{const t=i._params?.name,s=i._params?.value;if(!e||typeof t!="string"||t.length===0)return;if(F(t)){c.error(`merge denied for protected field: ${t}`);return}if(!K(s)){c.error("merge expects _params.value as a plain object");return}const n=e[t];K(n)||(e[t]={}),Object.assign(e[t],s)},{_name:"merge",_scope:"object",_description:"Shallow-merges a plain object into a target object field.",_params:{name:"Target field name.",value:"Plain object to merge."}}),"run-seq":g(async(i,e)=>{if(!e)return;const t=i._params?.seq;if(!Array.isArray(t)){c.error("run-seq expects _params.seq as an array");return}for(const s of t){if(typeof s=="string"){await e.run(`${e._id} ${s}`);continue}if(s&&typeof s=="object"&&s._op){const n=s._object;if(!(n==null||n==="this"||n===e._id)){c.error("run-seq rejected non-self _object target");return}const o={_op:s._op,_params:s._params?{...s._params}:void 0};await e.execute(o);continue}c.error("run-seq skipped invalid step; expected string or object with _op")}},{_name:"run-seq",_scope:"object",_description:"Runs a sequence of local nano-command steps in strict order.",_params:{seq:"Array of command strings or local command objects."},_example:{_op:"run-seq",_params:{seq:[{_op:"set-field",_params:{name:"_debug",value:!0}},{_op:"log",_params:{1:"Debug enabled"}}]}}})};let N;function _e(i){N=i}function le(){if(!N)throw new Error("XRuntime not set");return N}const L={_id:"xobject",_title:"XObject Core Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime object for identity, typing, composition, lifecycle hooks, events, data binding, and nano-command execution.",_fields:{_id:"Unique object id.",_type:"Registered runtime object type.",_name:"Optional object name.",_children:"Child objects/data.",_data_source:"XData key to bind this object to.",_on:"Event handlers map.",_once:"One-time event handlers map.",_on_create:"Lifecycle handler after object creation.",_on_mount:"Lifecycle handler after mount.",_on_frame:"Frame lifecycle handler.",_on_data:"Data-source lifecycle handler.",_process_frame:"Enable/disable frame processing.",_process_data:"Enable/disable data-source processing.",_debug:"Enable object debug logs."},_exports:{_xui_fields:["_id","_type","_name","_children","_data_source","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_debug"]},_core_rules:["All Xpell runtime objects inherit this contract.","Generated object JSON must be data-only.","Do not generate JavaScript functions.","Use _children for composition.","Use _on/_once with nano-command strings or data-only command objects."],_notes:["Runtime methods include parse, append, run, execute, bindDataSource, unbindDataSource, toXData, dispose, and removeChild.","Most prompts should use this skill as a compact dependency summary, not full context."]},R={_children:"child nodes"},S=class S{constructor(e,t,s){this._children=[],this._parent=null,this._on={},this._once={},this._process_frame=!0,this._process_data=!0,this._nano_commands={},this._event_listeners_ids={},this._event_parsed=!1,this._mounted=!1,this._xporter={_ignore_fields:["_to_xdata_ignore_fields","_xporter","_children","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_parent","_event_listeners_ids","_event_parsed","_mounted","_debug"],_instance_xporters:{}},t&&l.mergeDefaultsWithData(e,t),this._id=e&&e._id?e._id:"xo-"+l.guid(),this._type="object",this._children=[],this._nano_commands={},this.addNanoCommandPack(G),e&&e.hasOwnProperty("_nano_commands")&&e._nano_commands&&(this.addNanoCommandPack(e._nano_commands),delete e._nano_commands),this.addXporterDataIgnoreFields(["_nano_commands"]),this.addXporterInstanceXporter(S,n=>n.toXData()),this._xem_options={},!s&&e&&this.parse(e,R)}static getOwnSkill(){const e=this,t=e._skill??L;return{...t,_exports:{...t._exports??{},_nano_commands:e.getNanoCommandSkills?.()??[]}}}static getSkillChain(){const e=Object.getPrototypeOf(this),t=e&&typeof e.getSkillChain=="function"?e.getSkillChain():[],s=Object.prototype.hasOwnProperty.call(this,"_skill")?this.getOwnSkill():null;return s?[...t,s]:t}static getOwnNanoCommands(){return{...G}}static getNanoCommands(){return{...this.getOwnNanoCommands()}}static getNanoCommandSkills(){return Object.prototype.hasOwnProperty.call(this,"getOwnNanoCommands")?Object.values(this.getOwnNanoCommands()).map(t=>t.getSkill?.()??t._skill).filter(Boolean):[]}log(e,...t){this._debug&&e&&c.log(this._type+"->"+this._id+"]",e,...t)}init(e,t){!t&&e&&this.parse(e,R)}parseEvents(e){if(!this._event_parsed){e||(e=this._xem_options),Object.keys(this._on).forEach(s=>{this.addEventListener(s,this._on[s],e)});const t={};Object.assign(t,e),t._once=!0,Object.keys(this._once).forEach(s=>{this.addEventListener(s,this._once[s],t)}),this._event_parsed=!0}}addEventListener(e,t,s){s||(s=this._xem_options);const n=async o=>{await this.checkAndRunInternalFunction(t,o)},r=x().on(e,n,s,this);return this._event_listeners_ids[e]||(this._event_listeners_ids[e]=[]),this._event_listeners_ids[e].push(r),r}removeEventListener(e){const t=this._event_listeners_ids[e];t&&t.length&&(t.forEach(s=>{x().remove(s)}),delete this._event_listeners_ids[e])}removeAllEventListeners(){Object.keys(this._event_listeners_ids).forEach(t=>this.removeEventListener(t))}append(e){this._children?.push(e),e._parent=this}addNanoCommand(e,t){typeof t=="function"&&(this._nano_commands[e]=t)}addNanoCommandPack(e){e&&Object.keys(e).forEach(t=>{this.addNanoCommand(t,e[t])})}addXporterDataIgnoreFields(e){this._xporter._ignore_fields=this._xporter._ignore_fields.concat(e)}addXporterInstanceXporter(e,t){const s=l.guid();this._xporter._instance_xporters[s]={cls:e,handler:t}}parse(e,t=R){Object.keys(e).forEach(n=>{!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&(this[n]=e[n])})}parseFieldsFromXDataObject(e,t){Object.keys(t).forEach(n=>{e.hasOwnProperty(n)?this[n]=e[n]:this[n]=t[n]})}parseFields(e,t,s){t.forEach(n=>{if(e.hasOwnProperty(n))this[n]=e[n];else if(s&&n.startsWith("_")){const r=n.substring(1);e.hasOwnProperty(r)&&(this[n]=e[r],this[r]=e[r])}})}async onCreate(){this._on_create?this.checkAndRunInternalFunction(this._on_create):this._on&&this._on.create?this.checkAndRunInternalFunction(this._on.create):this._once&&this._once.create&&this.checkAndRunInternalFunction(this._once.create)}async runCmd(e){const t=e instanceof A?e:new A(e);await this.execute(t)}async checkAndRunInternalFunction(e,...t){const s=r=>{if(typeof r=="string"){if(r==="$event")return t[0];if(r.startsWith("$event.")){const o=r.slice(7).split(".");let a=t[0];for(const _ of o){if(a==null)return;a=a[_]}return a}if(r==="$data")return t[0];if(r.startsWith("$data.")){const o=r.slice(6).split(".");let a=t[0];for(const _ of o){if(a==null)return;a=a[_]}return a}return r}if(Array.isArray(r))return r.map(s);if(r&&typeof r=="object"){const o={};for(const a of Object.keys(r))o[a]=s(r[a]);return o}return r},n=async(r,o)=>(o!==void 0&&r&&typeof r=="object"&&!Array.isArray(r)&&(r={...r,_params:{...r._params??{},_prev:o}}),await this.checkAndRunInternalFunction(r,...t));if(Array.isArray(e)){let r;for(const o of e)r=await n(o,r);return r}if(typeof e=="function")return await e(this,...t);if(typeof e=="string"){const r=w.parseObjectCommand(`${this._id} ${e}`);if(t.length>0){r._params=r._params||{};const o=t[0];r._params._event=o,!r._params.data&&!o?.target&&(r._params.data=o)}return await this.execute(r)}if(e&&typeof e=="object"&&Array.isArray(e._commands)){const r=e,o=typeof r._mode=="string"?r._mode:"sequence",a=r._stop_on_error!==!1,_=r._commands;if(o==="parallel"){const u=await Promise.allSettled(_.map(X=>n(X))),f=u.find(X=>X.status==="rejected");if(f&&a)throw f.reason;return u}let h;for(const u of _)try{h=await n(u,o==="chain"?h:void 0)}catch(f){if(c.error(this._type+"->"+this._id+"] command sequence failed",f),a)throw f}return h}if(e&&typeof e=="object"&&e._op){const r=e;if((r._object===void 0||r._object===null||r._object==="this"?this._id:r._object)!==this._id){c.error("XObject JSON handler target not supported; expected _object omitted/'this'/"+this._id);return}const a={...r,_params:r._params?{...r._params}:{}};if(t.length>0){const _=t[0];Object.prototype.hasOwnProperty.call(a._params,"data")||(a._params.data=_),Object.prototype.hasOwnProperty.call(a._params,"_event")||(a._params._event=_)}return a._params=s(a._params),this._debug&&c.log(this._type+"->"+this._id+"]","JSON handler executed locally",a),await this.execute(a)}c.error(this._type+"->"+this._id+"] invalid handler in checkAndRunInternalFunction",e)}async onMount(){if(!this._mounted){this.parseEvents(this._xem_options),this._process_data&&typeof this._data_source=="string"&&this._data_source.length>0&&this.bindDataSource(this._data_source,{initial:!0}),this._on_mount?await this.checkAndRunInternalFunction(this._on_mount):this._on&&this._on.mount?await this.checkAndRunInternalFunction(this._on.mount):this._once&&this._once.mount&&await this.checkAndRunInternalFunction(this._once.mount),this._mounted=!0;for(const e of this._children)e.onMount&&typeof e.onMount=="function"&&e.onMount()}}emptyDataSource(){const e=this._data_source;if(typeof e!="string"||e.length===0)return;const t=this._type??this.constructor.name,s=this._id??"no-id";v.delete(e,{source:`${t}#${s}.emptyDataSource`})}async onData(e){this._process_data&&(this._on_data?this.checkAndRunInternalFunction(this._on_data,e):this._on&&this._on.data?this.checkAndRunInternalFunction(this._on.data,e):this._once&&this._once.data&&this.checkAndRunInternalFunction(this._once.data,e))}async onFrame(e){this._process_frame&&(this._on_frame?this.checkAndRunInternalFunction(this._on_frame,e):this._on&&this._on.frame?this.checkAndRunInternalFunction(this._on.frame,e):this._once&&this._once.frame&&this.checkAndRunInternalFunction(this._once.frame,e));for(const t of this._children)t.onFrame&&typeof t.onFrame=="function"&&t.onFrame(e)}async run(e,t=!0){let s=this._cache_cmd_txt&&this._cache_cmd_txt==e?this._cache_jcmd:w.parseObjectCommand(e);t&&(this._cache_cmd_txt=e,this._cache_jcmd=s),await this.execute(s)}async execute(e){const t=e?._op;if(!t){c.error(this._id+" missing _op in command");return}const s=e?._module;if(s)try{return await le().execute({...e,_module:s})}catch(n){c.error(this._id+" module execution failed: "+s+"."+t+" "+n);return}if(this._nano_commands[t])try{return await this._nano_commands[t](e,this)}catch(n){c.error(this._id+" has error with command name "+t+" "+n);return}c.error(this._id+" has no command name "+t)}toXData(){const e={};return Object.keys(this).forEach(t=>{if(!this._xporter._ignore_fields.includes(t)&&this.hasOwnProperty(t)&&this[t]!==void 0){const s=this[t];if(typeof s=="function")return;if(typeof s=="object"){const n=Object.keys(this._xporter._instance_xporters);let r=!0;n.forEach(o=>{this._xporter._instance_xporters[o],s instanceof this._xporter._instance_xporters[o].cls&&(e[t]=this._xporter._instance_xporters[o].handler(s),r=!1)}),r&&(e[t]=s)}else e[t]=s}}),e._children=[],this._children.length>0&&this._children.forEach(t=>{typeof t.toXData=="function"&&e._children?.push(t.toXData())}),e}toString(){return JSON.stringify(this.toXData())}clearAttributes(e){e.forEach(t=>{this.hasOwnProperty(t)&&(this[t]=null,delete this[t])})}bindDataSource(e,t){const s=t?.initial??!0,n=e??this._data_source;typeof n!="string"||n.length===0||this._process_data&&(this._xd_bound_key===n&&this._xd_unsub||(this.unbindDataSource(),this._data_source=n,this._xd_bound_key=n,this._type??this.constructor.name,this._id,this._xd_unsub=v.on(n,async r=>{await this.onData(r.value)}),s&&v.has(n)&&this.onData(v.get(n))))}unbindDataSource(){this._xd_unsub?.(),this._xd_unsub=void 0,this._xd_bound_key=void 0}async dispose(){if(this.unbindDataSource(),this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._process_data=!1,this._process_frame=!1,this.removeAllEventListeners(),this.clearAttributes(["_cache_cmd_txt","_cache_jcmd","_nano_commands","_event_listeners_ids","_parent","_on","_once","_xem_options","_xporter"]),this._children&&this._children.forEach(e=>{typeof e.dispose=="function"&&e.dispose()}),this._children=[]}removeChild(e,t=!1){if(t)e.dispose();else{const s=this._children.indexOf(e);s>-1&&this._children.splice(s,1),e._parent=null}}addChild(e){this.append(e)}};S._xtype="object",S._skill=L;let D=S;class he{static getObjects(){return{object:D}}}const ue="engine:module:num-of-objects:",U={_id:"xmodule",_title:"XModule Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime module contract for object ownership, object packs, and executable underscore-prefixed commands.",_core_rules:["Every module must have a unique _name.","Modules expose commands through methods prefixed with underscore.","Command names remove the leading underscore and convert dashes to underscores internally.","Modules own and create registered XObject classes.","Do not mutate another module's objects directly."]};var d;const P=class P{constructor(e){J(this,d);this._loaded=!1,this._loading=!1,this._log_rules={createObject:!1,removeObject:!1},V(this,d,new ee),this._name=e._name,this._id=l.guid()}static getOwnSkillBase(){return{...this._skill}}getOwnSkill(){const t=this.constructor._skill??U;return{...t,_exports:{...t._exports??{},_modules:[{_name:this._name,_scope:t._type==="server-module-api"?"server":"client",_description:t._description,_ops:this.getCommandSkills()}]}}}getSkillChain(){return[this.getOwnSkill()]}getObjectSkills(){const e=[],t=new Set;for(const s of Object.values(p(this,d).getObjectClasses())){if(typeof s.getOwnSkill!="function")continue;const n=s.getOwnSkill();n?._id&&(t.has(n._id)||(t.add(n._id),e.push(n)))}return e}getCommandSkills(){const e=Object.getPrototypeOf(this),s=this.constructor._ops??{};return Object.getOwnPropertyNames(e).filter(n=>n.startsWith("_")&&!n.startsWith("__")&&typeof this[n]=="function").map(n=>{const r=n.slice(1).replaceAll("_","-");return s[r]??{_name:r,_scope:"module",_description:`Runtime module command: ${r}`}})}async load(){if(!(this._loaded||this._loading)){this._loading=!0;try{await this.onLoad(),this._loaded=!0,c.log("Module "+this._name+" loaded")}finally{this._loading=!1}}}async onLoad(){}create(e){e._debug&&c.log("Creating object with data",e);let t;if(e.hasOwnProperty("_type")){e._debug&&c.log("Object type is",e._type,this.hasObject(e._type)?"found":"not found","in module",this._name);const s=String(e._type),n=p(this,d).getObjectClass(s);if(!n)throw`Xpell object '${s}' not found in module '${this._name}'`;typeof n=="function"&&n.hasOwnProperty("defaults")&&l.mergeDefaultsWithData(e,n.defaults),t=new n(e)}else t=new D(e);return p(this,d).addObject(t),e._children&&e._children.forEach(s=>{const n=this.create(s);t.append(n)}),t.onCreate(),t}remove(e){const t=p(this,d).getObject(e);if(!t)return;const s=[],n=r=>{r?._id&&(s.push(r._id),(r._children??[]).forEach(o=>n(o)))};n(t),typeof t.dispose=="function"&&t.dispose(),s.reverse().forEach(r=>p(this,d).removeObject(r))}_info(e){c.log("module info")}async run(e){if(e){let t=e.trim();t.startsWith(this._name)||(t=this._name+" "+t);let s=w.parse(t);return await this.execute(s)}else throw"Unable to parse Xpell Command"}async execute(e){if(!e||!e._op)throw new Error(`Invalid XCommand: missing _op (module: ${this._name})`);const t=e._object;if(t){const r=p(this,d).getObject(t);if(!r)throw new Error(`Module '${this._name}' cant find object id: ${t}`);return await r.execute(e)}const s="_"+e._op.replaceAll("-","_"),n=this[s];if(typeof n=="function")return await n.call(this,e);throw new Error(`Module '${this._name}' cant find op: ${e._op}`)}async onFrame(e){const t=p(this,d)._objects,s=Object.keys(t);s.forEach(n=>{const r=t[n];r&&r.onFrame&&typeof r.onFrame=="function"&&r?.onFrame(e)}),m.set(ue+this._id,s.length,{source:"xmodule"})}get om(){return p(this,d)}get _object_manager(){return p(this,d)}getObject(e){return p(this,d).getObject(e)}hasObject(e){return p(this,d).hasObjectClass(e)}get _o(){return p(this,d)._objects}importObjectPack(e){p(this,d).registerObjects(e.getObjects())}importObjects(e){this.importObjectPack(e)}importObject(e,t){p(this,d).registerObject(e,t)}async _help(e){const t=e?._params?._op??e?._params?._command??"";return this.help(t)}help(e){return{module:this._name,usage:`${this._name} help`,ops:["help"],note:"No help() implemented for this module."}}};d=new WeakMap,P._skill=U,P._ops={help:{_name:"help",_scope:"module",_description:"Return module help or command-specific help."},info:{_name:"info",_scope:"module",_description:"Log basic module information."}};let E=P;const de={_id:"xdata",_title:"XData Runtime State Contract",_version:"1.0.0",_active:!0,_type:"xdata-skill",_description:"Shared runtime state store used by Xpell modules and objects for reactive data binding.",_requires:["xmodule"],_core_rules:["Use XData for shared runtime state.","Use _data_source on objects to bind to an XData key.","Use $xdata.key references in generated payloads when a flow or command needs current state.","Do not use XData as hidden local component state.","XData keys should be explicit and stable."],_fields:{_data_source:"XData key used by XObject/XUIObject for reactive data binding.","$xdata.key":"Runtime payload reference to an XData value."}},k=class k extends E{constructor(){super({_name:k._name})}async _get(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");return{_ok:!0,_result:m.get(s)}}async _set(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");return t._debug&&j.log("XD SET",{key:s,value:t.value}),m.set(s,t.value,{source:t.source??"xd:set"}),{_ok:!0,_result:{key:s}}}async _patch(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");if(!l.is_plain_object(t.value))throw new Error("xd patch expects value as plain object");return m.patch(s,t.value,{source:t.source??"xd:patch"}),{_ok:!0,_result:{key:s}}}async _delete(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");return m.delete(s,{source:t.source??"xd:delete"}),{_ok:!0,_result:{key:s}}}async _touch(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");return m.touch(s,{source:t.source??"xd:touch"}),{_ok:!0,_result:{key:s}}}async _has(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.key,"key");return{_ok:!0,_result:m.has(s)}}};k._name="xd",k._skill=de,k._ops={get:{_name:"get",_scope:"module",_description:"Get value from XData store.",_params:{key:"XData key."}},set:{_name:"set",_scope:"module",_description:"Set value in XData store.",_params:{key:"XData key.",value:"Value to store.",source:"Optional mutation source."}},patch:{_name:"patch",_scope:"module",_description:"Patch plain object into existing XData value.",_params:{key:"XData key.",value:"Plain object patch.",source:"Optional mutation source."}},delete:{_name:"delete",_scope:"module",_description:"Delete XData key.",_params:{key:"XData key.",source:"Optional mutation source."}},touch:{_name:"touch",_scope:"module",_description:"Trigger XData subscribers without changing value.",_params:{key:"XData key.",source:"Optional mutation source."}},has:{_name:"has",_scope:"module",_description:"Check if XData key exists.",_params:{key:"XData key."}}};let C=k;const pe={_id:"xem",_title:"XEventManager Runtime Event Bus",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Global runtime event bus for decoupled communication between Xpell modules, objects, flows, and UI components.",_requires:["xmodule"],_core_rules:["Use XEM for decoupled runtime events.","Use explicit event names and explicit payload objects.","Do not use XEM as state storage.","Use XData for shared state and XEM for notifications/events.","Prefer _on/_once on objects for local event handlers."],_fields:{_on:"Object event handler map.",_once:"Object one-time event handler map.",event:"Event name to fire.",data:"Optional event payload."},_notes:["XEM is process-wide and listener order should not be assumed.","Event payloads should be JSON/data-only."]},O=class O extends E{constructor(){super({_name:O._name})}async _fire(e){const t=l.ensure_params(e?._params),s=l.ensure_string(t.event,"event"),n=t.data;t._debug&&j.log("xem fire 🔥 ",s,n),await x().fire(s,n)}};O._name="xem",O._skill=pe,O._ops={fire:{_name:"fire",_scope:"module",_description:"Fire a global XEM event with optional payload data.",_params:{event:"Event name.",data:"Optional event payload.",_debug:"Optional debug log flag."},_example:{_module:"xem",_op:"fire",_params:{event:"user:login",data:{source:"login-button"}}}}};let I=O;class me{static get(e,t,s){if(!e?._params)return s;const n=e._params[t];return n!==void 0?n:s}static has(e,t){return(e?._params||e)[t]!==void 0}static str(e,...t){const s=e?._params||e;for(const n of t){const r=s?.[n];if(r!=null)return String(r)}}static bool(e,t,s=!1){const n=e?._params||e,r=this.get(n,t,s);if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){const o=r.toLowerCase();if(["1","true","yes","on"].includes(o))return!0;if(["0","false","no","off"].includes(o))return!1}return!!r}static int(e,t,s=0){const n=e?._params||e,r=this.get(n,t,s),o=parseInt(String(r),10);return Number.isFinite(o)?o:s}static json(e,t,s){const n=e?._params||e,r=this.get(n,t,s);if(r==null)return s;if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return s}return s}}class T extends Error{constructor(e,t,s){super(t),this.name="XError",this._code=e,this._level=s?._level??"error",this._meta=s?._meta,this._cause=s?._cause}toXData(){return{_code:this._code,_level:this._level,_meta:this._meta,_cause:this._cause,name:this.name,message:this.message}}toJSON(){return{...this.toXData(),stack:this.stack}}}class b{constructor(e){this._ok=!1,this._ts=Date.now(),this._pt=0,e&&this.setXData(e)}static create(e){return new b(e)}static ok(e){return new b({_ok:!0,_result:e})}static error(e){if(e instanceof T)return new b({_ok:!1,_result:e.toXData()});const t=new T("E_INTERNAL",e?.message??String(e),{_cause:e});return new b({_ok:!1,_result:t.toXData()})}stopProcessTimeCounter(){this._pt=Date.now()-this._ts}toXData(){return this.stopProcessTimeCounter(),{_ok:this._ok,_ts:this._ts,_pt:this._pt,_result:this._result}}toString(){return JSON.stringify(this.toXData())}setXData(e){e&&("_ok"in e&&(this._ok=!!e._ok),"_ts"in e&&typeof e._ts=="number"&&(this._ts=e._ts),"_pt"in e&&typeof e._pt=="number"&&(this._pt=e._pt),"_result"in e&&(this._result=e._result))}}class fe extends b{constructor(e){super(b.error(e).toXData())}}class ge extends b{constructor(e){super({_ok:!0,_result:e})}}const te="engine:frame-number",se="engine:fps";class ne{constructor(e){this._log_rules={},this._modules={},this._schedule_frame=e?._schedule_frame??l.createDefaultScheduler(e?._target_fps),this._version="0.0.1",this._engine_id=l.guid(),this._frame_number=0,this._fps_calc=new oe,this.parser=w,this._modules={},c._enabled=!1,_e(this)}set verbose(e){c._enabled=e}set _verbose(e){c._enabled=e}log(e,...t){c.log(e,...t)}async delay(e){return new Promise(t=>setTimeout(t,e))}addModule(e){return this._modules.hasOwnProperty(e._name)?(c.log("Module "+e._name+" already loaded"),!1):(this._modules[e._name]=e,!0)}loadModule(e){this.addModule(e)&&e.load()}loadModules(...e){e.forEach(t=>this.loadModule(t))}async loadModuleAsync(e){this.addModule(e)&&await e.load()}async loadModulesAsync(...e){for(const t of e)await this.loadModuleAsync(t)}info(){c.log(`Xpell information:
|
|
1
|
+
"use strict";var J=o=>{throw TypeError(o)};var V=(o,e,t)=>e.has(o)||J("Cannot "+t);var f=(o,e,t)=>(V(o,e,"read from private field"),t?t.call(o):e.get(o)),K=(o,e,t)=>e.has(o)?J("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(o):e.set(o,t),G=(o,e,t,s)=>(V(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class Y{createIgnoreList(e,t){if(!e)return t;const s=e.split(",").map(r=>r.trim()).filter(Boolean);for(const r of s)t[r]="";return t}guid(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const i=new Uint8Array(16);t.getRandomValues(i),i[6]=i[6]&15|64,i[8]=i[8]&63|128;const c=Array.from(i,a=>a.toString(16).padStart(2,"0"));return c.slice(0,4).join("")+"-"+c.slice(4,6).join("")+"-"+c.slice(6,8).join("")+"-"+c.slice(8,10).join("")+"-"+c.slice(10,16).join("")}const s="0123456789abcdef".split(""),r=[];let n;r[8]=r[13]=r[18]=r[23]="-",r[14]="4";for(let i=0;i<36;i++)r[i]||(n=(0|Math.random()*16)>>>0,r[i]=s[i===19?n&3|8:n&15]);return r.join("")}mergeDefaultsWithData(e,t,s=!1){if(!e)return t;e._id||(e._id=e.id??this.guid());for(const r of Object.keys(t))(!(r in e)||s)&&(e[r]=t[r]);return e}deepMergeDefaults(e,t){if(!e||typeof e!="object"||Array.isArray(e))return structuredClone(t);const s=structuredClone(t);for(const r of Object.keys(e)){const n=e[r],i=t?.[r];n&&typeof n=="object"&&!Array.isArray(n)&&i&&typeof i=="object"&&!Array.isArray(i)?s[r]=this.deepMergeDefaults(n,i):s[r]=n}return s}encode(e){const t=globalThis;if(typeof t.btoa=="function"){const s=encodeURIComponent(String(e)).replace(/%([0-9A-F]{2})/g,(r,n)=>String.fromCharCode(parseInt(n,16)));return t.btoa(s)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"utf8").toString("base64");throw new Error("Base64 encode not supported in this environment")}decode(e){const t=globalThis;if(typeof t.atob=="function"){const s=t.atob(String(e)),r=Array.prototype.map.call(s,n=>"%"+n.charCodeAt(0).toString(16).padStart(2,"0")).join("");return decodeURIComponent(r)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"base64").toString("utf8");throw new Error("Base64 decode not supported in this environment")}getRandomInt(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}getParam(e,t,s=0){return e?._params?.[t]??s}createDefaultScheduler(e){const t=globalThis;if(typeof t.requestAnimationFrame=="function")return n=>t.requestAnimationFrame(n);const s=typeof e=="number"&&isFinite(e)&&e>0?e:60;if(typeof t.setImmediate=="function"&&(!e||e>=60))return n=>t.setImmediate(n);const r=Math.max(1,Math.round(1e3/s));return n=>t.setTimeout(n,r)}to_iso_now(){return new Date().toISOString()}is_plain_object(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}ensure_object(e,t){if(!this.is_plain_object(e))throw new Error(`Invalid '${t}'`);return e}ensure_string(e,t){if(typeof e!="string"||!e.trim())throw new Error(`Invalid '${t}'`);return e.trim()}ensure_boolean(e,t){if(typeof e=="boolean")return e;if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid '${t}'`)}ensure_number(e,t){const s=Number(e);if(isNaN(s))throw new Error(`Invalid '${t}'`);return s}ensure_params(e){return this.is_plain_object(e)?e:{}}addIfNotNull(e,t,s){if(!(!e||!t||!Array.isArray(s)))for(const r of s){const n=e[r];n!=null&&(t[r]=n)}}als(e){const t=String(e??"");return t.endsWith("/")?t:t+"/"}cls(e){const t=String(e??"");return t.endsWith("/")?t.slice(0,-1):t}afs(e){const t=String(e??"");return t.startsWith("/")?t:"/"+t}cfs(e){const t=String(e??"");return t.startsWith("/")?t.slice(1):t}calculateExpiration(e){const s=String(e??"").trim().match(/^(\d+)([hdy])$/);if(!s)throw new Error("Invalid expiration format. Use: 1h | 2d | 3y");const r=Number.parseInt(s[1],10),n=s[2],i=Date.now();let c=0;switch(n){case"h":c=r*60*60*1e3;break;case"d":c=r*24*60*60*1e3;break;case"y":c=r*365*24*60*60*1e3;break}return i+c}normalize_prompt(e){return String(e??"").normalize("NFKC").replace(/\s+/g," ").trim()}normalize_prompt_key(e){return this.normalize_prompt(e).toLowerCase().replace(/[_/]+/g," ")}is_non_empty_string(e){return typeof e=="string"&&e.trim().length>0}has_value(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}ensure_array(e){return Array.isArray(e)?e:e==null?[]:[e]}to_record(e){return this.is_plain_object(e)?e:{}}safe_json_parse(e,t){if(typeof e!="string")return t;try{return JSON.parse(e)}catch{return t}}safe_json_stringify(e,t="{}"){try{return JSON.stringify(e)}catch{return t}}clone_json(e){return this.safe_json_parse(this.safe_json_stringify(e,"null"),e)}get_path(e,t,s){const r=Array.isArray(t)?t:String(t??"").split(".").filter(Boolean);let n=e;for(const i of r){if(n==null)return s;n=n[i]}return n===void 0?s:n}set_path(e,t,s){const r=Array.isArray(t)?t:String(t??"").split(".").filter(Boolean);if(!r.length)return e;let n=e;for(let i=0;i<r.length-1;i++){const c=r[i];this.is_plain_object(n[c])||(n[c]={}),n=n[c]}return n[r[r.length-1]]=s,e}pick_defined(e,t){const s={};if(!this.is_plain_object(e)||!Array.isArray(t))return s;for(const r of t){const n=e[r];n!=null&&(s[r]=n)}return s}omit_undefined(e){const t={};if(!this.is_plain_object(e))return t;for(const[s,r]of Object.entries(e))r!==void 0&&(t[s]=r);return t}escape_regexp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}matches_keyword(e,t){const s=/^[a-z0-9]+$/.test(t)?"s?":"";return new RegExp(`(^|[^a-z0-9])${this.escape_regexp(t)}${s}($|[^a-z0-9])`).test(e)}match_keywords(e,t){return t.filter(s=>this.matches_keyword(e,s))}contains_keyword(e,t){return this.match_keywords(e,t).length>0}read_optional_string(e,t){if(e!=null){if(typeof e!="string"||e.trim().length===0)throw new Error(`Invalid '${t}': expected non-empty string`);return e.trim()}}read_optional_boolean(e,t){if(e!=null){if(typeof e!="boolean")throw new Error(`Invalid '${t}': expected boolean`);return e}}read_optional_number(e,t){if(e!=null){if(typeof e!="number"||!isFinite(e))throw new Error(`Invalid '${t}': expected finite number`);return e}}read_optional_object(e,t){if(e!=null){if(!this.is_plain_object(e))throw new Error(`Invalid '${t}': expected plain object`);return e}}unique_strings(e){return Array.from(new Set(e))}unique_normalized_ids(e){return Array.from(new Set(e.map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)))}truncate_text(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-18))}
|
|
2
|
+
...[truncated]`}compact_json(e,t=5e3){return this.truncate_text(JSON.stringify(e,null,2),t)}compact_inline_json(e,t=5e3){return this.truncate_text(JSON.stringify(e),t)}safe_compact_inline_json(e,t=5e3){try{return this.compact_inline_json(e,t)}catch{return""}}compact_array(e,t=20){return Array.isArray(e)?e.slice(0,t):[]}normalize_id(e){if(typeof e!="string")return;const t=e.toLowerCase().trim().replace(/[_\s]+/gu,"-").replace(/[^a-z0-9-]+/gu,"-").replace(/-+/gu,"-").replace(/^-|-$/gu,"");return t.length>0?t:void 0}normalize_id_array(e){return Array.isArray(e)?e.map(t=>this.normalize_id(t)).filter(t=>typeof t=="string").filter((t,s,r)=>r.indexOf(t)===s):[]}normalize_string_array(e){return this.normalize_id_array(e)}ensure_object_array(e){return Array.isArray(e)?e.filter(t=>this.is_plain_object(t)):[]}read_object_array(e){return this.ensure_object_array(e)}}const Z=new Y,u=Z;class ae{#e=0;#t=0;#s=0;#r;#n;constructor(e=.05,t=1){const s=Number(e);this.#r=Number.isFinite(s)?Math.min(1,Math.max(.001,s)):.05;const r=Number(t);this.#n=Number.isFinite(r)?Math.max(0,Math.floor(r)):1}now(){const e=globalThis.performance;return e&&typeof e.now=="function"?e.now():Date.now()}calc(){const e=this.now();if(this.#s===0)return this.#s=e,this.#e;const t=e-this.#s;if(this.#s=e,!Number.isFinite(t)||t<=0)return this.#e;this.#t===0?this.#t=t:this.#t=(1-this.#r)*this.#t+this.#r*t;const s=1e3/this.#t;if(!Number.isFinite(s)||s<=0)return this.#e;const r=Math.round(s);return this.#e!==0&&this.#n>0&&Math.abs(r-this.#e)<this.#n?this.#e:(this.#e=r,this.#e)}reset(){this.#e=0,this.#t=0,this.#s=0}}class ee{constructor(e){this._enabled=!0,this._show_date=!1,this._show_time=!0,this._debug=!1,e&&this.configure(e)}configure(e){typeof e._enabled=="boolean"&&(this._enabled=e._enabled),typeof e._show_date=="boolean"&&(this._show_date=e._show_date),typeof e._show_time=="boolean"&&(this._show_time=e._show_time),typeof e._debug=="boolean"&&(this._debug=e._debug)}_dt(){const e=new Date,t=this._show_date?`${e.getDate()}.${e.getMonth()}.${e.getFullYear()} `:"",s=this._show_time?`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()}|`:"";return t+s}log(e,...t){this._enabled&&console.log(this._dt(),e,...t)}warn(e,...t){this._enabled&&console.warn(this._dt(),e,...t)}error(e,...t){this._enabled&&console.error(this._dt(),e,...t)}debug(e,...t){!this._enabled||!this._debug||console.debug(this._dt(),e,...t)}}const h=new ee,te=typeof process<"u"&&!!process?.env&&process.env.NODE_ENV==="production";te||console.info("[Xpell] _xlog is redirected to console in development mode. Tip: enable 'Show timestamps' in DevTools → Console for timed logs.");const x=te?h:console;class se{constructor(){this._objects={},this._listeners=new Map,this._any_listeners=new Set,this._compat_writes=!0,this._warn_legacy_writes=!0,this._verbose=!1,this._compat_legacy_keys=!0,this._o_proxy=null,this._objects={}}get _o(){return!this._compat_writes&&!this._warn_legacy_writes?this._objects:(this._o_proxy||(this._o_proxy=new Proxy(this._objects,{set:(e,t,s)=>{const r=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy write: _o["${r}"] = ... ; prefer XData.set("${r}", value).`),this._compat_writes?this.set(r,s,{source:"legacy:_o"}):e[r]=s,!0},deleteProperty:(e,t)=>{const s=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy delete: delete _o["${s}"] ; prefer XData.delete("${s}").`),this._compat_writes?this.delete(s,{source:"legacy:_o"}):delete e[s],!0}})),this._o_proxy)}get(e){return this._objects[e]}set(e,t,s){const r=this._objects[e];this._objects[e]=t,this._emit({key:e,value:t,prev:r,ts:Date.now(),op:"set",meta:s})}patch(e,t,s){const r=this._objects[e],i={...r&&typeof r=="object"?r:{},...t};this._objects[e]=i,this._emit({key:e,value:i,prev:r,ts:Date.now(),op:"patch",meta:s})}touch(e,t){const s=this._objects[e];this._emit({key:e,value:s,prev:s,ts:Date.now(),op:"touch",meta:t})}has(e){return Object.prototype.hasOwnProperty.call(this._objects,e)}delete(e,t){const s=this._objects[e];delete this._objects[e],this._emit({key:e,value:void 0,prev:s,ts:Date.now(),op:"delete",meta:t})}pick(e,t){const s=this._objects[e];return this.delete(e,t),s}clean(){this._objects={}}on(e,t){let s=this._listeners.get(e);return s||this._listeners.set(e,s=new Set),s.add(t),()=>this.off(e,t)}off(e,t){const s=this._listeners.get(e);s&&(s.delete(t),s.size===0&&this._listeners.delete(e))}onAny(e){return this._any_listeners.add(e),()=>this._any_listeners.delete(e)}_emit(e){this._verbose&&e.meta?.trace&&(e.stack=new Error().stack);const t=this._listeners.get(e.key);if(t)for(const s of t)s(e);for(const s of this._any_listeners)s(e)}}const k=new se,m=k;class F{constructor(e){e&&Object.keys(e).forEach(t=>{this[t]=e[t]}),this.d||(this.d=Date.now())}getParam(e,t,s){return this._params?.hasOwnProperty(t)?this._params[t]:this._params?.hasOwnProperty(e)?this._params[e]:s}}const C={type:"_type",children:"_children"},v=class v{static addHtml2XpellMapItem(e,t){v.html2XMap.elements[e]=t}static parse(e,t){const s=e.split(" ");let r=new F;if(t?(r._module=t,r._op=s[0]):(r._module=s[0],r._op=s[1]),r._params={},s.length>1)for(let n=2;n<s.length;++n){const i=s[n];if(i.indexOf(":")>-1){const a=i.split(":");r._params[a[0]]=a[1]}else r._params[n-1]=s[n]}return r}static replaceSpacesInQuotes(e,t="_%20_"){return e.replace(/(['"])(.*?)\1/g,(s,r,n)=>{const i=String(n).replace(/\s/g,t);return`${r}${i}${r}`})}static parseObjectCommand(e,t){e=v.replaceSpacesInQuotes(e);const s=e.trim().split(/\s+/),r=t||s.shift();if(!r)throw new Error("Missing module name");let n;if(s[0]?.startsWith("#")&&(n=s.shift().slice(1),!n))throw new Error("Invalid object selector '#'. Use '#<id>'");const i=s.shift();if(!i)throw new Error("Missing operation");const c={};let a=null,_=null;if(s.forEach(l=>{if(_){if(_+=` ${l}`,l.endsWith(_[0])){const d=_.slice(1,-1).replace(/_%20_/g," ");c[a]=d,_=null}return}if(l.startsWith('"')||l.startsWith("'")){if(_=l,l.endsWith(l[0])&&l.length>1){const d=l.slice(1,-1).replace(/_%20_/g," ");c[a]=d,_=null}return}if(l.includes(":")){const d=l.split(":"),y=d[0],g=d.slice(1).join(":").replace(/_%20_/g," ");c[y]=g,a=null;return}a=l.replace(/_%20_/g," ")}),_)throw new Error("Unclosed quoted parameter value");return{_module:r,_object:n,_op:i,_params:c}}static xmlString2Xpell(e){const s=new DOMParser().parseFromString(e,"text/xml");return s.childNodes.length>0?v.xml2Xpell(s.childNodes[0]):{}}static xml2Xpell(e,t){const s=v.html2XMap;let r={};r._children=[];const n=e.nodeName,i=e.nodeName;let c=t;if(t?(r[C.type]="xhtml",r._html_ns="http://www.w3.org/2000/svg"):r._type=s.elements[n]?s.elements[n]:n,e.attributes)for(let a=0;a<e.attributes.length;++a){const _=e.attributes[a],l=s.attributes[_.name]?s.attributes[_.name]:_.name;r[l]=_.value}if(e?.firstChild?.nodeValue&&(r.text=e?.firstChild.nodeValue.trim()),r[C.type]=="xhtml"?r._html_tag=i:r[C.type]=="svg"&&(c=!0,r._html_ns="http://www.w3.org/2000/svg"),e?.childNodes.length>0)for(let a=0;a<e.childNodes.length;++a){const _=e.childNodes[a];_.nodeName.startsWith("#")||r[C.children].push(v.xml2Xpell(_,c))}return r}};v.html2XMap={elements:{div:"view",a:"link",b:"xhtml",h1:"xhtml",h2:"xhtml",h3:"xhtml",h4:"xhtml",h5:"xhtml",p:"xhtml",small:"xhtml",aside:"xhtml",span:"xhtml",table:"xhtml",th:"xhtml",td:"xhtml",tr:"xhtml",thead:"xhtml",tbody:"xhtml",ul:"xhtml",li:"xhtml",ol:"xhtml",canvas:"xhtml",img:"image"},attributes:{id:"_id"}};let O=v;class re{#e;#t;#s;constructor(){this.#e={},this.#t={},this.#s={}}get _objects(){return this.#t}hasObject(e){return this.#t.hasOwnProperty(e)}registerObjects(e){Object.keys(e).forEach(s=>this.registerObject(s,e[s]))}registerObject(e,t){this.#e[e]=t}hasObjectClass(e){return this.#e.hasOwnProperty(e)}getObjectClass(e){return this.#e[e]}getAllClasses(){return this.getObjectClasses()}getObjectClasses(){return this.#e}get _classes(){return this.#e}addObject(e){e&&e._id?(this.#t[e._id]=e,(!e._name||e._name.length==0)&&(e._name=e._id),this.#s[e._name]=e._id):h.log("unable to add object")}removeObject(e){const t=this.#t[e];t&&(delete this.#s[t?._name],delete this.#t[e])}getObject(e){return this.#t[e]}go(e){return this.getObject(e)}getObjectByName(e){return this.#s[e]?this.getObject(this.#s[e]):null}}class ce{constructor(){this._log_rules={register:!1,remove:!1,fire:!1},this._events={},this._listener_index={}}on(e,t,s={},r){this._events[e]||(this._events[e]=[]);const n=s?._owner??r,i=u.guid(),c={_id:i,_callback:t,_options:s,_owner:n,_tag:s?._tag};return this._events[e].push(c),this._listener_index[i]=e,this._log_rules.register&&x.log("XEM Register",e,i),i}once(e,t,s){return this.on(e,t,{_once:!0,_owner:s})}async fire(e,t){const s=this._events[e];if(!s||s.length===0)return;this._log_rules.fire&&x.log("XEM Fire",e,t);const r=s.slice(),n=[];for(const i of r){try{i&&i._callback&&i._callback(t)}catch(c){x.error(c)}i?._options?._once&&n.push(i._id)}for(const i of n)this.remove(i)}remove(e){const t=this._listener_index[e];if(!t)return;const s=this._events[t];if(s&&s.length){const r=s.findIndex(n=>n?._id===e);r>=0&&s.splice(r,1),s.length===0&&delete this._events[t]}delete this._listener_index[e],this._log_rules.remove&&x.log("XEM Remove",t,e)}removeOwner(e){if(!e)return;const t=[];for(const s of Object.values(this._events))for(const r of s)(r?._owner??r?._options?._owner)===e&&t.push(r._id);t.forEach(s=>this.remove(s))}clear(){this._events={},this._listener_index={}}}let U;function _e(o){U=o}function D(){if(!U)throw new Error("XEventManager not set");return U}const le=["_nano_commands","_cache_cmd_txt","_cache_jcmd","_xporter","_event_listeners_ids","_parent","_children"];function $(o){return le.includes(o)}function H(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function b(o,e){return o._skill=e,o.getSkill=()=>e,o}const Q={info:b((o,e)=>{h.log("XObject id "+e?._id)},{_name:"info",_scope:"object",_description:"Logs the current object's id."}),log:b((o,e)=>{o._params&&o._params[1]?h.log(o._params[1]):h.log(e)},{_name:"log",_scope:"object",_description:"Logs a message or the current object.",_params:{1:"Optional message to log."}}),fire:b((o,e)=>{o._params&&o._params[1]?D().fire(String(o._params[1]),o._params[2]):o._params&&o._params.event&&D().fire(String(o._params.event),o._params.data)},{_name:"fire",_scope:"object",_description:"Fires an XEventManager event.",_params:{event:"Event name.",data:"Optional event payload.",1:"Event name shorthand.",2:"Event payload shorthand."},_example:{_op:"fire",_params:{event:"user:login",data:{source:"button"}}}}),noop:b(()=>{},{_name:"noop",_scope:"object",_description:"No-op command. Useful as a placeholder in sequences."}),"set-field":b((o,e)=>{const t=o._params?.name,s=o._params?.value;if(!(!e||typeof t!="string"||t.length===0)){if($(t)){h.error(`set-field denied for protected field: ${t}`);return}e[t]=s}},{_name:"set-field",_scope:"object",_description:"Sets a runtime field directly on the current object.",_params:{name:"Field name.",value:"Value to assign."},_example:{_op:"set-field",_params:{name:"_text",value:"Hello"}}}),"delete-field":b((o,e)=>{const t=o._params?.name;if(!(!e||typeof t!="string"||t.length===0)){if($(t)){h.error(`delete-field denied for protected field: ${t}`);return}delete e[t]}},{_name:"delete-field",_scope:"object",_description:"Deletes a runtime field from the current object.",_params:{name:"Field name to delete."}}),"toggle-field":b((o,e)=>{const t=o._params?.name;if(!e||typeof t!="string"||t.length===0)return;if($(t)){h.error(`toggle-field denied for protected field: ${t}`);return}const s=e[t];typeof s=="boolean"?e[t]=!s:s==null?e[t]=!0:e[t]=!1},{_name:"toggle-field",_scope:"object",_description:"Toggles a runtime field using boolean-first semantics.",_params:{name:"Field name to toggle."}}),merge:b((o,e)=>{const t=o._params?.name,s=o._params?.value;if(!e||typeof t!="string"||t.length===0)return;if($(t)){h.error(`merge denied for protected field: ${t}`);return}if(!H(s)){h.error("merge expects _params.value as a plain object");return}const r=e[t];H(r)||(e[t]={}),Object.assign(e[t],s)},{_name:"merge",_scope:"object",_description:"Shallow-merges a plain object into a target object field.",_params:{name:"Target field name.",value:"Plain object to merge."}}),"run-seq":b(async(o,e)=>{if(!e)return;const t=o._params?.seq;if(!Array.isArray(t)){h.error("run-seq expects _params.seq as an array");return}for(const s of t){if(typeof s=="string"){await e.run(`${e._id} ${s}`);continue}if(s&&typeof s=="object"&&s._op){const r=s._object;if(!(r==null||r==="this"||r===e._id)){h.error("run-seq rejected non-self _object target");return}const i={_op:s._op,_params:s._params?{...s._params}:void 0};await e.execute(i);continue}h.error("run-seq skipped invalid step; expected string or object with _op")}},{_name:"run-seq",_scope:"object",_description:"Runs a sequence of local nano-command steps in strict order.",_params:{seq:"Array of command strings or local command objects."},_example:{_op:"run-seq",_params:{seq:[{_op:"set-field",_params:{name:"_debug",value:!0}},{_op:"log",_params:{1:"Debug enabled"}}]}}})};let W;function he(o){W=o}function ue(){if(!W)throw new Error("XRuntime not set");return W}const q={_id:"xobject",_title:"XObject Core Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime object for identity, typing, composition, lifecycle hooks, events, data binding, and nano-command execution.",_fields:{_id:"Unique object id.",_type:"Registered runtime object type.",_name:"Optional object name.",_children:"Child objects/data.",_data_source:"XData key to bind this object to.",_on:"Event handlers map.",_once:"One-time event handlers map.",_on_create:"Lifecycle handler after object creation.",_on_mount:"Lifecycle handler after mount.",_on_frame:"Frame lifecycle handler.",_on_data:"Data-source lifecycle handler.",_process_frame:"Enable/disable frame processing.",_process_data:"Enable/disable data-source processing.",_debug:"Enable object debug logs."},_exports:{_xui_fields:["_id","_type","_name","_children","_data_source","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_debug"]},_core_rules:["All Xpell runtime objects inherit this contract.","Generated object JSON must be data-only.","Do not generate JavaScript functions.","Use _children for composition.","Use _on/_once with nano-command strings or data-only command objects."],_notes:["Runtime methods include parse, append, run, execute, bindDataSource, unbindDataSource, toXData, dispose, and removeChild.","Most prompts should use this skill as a compact dependency summary, not full context."]},L={_children:"child nodes"},E=class E{constructor(e,t,s){this._children=[],this._parent=null,this._on={},this._once={},this._process_frame=!0,this._process_data=!0,this._nano_commands={},this._event_listeners_ids={},this._event_parsed=!1,this._mounted=!1,this._xporter={_ignore_fields:["_to_xdata_ignore_fields","_xporter","_children","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_parent","_event_listeners_ids","_event_parsed","_mounted","_debug"],_instance_xporters:{}},t&&u.mergeDefaultsWithData(e,t),this._id=e&&e._id?e._id:"xo-"+u.guid(),this._type="object",this._children=[],this._nano_commands={},this.addNanoCommandPack(Q),e&&e.hasOwnProperty("_nano_commands")&&e._nano_commands&&(this.addNanoCommandPack(e._nano_commands),delete e._nano_commands),this.addXporterDataIgnoreFields(["_nano_commands"]),this.addXporterInstanceXporter(E,r=>r.toXData()),this._xem_options={},!s&&e&&this.parse(e,L)}static getOwnSkill(){const e=this,t=e._skill??q;return{...t,_exports:{...t._exports??{},_nano_commands:e.getNanoCommandSkills?.()??[]}}}static getSkillChain(){const e=Object.getPrototypeOf(this),t=e&&typeof e.getSkillChain=="function"?e.getSkillChain():[],s=Object.prototype.hasOwnProperty.call(this,"_skill")?this.getOwnSkill():null;return s?[...t,s]:t}static getOwnNanoCommands(){return{...Q}}static getNanoCommands(){return{...this.getOwnNanoCommands()}}static getNanoCommandSkills(){return Object.prototype.hasOwnProperty.call(this,"getOwnNanoCommands")?Object.values(this.getOwnNanoCommands()).map(t=>t.getSkill?.()??t._skill).filter(Boolean):[]}static getArtifactStrategy(){return"canonical"}static generateArtifact(e={}){const t=this.getOwnSkill?.(),s=t?._canonical_examples?.[0],r=s?this.cloneArtifact(s):{_type:this._xtype??t?._id??"object"};return this.applyArtifactIntent(r,e)}static cloneArtifact(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}static applyArtifactIntent(e,t={}){const s=e;return t._id&&(s._id=t._id),t._label&&("_label"in s?s._label=t._label:"_text"in s?s._text=t._label:"_title"in s&&(s._title=t._label)),t._text&&"_text"in s&&(s._text=t._text),t._title&&"_title"in s&&(s._title=t._title),t._description&&"_description"in s&&(s._description=t._description),t._variant&&"_variant"in s&&(s._variant=t._variant),t._tone&&"_tone"in s&&(s._tone=t._tone),t._size&&"_size"in s&&(s._size=t._size),t._density&&"_density"in s&&(s._density=t._density),t._elevation&&"_elevation"in s&&(s._elevation=t._elevation),t.class&&(s.class=t.class),t._placeholder&&("placeholder"in s?s.placeholder=t._placeholder:"_placeholder"in s&&(s._placeholder=t._placeholder)),t._data_output&&"_data_output"in s&&(s._data_output=t._data_output),Array.isArray(t._children)&&(s._children=t._children),Array.isArray(t._actions)&&(s._actions=t._actions),Array.isArray(t._items)&&(s._items=t._items),t._flow_id&&(s._flow={_id:t._flow_id,_payload:t._payload??{}}),t._flow_event&&(s._flow_event=t._flow_event),s}static validateArtifact(e){const t=[];return(!e||typeof e!="object")&&t.push("artifact must be an object"),e._type||t.push("artifact requires _type"),{_ok:t.length===0,_errors:t}}log(e,...t){this._debug&&e&&h.log(this._type+"->"+this._id+"]",e,...t)}init(e,t){!t&&e&&this.parse(e,L)}parseEvents(e){if(!this._event_parsed){e||(e=this._xem_options),Object.keys(this._on).forEach(s=>{this.addEventListener(s,this._on[s],e)});const t={};Object.assign(t,e),t._once=!0,Object.keys(this._once).forEach(s=>{this.addEventListener(s,this._once[s],t)}),this._event_parsed=!0}}addEventListener(e,t,s){s||(s=this._xem_options);const r=async i=>{await this.checkAndRunInternalFunction(t,i)},n=D().on(e,r,s,this);return this._event_listeners_ids[e]||(this._event_listeners_ids[e]=[]),this._event_listeners_ids[e].push(n),n}removeEventListener(e){const t=this._event_listeners_ids;if(!t||typeof t!="object"||Array.isArray(t)){this._event_listeners_ids={};return}(Array.isArray(t[e])?[...t[e]]:[]).forEach(r=>{try{D().remove(r)}catch{}}),delete t[e]}removeAllEventListeners(e){const t=this._event_listeners_ids;if(!t||typeof t!="object"||Array.isArray(t)){this._event_listeners_ids={};return}(e?[e]:Object.keys(t)).forEach(r=>{try{this.removeEventListener(r)}catch{}})}append(e){this._children?.push(e),e._parent=this}addNanoCommand(e,t){typeof t=="function"&&(this._nano_commands[e]=t)}addNanoCommandPack(e){e&&Object.keys(e).forEach(t=>{this.addNanoCommand(t,e[t])})}addXporterDataIgnoreFields(e){this._xporter._ignore_fields=this._xporter._ignore_fields.concat(e)}addXporterInstanceXporter(e,t){const s=u.guid();this._xporter._instance_xporters[s]={cls:e,handler:t}}parse(e,t=L){Object.keys(e).forEach(r=>{!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&(this[r]=e[r])})}parseFieldsFromXDataObject(e,t){Object.keys(t).forEach(r=>{e.hasOwnProperty(r)?this[r]=e[r]:this[r]=t[r]})}parseFields(e,t,s){t.forEach(r=>{if(e.hasOwnProperty(r))this[r]=e[r];else if(s&&r.startsWith("_")){const n=r.substring(1);e.hasOwnProperty(n)&&(this[r]=e[n],this[n]=e[n])}})}async onCreate(){this._on_create?this.checkAndRunInternalFunction(this._on_create):this._on&&this._on.create?this.checkAndRunInternalFunction(this._on.create):this._once&&this._once.create&&this.checkAndRunInternalFunction(this._once.create)}async runCmd(e){const t=e instanceof F?e:new F(e);await this.execute(t)}async checkAndRunInternalFunction(e,...t){const s=(i,c)=>{const a=c.split(".");let _=i;for(const l of a){if(_==null)return;_=_[l]}return _},r=(i,c,a)=>{if(typeof i=="string"){if(i==="$prev")return c;if(i.startsWith("$prev."))return s(c,i.slice(6));if(i==="$event")return t[0];if(i.startsWith("$event."))return s(t[0],i.slice(7));if(i==="$data")return t[0];if(i.startsWith("$data."))return s(t[0],i.slice(6));if(i.startsWith("$xdata:")||i.startsWith("$xdata.")){const l=(i.startsWith("$xdata:"),i.slice(7)).split(".");for(let d=l.length;d>0;d--){const y=l.slice(0,d).join(".");if(k.has(y)){const g=k.get(y),j=l.slice(d).join(".");return j?u.get_path(g,j):g}}return}if(i.startsWith("$")&&a&&typeof a=="object"){const _=i.slice(1),l=_.indexOf("."),d=l===-1?_:_.slice(0,l),y=l===-1?"":_.slice(l+1);if(Object.prototype.hasOwnProperty.call(a,d)){const g=a[d];return y?s(g,y):g}}return i}if(Array.isArray(i))return i.map(_=>r(_,c,a));if(i&&typeof i=="object"){const _={};for(const l of Object.keys(i))_[l]=r(i[l],c,a);return _}return i},n=async(i,c)=>{if(Array.isArray(i)){let a;for(const _ of i)a=await n(_,a);return a}if(typeof i=="function")return await i(this,...t);if(typeof i=="string"){const a=O.parseObjectCommand(`${this._id} ${i}`);if(t.length>0){a._params=a._params||{};const _=t[0];a._params._event=_,!a._params.data&&!_?.target&&(a._params.data=_)}return await this.execute(a)}if(i&&typeof i=="object"&&Array.isArray(i._commands)){const a=i,_=typeof a._mode=="string"?a._mode:"sequence",l=a._stop_on_error!==!1,d=a._commands;if(_==="parallel"){const g=await Promise.allSettled(d.map(R=>n(R,c))),j=g.find(R=>R.status==="rejected");if(j&&l)throw j.reason;return g}let y=c;for(const g of d)try{y=await n(g,_==="chain"?y:c)}catch(j){if(h.error(this._type+"->"+this._id+"] command sequence failed",j),l)throw j}return y}if(i&&typeof i=="object"&&i._op){const a=i;if((a._object===void 0||a._object===null||a._object==="this"?this._id:a._object)!==this._id){h.error("XObject JSON handler target not supported; expected _object omitted/'this'/"+this._id);return}const l={...a,_params:a._params?{...a._params}:{}};if(t.length>0){const d=t[0];Object.prototype.hasOwnProperty.call(l._params,"data")||(l._params.data=d),Object.prototype.hasOwnProperty.call(l._params,"_event")||(l._params._event=d)}return l._params=r(l._params,c,this._context),this._debug&&h.log(this._type+"->"+this._id+"]","JSON handler executed locally",l),await this.execute(l)}h.error(this._type+"->"+this._id+"] invalid handler in checkAndRunInternalFunction",i)};return await n(e)}async onMount(){if(!this._mounted){this.parseEvents(this._xem_options),this._process_data&&typeof this._data_source=="string"&&this._data_source.length>0&&this.bindDataSource(this._data_source,{initial:!0}),this._on_mount?await this.checkAndRunInternalFunction(this._on_mount):this._on&&this._on.mount?await this.checkAndRunInternalFunction(this._on.mount):this._once&&this._once.mount&&await this.checkAndRunInternalFunction(this._once.mount),this._mounted=!0;for(const e of this._children)e.onMount&&typeof e.onMount=="function"&&e.onMount()}}emptyDataSource(){const e=this._data_source;if(typeof e!="string"||e.length===0)return;const t=this._type??this.constructor.name,s=this._id??"no-id";k.delete(e,{source:`${t}#${s}.emptyDataSource`})}async onData(e){this._process_data&&(this._on_data?this.checkAndRunInternalFunction(this._on_data,e):this._on&&this._on.data?this.checkAndRunInternalFunction(this._on.data,e):this._once&&this._once.data&&this.checkAndRunInternalFunction(this._once.data,e))}async onFrame(e){this._process_frame&&(this._on_frame?this.checkAndRunInternalFunction(this._on_frame,e):this._on&&this._on.frame?this.checkAndRunInternalFunction(this._on.frame,e):this._once&&this._once.frame&&this.checkAndRunInternalFunction(this._once.frame,e));for(const t of this._children)t.onFrame&&typeof t.onFrame=="function"&&t.onFrame(e)}async run(e,t=!0){let s=this._cache_cmd_txt&&this._cache_cmd_txt==e?this._cache_jcmd:O.parseObjectCommand(e);t&&(this._cache_cmd_txt=e,this._cache_jcmd=s),await this.execute(s)}async execute(e){const t=e?._op,s=typeof t=="string"&&t.startsWith("_")&&t.length>1?t.slice(1):t;if(!s){h.error(this._id+" missing _op in command");return}const r=e?._module;if(r)try{return await ue().execute({...e,_module:r,_op:s})}catch(n){h.error(this._id+" module execution failed: "+r+"."+s+" "+n);return}if(this._nano_commands[s])try{const n={...e,_op:s};return await this._nano_commands[s](n,this)}catch(n){h.error(this._id+" has error with command name "+s+" "+n);return}h.error(this._id+" has no command name "+s)}toXData(){const e={};return Object.keys(this).forEach(t=>{if(!this._xporter._ignore_fields.includes(t)&&this.hasOwnProperty(t)&&this[t]!==void 0){const s=this[t];if(typeof s=="function")return;if(typeof s=="object"){const r=Object.keys(this._xporter._instance_xporters);let n=!0;r.forEach(i=>{this._xporter._instance_xporters[i],s instanceof this._xporter._instance_xporters[i].cls&&(e[t]=this._xporter._instance_xporters[i].handler(s),n=!1)}),n&&(e[t]=s)}else e[t]=s}}),e._children=[],this._children.length>0&&this._children.forEach(t=>{typeof t.toXData=="function"&&e._children?.push(t.toXData())}),e}toString(){return JSON.stringify(this.toXData())}clearAttributes(e){e.forEach(t=>{this.hasOwnProperty(t)&&(this[t]=null,delete this[t])})}bindDataSource(e,t){const s=t?.initial??!0,r=e??this._data_source;typeof r!="string"||r.length===0||this._process_data&&(this._xd_bound_key===r&&this._xd_unsub||(this.unbindDataSource(),this._data_source=r,this._xd_bound_key=r,this._type??this.constructor.name,this._id,this._xd_unsub=k.on(r,async n=>{await this.onData(n.value)}),s&&k.has(r)&&this.onData(k.get(r))))}unbindDataSource(){this._xd_unsub?.(),this._xd_unsub=void 0,this._xd_bound_key=void 0}async dispose(){if(this.unbindDataSource(),this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._process_data=!1,this._process_frame=!1,this.removeAllEventListeners(),this.clearAttributes(["_cache_cmd_txt","_cache_jcmd","_nano_commands","_event_listeners_ids","_parent","_on","_once","_xem_options","_xporter"]),this._children&&this._children.forEach(e=>{typeof e.dispose=="function"&&e.dispose()}),this._children=[]}removeChild(e,t=!1){if(t)e.dispose();else{const s=this._children.indexOf(e);s>-1&&this._children.splice(s,1),e._parent=null}}addChild(e){this.append(e)}};E._xtype="object",E._skill=q;let A=E;class de{static getObjects(){return{object:A}}}const pe="engine:module:num-of-objects:",T={_id:"xmodule",_title:"XModule Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime module contract for object ownership, object packs, and executable underscore-prefixed commands.",_core_rules:["Every module must have a unique _name.","Modules expose commands through methods prefixed with underscore.","Command names remove the leading underscore and convert dashes to underscores internally.","Modules own and create registered XObject classes.","Do not mutate another module's objects directly."]};var p;const N=class N{constructor(e){K(this,p);this._loaded=!1,this._loading=!1,this._log_rules={createObject:!1,removeObject:!1},G(this,p,new re),this._name=e._name,this._id=u.guid()}static getOwnSkillBase(){return{...this._skill}}getOwnSkill(){const t=this.constructor._skill??T;return{...t,_exports:{...t._exports??{},_modules:[{_name:this._name,_scope:t._type==="server-module-api"?"server":"client",_description:t._description,_ops:this.getCommandSkills()}]}}}getSkillChain(){return[this.getOwnSkill()]}getObjectSkills(){const e=[],t=new Set;for(const s of Object.values(f(this,p).getObjectClasses())){if(typeof s.getOwnSkill!="function")continue;const r=s.getOwnSkill();r?._id&&(t.has(r._id)||(t.add(r._id),e.push(r)))}return e}getCommandSkills(){const e=Object.getPrototypeOf(this),s=this.constructor._ops??{};return Object.getOwnPropertyNames(e).filter(r=>r.startsWith("_")&&!r.startsWith("__")&&typeof this[r]=="function").map(r=>{const n=r.slice(1).replaceAll("_","-");return s[n]??{_name:n,_scope:"module",_description:`Runtime module command: ${n}`}})}async load(){if(!(this._loaded||this._loading)){this._loading=!0;try{await this.onLoad(),this._loaded=!0,h.log("Module "+this._name+" loaded")}finally{this._loading=!1}}}async onLoad(){}create(e){e._debug&&h.log("Creating object with data",e);let t;if(e.hasOwnProperty("_type")){e._debug&&h.log("Object type is",e._type,this.hasObject(e._type)?"found":"not found","in module",this._name);const s=String(e._type),r=f(this,p).getObjectClass(s);if(!r)throw`Xpell object '${s}' not found in module '${this._name}'`;typeof r=="function"&&r.hasOwnProperty("defaults")&&u.mergeDefaultsWithData(e,r.defaults),t=new r(e)}else t=new A(e);return f(this,p).addObject(t),e._children&&e._children.forEach(s=>{const r=this.create(s);t.append(r)}),t.onCreate(),t}remove(e){const t=f(this,p).getObject(e);if(!t)return;const s=[],r=n=>{n?._id&&(s.push(n._id),(n._children??[]).forEach(i=>r(i)))};r(t),typeof t.dispose=="function"&&t.dispose(),s.reverse().forEach(n=>f(this,p).removeObject(n))}_info(e){h.log("module info")}async run(e){if(e){let t=e.trim();t.startsWith(this._name)||(t=this._name+" "+t);let s=O.parse(t);return await this.execute(s)}else throw"Unable to parse Xpell Command"}async execute(e){if(!e||!e._op)throw new Error(`Invalid XCommand: missing _op (module: ${this._name})`);const t=e._object;if(t){const c=f(this,p).getObject(t);if(!c)throw new Error(`Module '${this._name}' cant find object id: ${t}`);return await c.execute(e)}const s=e._op,n="_"+(s.startsWith("_")&&s.length>1?s.slice(1):s).replaceAll("-","_"),i=this[n];if(typeof i=="function")return await i.call(this,e);throw new Error(`Module '${this._name}' cant find op: ${e._op}`)}async onFrame(e){const t=f(this,p)._objects,s=Object.keys(t);s.forEach(r=>{const n=t[r];n&&n.onFrame&&typeof n.onFrame=="function"&&n?.onFrame(e)}),m.set(pe+this._id,s.length,{source:"xmodule"})}get om(){return f(this,p)}get _object_manager(){return f(this,p)}getObject(e){return f(this,p).getObject(e)}hasObject(e){return f(this,p).hasObjectClass(e)}get _o(){return f(this,p)._objects}importObjectPack(e){f(this,p).registerObjects(e.getObjects())}importObjects(e){this.importObjectPack(e)}importObject(e,t){f(this,p).registerObject(e,t)}async _help(e){const t=e?._params?._op??e?._params?._command??"";return this.help(t)}help(e){return{module:this._name,usage:`${this._name} help`,ops:["help"],note:"No help() implemented for this module."}}};p=new WeakMap,N._skill=T,N._ops={help:{_name:"help",_scope:"module",_description:"Return module help or command-specific help."},info:{_name:"info",_scope:"module",_description:"Log basic module information."}};let M=N;const fe={_id:"xdata",_title:"XData Runtime State Contract",_version:"1.0.0",_active:!0,_type:"xdata-skill",_description:"Shared runtime state store used by Xpell modules and objects for reactive data binding.",_requires:["xmodule"],_core_rules:["Use XData for shared runtime state.","Use _data_source on objects to bind to an XData key.","Use $xdata.key references in generated payloads when a flow or command needs current state.","Do not use XData as hidden local component state.","XData keys should be explicit and stable."],_fields:{_data_source:"XData key used by XObject/XUIObject for reactive data binding.","$xdata.key":"Runtime payload reference to an XData value."}},X=class X extends M{constructor(){super({_name:X._name})}async _get(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return{_ok:!0,_result:m.get(s)}}async _set(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return t._debug&&x.log("XD SET",{key:s,value:t.value}),m.set(s,t.value,{source:t.source??"xd:set"}),{_ok:!0,_result:{key:s}}}async _patch(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");if(!u.is_plain_object(t.value))throw new Error("xd patch expects value as plain object");return m.patch(s,t.value,{source:t.source??"xd:patch"}),{_ok:!0,_result:{key:s}}}async _delete(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return m.delete(s,{source:t.source??"xd:delete"}),{_ok:!0,_result:{key:s}}}async _touch(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return m.touch(s,{source:t.source??"xd:touch"}),{_ok:!0,_result:{key:s}}}async _has(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return{_ok:!0,_result:m.has(s)}}async _get_path(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key"),r=u.ensure_string(t.path,"path"),n=m.get(s);return{_ok:!0,_result:u.get_path(n,r,t.fallback)}}async _log(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key"),r=m.get(s),n=u.read_optional_string(t.path,"path"),i=n?u.get_path(r,n,t.fallback):r;return x.log("XDATA LOG",{key:s,path:n,value:i}),{_ok:!0,_result:{key:s,path:n,value:i}}}};X._name="xd",X._skill=fe,X._ops={get:{_name:"get",_scope:"module",_description:"Get value from XData store.",_params:{key:"XData key."}},set:{_name:"set",_scope:"module",_description:"Set value in XData store.",_params:{key:"XData key.",value:"Value to store.",source:"Optional mutation source."}},patch:{_name:"patch",_scope:"module",_description:"Patch plain object into existing XData value.",_params:{key:"XData key.",value:"Plain object patch.",source:"Optional mutation source."}},delete:{_name:"delete",_scope:"module",_description:"Delete XData key.",_params:{key:"XData key.",source:"Optional mutation source."}},touch:{_name:"touch",_scope:"module",_description:"Trigger XData subscribers without changing value.",_params:{key:"XData key.",source:"Optional mutation source."}},has:{_name:"has",_scope:"module",_description:"Check if XData key exists.",_params:{key:"XData key."}},get_path:{_name:"get_path",_scope:"module",_description:"Get nested value from an XData value.",_params:{key:"XData key.",path:"Nested path inside the stored value.",fallback:"Optional fallback value."}}};let I=X;const me={_id:"xem",_title:"XEventManager Runtime Event Bus",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Global runtime event bus for decoupled communication between Xpell modules, objects, flows, and UI components.",_requires:["xmodule"],_core_rules:["Use XEM for decoupled runtime events.","Use explicit event names and explicit payload objects.","Do not use XEM as state storage.","Use XData for shared state and XEM for notifications/events.","Prefer _on/_once on objects for local event handlers."],_fields:{_on:"Object event handler map.",_once:"Object one-time event handler map.",event:"Event name to fire.",data:"Optional event payload."},_notes:["XEM is process-wide and listener order should not be assumed.","Event payloads should be JSON/data-only."]},S=class S extends M{constructor(){super({_name:S._name})}async _fire(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.event,"event"),r=t.data;t._debug&&x.log("xem fire 🔥 ",s,r),await D().fire(s,r)}};S._name="xem",S._skill=me,S._ops={fire:{_name:"fire",_scope:"module",_description:"Fire a global XEM event with optional payload data.",_params:{event:"Event name.",data:"Optional event payload.",_debug:"Optional debug log flag."},_example:{_module:"xem",_op:"fire",_params:{event:"user:login",data:{source:"login-button"}}}}};let P=S;class ge{static get(e,t,s){const n=(e?._params??e)?.[t];return n!==void 0?n:s}static has(e,t){return(e?._params??e)[t]!==void 0}static str(e,...t){const s=e?._params??e;for(const r of t){const n=s?.[r];if(n!=null)return String(n)}}static bool(e,t,s=!1){const r=e?._params??e,n=this.get(r,t,s);if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;if(typeof n=="string"){const i=n.toLowerCase();if(["1","true","yes","on"].includes(i))return!0;if(["0","false","no","off"].includes(i))return!1}return!!n}static int(e,t,s=0){const r=e?._params??e,n=this.get(r,t,s),i=parseInt(String(n),10);return Number.isFinite(i)?i:s}static json(e,t,s){const r=e?._params??e,n=this.get(r,t,s);if(n==null)return s;if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return s}return s}}class B extends Error{constructor(e,t,s){super(t),this.name="XError",this._code=e,this._level=s?._level??"error",this._meta=s?._meta,this._cause=s?._cause}toXData(){return{_code:this._code,_level:this._level,_meta:this._meta,_cause:this._cause,name:this.name,message:this.message}}toJSON(){return{...this.toXData(),stack:this.stack}}}class w{constructor(e){this._ok=!1,this._ts=Date.now(),this._pt=0,e&&this.setXData(e)}static create(e){return new w(e)}static ok(e){return new w({_ok:!0,_result:e})}static error(e){if(e instanceof B)return new w({_ok:!1,_result:e.toXData()});const t=new B("E_INTERNAL",e?.message??String(e),{_cause:e});return new w({_ok:!1,_result:t.toXData()})}stopProcessTimeCounter(){this._pt=Date.now()-this._ts}toXData(){return this.stopProcessTimeCounter(),{_ok:this._ok,_ts:this._ts,_pt:this._pt,_result:this._result}}toString(){return JSON.stringify(this.toXData())}setXData(e){e&&("_ok"in e&&(this._ok=!!e._ok),"_ts"in e&&typeof e._ts=="number"&&(this._ts=e._ts),"_pt"in e&&typeof e._pt=="number"&&(this._pt=e._pt),"_result"in e&&(this._result=e._result))}}class ye extends w{constructor(e){super(w.error(e).toXData())}}class be extends w{constructor(e){super({_ok:!0,_result:e})}}const ne="engine:frame-number",ie="engine:fps";class oe{constructor(e){this._log_rules={},this._modules={},this._schedule_frame=e?._schedule_frame??u.createDefaultScheduler(e?._target_fps),this._version="0.0.1",this._engine_id=u.guid(),this._frame_number=0,this._fps_calc=new ae,this.parser=O,this._modules={},h._enabled=!1,he(this)}set verbose(e){h._enabled=e}set _verbose(e){h._enabled=e}log(e,...t){h.log(e,...t)}async delay(e){return new Promise(t=>setTimeout(t,e))}addModule(e){return this._modules.hasOwnProperty(e._name)?(h.log("Module "+e._name+" already loaded"),!1):(this._modules[e._name]=e,!0)}loadModule(e){this.addModule(e)&&e.load()}loadModules(...e){e.forEach(t=>this.loadModule(t))}async loadModuleAsync(e){this.addModule(e)&&await e.load()}async loadModulesAsync(...e){for(const t of e)await this.loadModuleAsync(t)}info(){h.log(`Xpell information:
|
|
2
3
|
- Engine Id: `+this._engine_id+`
|
|
3
|
-
- Version `+this._version)}run(e){if(e?.length>2){let t=
|
|
4
|
+
- Version `+this._version)}run(e){if(e?.length>2){let t=O.parse(e);return this.execute(t)}else throw"Unable to parse Xpell command"}execute(e){if(e&&e._module&&this._modules[e._module])return this._modules[e._module].execute(e);throw"Xpell module "+e._module+" not loaded"}onFrame(){this._frame_number++;for(const t of Object.keys(this._modules)){const s=this._modules[t];s?.onFrame&&typeof s.onFrame=="function"&&s.onFrame(this._frame_number)}const e=this._fps_calc.calc();m.set(ne,this._frame_number,{source:"engine"}),m.set(ie,e,{source:"engine"}),m._compat_legacy_keys&&(m.set("frame-number",this._frame_number,{source:"engine:legacy"}),m.set("fps",e,{source:"engine:legacy"})),this._schedule_frame(()=>this.onFrame())}getModule(e){return this._modules[e]}start(){h.log("Loading Xpell core modules...[xd, xem]"),this.loadModule(new I),this.loadModule(new P),h.log("Starting Xpell"),this.onFrame()}getCoreSkills(){return[T,q]}getModuleSkills(){return Object.values(this._modules).flatMap(e=>typeof e.getSkillChain=="function"?e.getSkillChain():[])}getSkills(){return{_runtime:{_engine_id:this._engine_id,_version:this._version},_skills:this.getCoreSkills(),_modules:Object.values(this._modules).map(e=>({_name:e._name,_skills:typeof e.getSkillChain=="function"?e.getSkillChain():[],_objects:typeof e.getObjectSkills=="function"?e.getObjectSkills():[]}))}}}const z=new oe;exports.XCommand=F;exports.XD_FPS=ie;exports.XD_FRAME_NUMBER=ne;exports.XData=k;exports.XDataModule=I;exports.XError=B;exports.XEventManagerModule=P;exports.XLogger=h;exports.XModule=M;exports.XObject=A;exports.XObjectManager=re;exports.XObjectPack=de;exports.XParams=ge;exports.XParser=O;exports.XResponse=w;exports.XResponseError=ye;exports.XResponseOK=be;exports.XUtils=Z;exports.Xpell=z;exports.XpellEngine=oe;exports._XData=se;exports._XEventManager=ce;exports._XLogger=ee;exports._XUtils=Y;exports._x=z;exports._xd=m;exports._xlog=h;exports._xu=u;exports.createNanoCommandWithSkill=b;exports.default=z;exports.getXEventManager=D;exports.setXEventManager=_e;
|