@qontinui/ui-bridge 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/ai/index.d.mts +312 -155
  2. package/dist/ai/index.d.ts +312 -155
  3. package/dist/ai/index.js +2363 -67
  4. package/dist/ai/index.js.map +1 -1
  5. package/dist/ai/index.mjs +2328 -68
  6. package/dist/ai/index.mjs.map +1 -1
  7. package/dist/annotations/index.d.mts +218 -0
  8. package/dist/annotations/index.d.ts +218 -0
  9. package/dist/annotations/index.js +246 -0
  10. package/dist/annotations/index.js.map +1 -0
  11. package/dist/annotations/index.mjs +241 -0
  12. package/dist/annotations/index.mjs.map +1 -0
  13. package/dist/assertions-BSR3afVr.d.ts +161 -0
  14. package/dist/assertions-CTw1hfOx.d.mts +161 -0
  15. package/dist/babel-plugin/index.js +504 -0
  16. package/dist/babel-plugin/index.js.map +1 -0
  17. package/dist/babel-plugin/index.mjs +488 -0
  18. package/dist/babel-plugin/index.mjs.map +1 -0
  19. package/dist/browser-capture-Bms60T6f.d.mts +47 -0
  20. package/dist/browser-capture-CsTU29mb.d.ts +47 -0
  21. package/dist/control/index.d.mts +26 -7
  22. package/dist/control/index.d.ts +26 -7
  23. package/dist/control/index.js +276 -48
  24. package/dist/control/index.js.map +1 -1
  25. package/dist/control/index.mjs +276 -48
  26. package/dist/control/index.mjs.map +1 -1
  27. package/dist/core/index.d.mts +115 -44
  28. package/dist/core/index.d.ts +115 -44
  29. package/dist/core/index.js +0 -1560
  30. package/dist/core/index.js.map +1 -1
  31. package/dist/core/index.mjs +1 -1549
  32. package/dist/core/index.mjs.map +1 -1
  33. package/dist/debug/index.d.mts +5 -3
  34. package/dist/debug/index.d.ts +5 -3
  35. package/dist/debug/index.js +925 -1
  36. package/dist/debug/index.js.map +1 -1
  37. package/dist/debug/index.mjs +924 -2
  38. package/dist/debug/index.mjs.map +1 -1
  39. package/dist/index.d.mts +13 -9
  40. package/dist/index.d.ts +13 -9
  41. package/dist/index.js +8310 -3777
  42. package/dist/index.js.map +1 -1
  43. package/dist/index.mjs +8246 -3766
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/{metrics-NC3csD0R.d.mts → metrics-DuA2qIIz.d.mts} +2 -2
  46. package/dist/{metrics-C9XRi_mL.d.ts → metrics-KFAAKNEB.d.ts} +2 -2
  47. package/dist/native/control/index.js +448 -0
  48. package/dist/native/control/index.js.map +1 -0
  49. package/dist/native/control/index.mjs +445 -0
  50. package/dist/native/control/index.mjs.map +1 -0
  51. package/dist/native/core/index.js +486 -0
  52. package/dist/native/core/index.js.map +1 -0
  53. package/dist/native/core/index.mjs +475 -0
  54. package/dist/native/core/index.mjs.map +1 -0
  55. package/dist/native/debug/index.js +408 -0
  56. package/dist/native/debug/index.js.map +1 -0
  57. package/dist/native/debug/index.mjs +406 -0
  58. package/dist/native/debug/index.mjs.map +1 -0
  59. package/dist/native/index.js +2232 -0
  60. package/dist/native/index.js.map +1 -0
  61. package/dist/native/index.mjs +2204 -0
  62. package/dist/native/index.mjs.map +1 -0
  63. package/dist/native/react/index.js +1377 -0
  64. package/dist/native/react/index.js.map +1 -0
  65. package/dist/native/react/index.mjs +1365 -0
  66. package/dist/native/react/index.mjs.map +1 -0
  67. package/dist/native/server/index.js +440 -0
  68. package/dist/native/server/index.js.map +1 -0
  69. package/dist/native/server/index.mjs +435 -0
  70. package/dist/native/server/index.mjs.map +1 -0
  71. package/dist/react/index.d.mts +121 -9
  72. package/dist/react/index.d.ts +121 -9
  73. package/dist/react/index.js +2239 -91
  74. package/dist/react/index.js.map +1 -1
  75. package/dist/react/index.mjs +2239 -92
  76. package/dist/react/index.mjs.map +1 -1
  77. package/dist/{registry-CIEDjbQ9.d.ts → registry-C6dDtn1v.d.ts} +34 -15
  78. package/dist/{registry-SsSDq46X.d.mts → registry-POtcxnal.d.mts} +34 -15
  79. package/dist/render-log/index.d.mts +1 -1
  80. package/dist/render-log/index.d.ts +1 -1
  81. package/dist/server/express.d.mts +37 -0
  82. package/dist/server/express.d.ts +37 -0
  83. package/dist/server/express.js +298 -0
  84. package/dist/server/express.js.map +1 -0
  85. package/dist/server/express.mjs +294 -0
  86. package/dist/server/express.mjs.map +1 -0
  87. package/dist/server/handlers.d.mts +124 -0
  88. package/dist/server/handlers.d.ts +124 -0
  89. package/dist/server/handlers.js +7183 -0
  90. package/dist/server/handlers.js.map +1 -0
  91. package/dist/server/handlers.mjs +7180 -0
  92. package/dist/server/handlers.mjs.map +1 -0
  93. package/dist/server/index.d.mts +12 -0
  94. package/dist/server/index.d.ts +12 -0
  95. package/dist/server/index.js +8384 -0
  96. package/dist/server/index.js.map +1 -0
  97. package/dist/server/index.mjs +8369 -0
  98. package/dist/server/index.mjs.map +1 -0
  99. package/dist/server/nextjs.d.mts +128 -0
  100. package/dist/server/nextjs.d.ts +128 -0
  101. package/dist/server/nextjs.js +390 -0
  102. package/dist/server/nextjs.js.map +1 -0
  103. package/dist/server/nextjs.mjs +385 -0
  104. package/dist/server/nextjs.mjs.map +1 -0
  105. package/dist/server/standalone.d.mts +7 -0
  106. package/dist/server/standalone.d.ts +7 -0
  107. package/dist/server/standalone.js +845 -0
  108. package/dist/server/standalone.js.map +1 -0
  109. package/dist/server/standalone.mjs +841 -0
  110. package/dist/server/standalone.mjs.map +1 -0
  111. package/dist/specs/index.d.mts +365 -0
  112. package/dist/specs/index.d.ts +365 -0
  113. package/dist/specs/index.js +2809 -0
  114. package/dist/specs/index.js.map +1 -0
  115. package/dist/specs/index.mjs +2786 -0
  116. package/dist/specs/index.mjs.map +1 -0
  117. package/dist/standalone-B6GLIEmR.d.ts +216 -0
  118. package/dist/standalone-CjdYqj3P.d.mts +216 -0
  119. package/dist/swc-plugin/index.d.mts +79 -0
  120. package/dist/swc-plugin/index.d.ts +79 -0
  121. package/dist/swc-plugin/index.js +15 -0
  122. package/dist/swc-plugin/index.js.map +1 -0
  123. package/dist/swc-plugin/index.mjs +9 -0
  124. package/dist/swc-plugin/index.mjs.map +1 -0
  125. package/dist/types-B2EfvEaq.d.ts +236 -0
  126. package/dist/{types-Dr6tH-bm.d.mts → types-C7gVYRnF.d.ts} +72 -2
  127. package/dist/{types-oCTrRxSw.d.ts → types-CJGrBEhC.d.mts} +72 -2
  128. package/dist/types-CebMQj76.d.ts +1275 -0
  129. package/dist/types-D_ypYl3T.d.mts +1275 -0
  130. package/dist/types-UBtp7R0u.d.mts +132 -0
  131. package/dist/types-UBtp7R0u.d.ts +132 -0
  132. package/dist/types-gO696T_t.d.mts +236 -0
  133. package/dist/{types-CPMbN_Iw.d.mts → types-suaYwWWg.d.mts} +519 -152
  134. package/dist/{types-CPMbN_Iw.d.ts → types-suaYwWWg.d.ts} +519 -152
  135. package/package.json +123 -4
  136. package/swc-plugin-wasm/ui_bridge_swc_plugin.wasm +0 -0
  137. package/dist/types-BvCfFuEV.d.ts +0 -534
  138. package/dist/types-CFT3Dnx4.d.mts +0 -534
  139. package/dist/websocket-client-CX4QJesI.d.ts +0 -124
  140. package/dist/websocket-client-C_Na0OSp.d.mts +0 -124
@@ -1,1551 +1,3 @@
1
- // src/core/element-identifier.ts
2
- var ID_ATTRIBUTES = ["data-ui-id", "data-testid", "data-awas-element", "id"];
3
- function generateXPath(element) {
4
- if (element.id) {
5
- return `//*[@id="${element.id}"]`;
6
- }
7
- const parts = [];
8
- let current = element;
9
- while (current && current.nodeType === Node.ELEMENT_NODE) {
10
- let selector = current.nodeName.toLowerCase();
11
- const uiId = current.getAttribute("data-ui-id");
12
- if (uiId) {
13
- selector += `[@data-ui-id="${uiId}"]`;
14
- parts.unshift(selector);
15
- break;
16
- }
17
- const testId = current.getAttribute("data-testid");
18
- if (testId) {
19
- selector += `[@data-testid="${testId}"]`;
20
- parts.unshift(selector);
21
- break;
22
- }
23
- const id = current.id;
24
- if (id) {
25
- selector += `[@id="${id}"]`;
26
- parts.unshift(selector);
27
- break;
28
- }
29
- const parentEl = current.parentElement;
30
- if (parentEl) {
31
- const currentEl = current;
32
- const siblings = Array.from(parentEl.children).filter(
33
- (child) => child.nodeName === currentEl.nodeName
34
- );
35
- if (siblings.length > 1) {
36
- const index = siblings.indexOf(currentEl) + 1;
37
- selector += `[${index}]`;
38
- }
39
- }
40
- parts.unshift(selector);
41
- current = parentEl;
42
- }
43
- return "/" + parts.join("/");
44
- }
45
- function generateCSSSelector(element) {
46
- const uiId = element.getAttribute("data-ui-id");
47
- if (uiId) {
48
- return `[data-ui-id="${uiId}"]`;
49
- }
50
- const testId = element.getAttribute("data-testid");
51
- if (testId) {
52
- return `[data-testid="${testId}"]`;
53
- }
54
- const awasId = element.getAttribute("data-awas-element");
55
- if (awasId) {
56
- return `[data-awas-element="${awasId}"]`;
57
- }
58
- if (element.id) {
59
- return `#${CSS.escape(element.id)}`;
60
- }
61
- const path = [];
62
- let current = element;
63
- while (current && current.nodeType === Node.ELEMENT_NODE) {
64
- let selector = current.nodeName.toLowerCase();
65
- const parentUiId = current.getAttribute("data-ui-id");
66
- if (parentUiId && current !== element) {
67
- path.unshift(`[data-ui-id="${parentUiId}"]`);
68
- break;
69
- }
70
- const parentTestId = current.getAttribute("data-testid");
71
- if (parentTestId && current !== element) {
72
- path.unshift(`[data-testid="${parentTestId}"]`);
73
- break;
74
- }
75
- if (current.id) {
76
- path.unshift(`#${CSS.escape(current.id)}`);
77
- break;
78
- }
79
- const parentEl = current.parentElement;
80
- if (parentEl) {
81
- const currentEl = current;
82
- const siblings = Array.from(parentEl.children);
83
- const sameTagSiblings = siblings.filter(
84
- (s) => s.nodeName === currentEl.nodeName
85
- );
86
- if (sameTagSiblings.length > 1) {
87
- const index = siblings.indexOf(currentEl) + 1;
88
- selector += `:nth-child(${index})`;
89
- }
90
- }
91
- path.unshift(selector);
92
- current = current.parentElement;
93
- }
94
- return path.join(" > ");
95
- }
96
- function getBestIdentifier(element) {
97
- const uiId = element.getAttribute("data-ui-id");
98
- if (uiId) return uiId;
99
- const testId = element.getAttribute("data-testid");
100
- if (testId) return testId;
101
- const awasId = element.getAttribute("data-awas-element");
102
- if (awasId) return awasId;
103
- if (element.id) return element.id;
104
- return generateCSSSelector(element);
105
- }
106
- function createElementIdentifier(element) {
107
- return {
108
- uiId: element.getAttribute("data-ui-id") || void 0,
109
- testId: element.getAttribute("data-testid") || void 0,
110
- awasId: element.getAttribute("data-awas-element") || void 0,
111
- htmlId: element.id || void 0,
112
- xpath: generateXPath(element),
113
- selector: generateCSSSelector(element)
114
- };
115
- }
116
- function findElementByIdentifier(identifier, root = document) {
117
- if (typeof identifier === "string") {
118
- const byUiId = root.querySelector(`[data-ui-id="${identifier}"]`);
119
- if (byUiId) return byUiId;
120
- const byTestId = root.querySelector(`[data-testid="${identifier}"]`);
121
- if (byTestId) return byTestId;
122
- const byAwasId = root.querySelector(`[data-awas-element="${identifier}"]`);
123
- if (byAwasId) return byAwasId;
124
- const byId = root.querySelector(`#${CSS.escape(identifier)}`);
125
- if (byId) return byId;
126
- try {
127
- const bySelector = root.querySelector(identifier);
128
- if (bySelector) return bySelector;
129
- } catch {
130
- }
131
- try {
132
- const result = document.evaluate(
133
- identifier,
134
- root,
135
- null,
136
- XPathResult.FIRST_ORDERED_NODE_TYPE,
137
- null
138
- );
139
- if (result.singleNodeValue instanceof HTMLElement) {
140
- return result.singleNodeValue;
141
- }
142
- } catch {
143
- }
144
- return null;
145
- }
146
- if (identifier.uiId) {
147
- const el = root.querySelector(`[data-ui-id="${identifier.uiId}"]`);
148
- if (el) return el;
149
- }
150
- if (identifier.testId) {
151
- const el = root.querySelector(`[data-testid="${identifier.testId}"]`);
152
- if (el) return el;
153
- }
154
- if (identifier.awasId) {
155
- const el = root.querySelector(`[data-awas-element="${identifier.awasId}"]`);
156
- if (el) return el;
157
- }
158
- if (identifier.htmlId) {
159
- const el = root.querySelector(`#${CSS.escape(identifier.htmlId)}`);
160
- if (el) return el;
161
- }
162
- if (identifier.selector) {
163
- try {
164
- const el = root.querySelector(identifier.selector);
165
- if (el) return el;
166
- } catch {
167
- }
168
- }
169
- if (identifier.xpath) {
170
- try {
171
- const result = document.evaluate(
172
- identifier.xpath,
173
- root,
174
- null,
175
- XPathResult.FIRST_ORDERED_NODE_TYPE,
176
- null
177
- );
178
- if (result.singleNodeValue instanceof HTMLElement) {
179
- return result.singleNodeValue;
180
- }
181
- } catch {
182
- }
183
- }
184
- return null;
185
- }
186
- function findAllElementsByIdentifier(pattern, root = document) {
187
- const results = [];
188
- try {
189
- const elements = root.querySelectorAll(pattern);
190
- results.push(...Array.from(elements));
191
- if (results.length > 0) return results;
192
- } catch {
193
- }
194
- const partials = [
195
- `[data-ui-id*="${pattern}"]`,
196
- `[data-testid*="${pattern}"]`,
197
- `[data-awas-element*="${pattern}"]`,
198
- `[id*="${pattern}"]`
199
- ];
200
- for (const selector of partials) {
201
- try {
202
- const elements = root.querySelectorAll(selector);
203
- for (const el of elements) {
204
- if (!results.includes(el)) {
205
- results.push(el);
206
- }
207
- }
208
- } catch {
209
- }
210
- }
211
- return results;
212
- }
213
- function elementMatchesIdentifier(element, identifier) {
214
- if (typeof identifier === "string") {
215
- return element.getAttribute("data-ui-id") === identifier || element.getAttribute("data-testid") === identifier || element.getAttribute("data-awas-element") === identifier || element.id === identifier || element.matches(identifier);
216
- }
217
- return identifier.uiId && element.getAttribute("data-ui-id") === identifier.uiId || identifier.testId && element.getAttribute("data-testid") === identifier.testId || identifier.awasId && element.getAttribute("data-awas-element") === identifier.awasId || identifier.htmlId && element.id === identifier.htmlId || false;
218
- }
219
-
220
- // src/ai/fuzzy-matcher.ts
221
- var DEFAULT_FUZZY_CONFIG = {
222
- threshold: 0.7,
223
- levenshteinWeight: 0.3,
224
- jaroWinklerWeight: 0.4,
225
- ngramWeight: 0.3,
226
- ngramSize: 2,
227
- caseSensitive: false,
228
- ignoreWhitespace: true
229
- };
230
- function levenshteinDistance(s1, s2) {
231
- const len1 = s1.length;
232
- const len2 = s2.length;
233
- const matrix = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
234
- for (let i = 0; i <= len1; i++) matrix[i][0] = i;
235
- for (let j = 0; j <= len2; j++) matrix[0][j] = j;
236
- for (let i = 1; i <= len1; i++) {
237
- for (let j = 1; j <= len2; j++) {
238
- const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
239
- matrix[i][j] = Math.min(
240
- matrix[i - 1][j] + 1,
241
- // deletion
242
- matrix[i][j - 1] + 1,
243
- // insertion
244
- matrix[i - 1][j - 1] + cost
245
- // substitution
246
- );
247
- }
248
- }
249
- return matrix[len1][len2];
250
- }
251
- function levenshteinSimilarity(s1, s2) {
252
- if (s1.length === 0 && s2.length === 0) return 1;
253
- if (s1.length === 0 || s2.length === 0) return 0;
254
- const distance = levenshteinDistance(s1, s2);
255
- const maxLength = Math.max(s1.length, s2.length);
256
- return 1 - distance / maxLength;
257
- }
258
- function jaroSimilarity(s1, s2) {
259
- if (s1.length === 0 && s2.length === 0) return 1;
260
- if (s1.length === 0 || s2.length === 0) return 0;
261
- const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
262
- const s1Matches = new Array(s1.length).fill(false);
263
- const s2Matches = new Array(s2.length).fill(false);
264
- let matches = 0;
265
- let transpositions = 0;
266
- for (let i = 0; i < s1.length; i++) {
267
- const start = Math.max(0, i - matchDistance);
268
- const end = Math.min(i + matchDistance + 1, s2.length);
269
- for (let j = start; j < end; j++) {
270
- if (s2Matches[j] || s1[i] !== s2[j]) continue;
271
- s1Matches[i] = true;
272
- s2Matches[j] = true;
273
- matches++;
274
- break;
275
- }
276
- }
277
- if (matches === 0) return 0;
278
- let k = 0;
279
- for (let i = 0; i < s1.length; i++) {
280
- if (!s1Matches[i]) continue;
281
- while (!s2Matches[k]) k++;
282
- if (s1[i] !== s2[k]) transpositions++;
283
- k++;
284
- }
285
- return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
286
- }
287
- function jaroWinklerSimilarity(s1, s2, prefixScale = 0.1) {
288
- const jaroSim = jaroSimilarity(s1, s2);
289
- let prefixLength = 0;
290
- const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
291
- for (let i = 0; i < maxPrefix; i++) {
292
- if (s1[i] === s2[i]) {
293
- prefixLength++;
294
- } else {
295
- break;
296
- }
297
- }
298
- return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
299
- }
300
- function generateNgrams(s, n) {
301
- const ngrams = /* @__PURE__ */ new Set();
302
- if (s.length < n) {
303
- ngrams.add(s);
304
- return ngrams;
305
- }
306
- for (let i = 0; i <= s.length - n; i++) {
307
- ngrams.add(s.substring(i, i + n));
308
- }
309
- return ngrams;
310
- }
311
- function ngramSimilarity(s1, s2, n = 2) {
312
- if (s1.length === 0 && s2.length === 0) return 1;
313
- if (s1.length === 0 || s2.length === 0) return 0;
314
- const ngrams1 = generateNgrams(s1, n);
315
- const ngrams2 = generateNgrams(s2, n);
316
- let intersection = 0;
317
- for (const ngram of ngrams1) {
318
- if (ngrams2.has(ngram)) {
319
- intersection++;
320
- }
321
- }
322
- const union = ngrams1.size + ngrams2.size - intersection;
323
- return union === 0 ? 0 : intersection / union;
324
- }
325
- function normalizeString(s, config = {}) {
326
- let normalized = s;
327
- if (!config.caseSensitive) {
328
- normalized = normalized.toLowerCase();
329
- }
330
- if (config.ignoreWhitespace !== false) {
331
- normalized = normalized.replace(/\s+/g, " ").trim();
332
- }
333
- return normalized;
334
- }
335
- function fuzzyMatch(source, target, config = {}) {
336
- const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
337
- const normalizedSource = normalizeString(source, finalConfig);
338
- const normalizedTarget = normalizeString(target, finalConfig);
339
- const levenshteinScore = levenshteinSimilarity(normalizedSource, normalizedTarget);
340
- const jaroWinklerScore = jaroWinklerSimilarity(normalizedSource, normalizedTarget);
341
- const ngramScore = ngramSimilarity(normalizedSource, normalizedTarget, finalConfig.ngramSize);
342
- const similarity = levenshteinScore * finalConfig.levenshteinWeight + jaroWinklerScore * finalConfig.jaroWinklerWeight + ngramScore * finalConfig.ngramWeight;
343
- return {
344
- similarity,
345
- isMatch: similarity >= finalConfig.threshold,
346
- scores: {
347
- levenshtein: levenshteinScore,
348
- jaroWinkler: jaroWinklerScore,
349
- ngram: ngramScore
350
- },
351
- normalizedSource,
352
- normalizedTarget
353
- };
354
- }
355
- function tokenize(s) {
356
- return s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase().split(" ").filter((token) => token.length > 0);
357
- }
358
-
359
- // src/ai/alias-generator.ts
360
- var DEFAULT_ALIAS_CONFIG = {
361
- includeText: true,
362
- includeAriaLabel: true,
363
- includePlaceholder: true,
364
- includeTitle: true,
365
- includeSynonyms: true,
366
- maxAliases: 20,
367
- minLength: 2,
368
- maxLength: 50
369
- };
370
- var SYNONYMS = {
371
- // Submit-related
372
- submit: ["send", "go", "confirm", "ok", "apply", "save", "done", "finish"],
373
- send: ["submit", "deliver", "post"],
374
- save: ["submit", "store", "keep", "apply"],
375
- cancel: ["close", "dismiss", "abort", "back", "exit", "quit", "nevermind"],
376
- close: ["cancel", "dismiss", "exit", "x"],
377
- delete: ["remove", "trash", "erase", "clear", "destroy"],
378
- remove: ["delete", "clear", "discard"],
379
- edit: ["modify", "change", "update", "alter"],
380
- update: ["edit", "modify", "save", "refresh"],
381
- add: ["create", "new", "plus", "insert"],
382
- create: ["add", "new", "make"],
383
- search: ["find", "lookup", "query", "filter"],
384
- find: ["search", "locate", "lookup"],
385
- login: ["signin", "sign in", "log in", "authenticate", "enter"],
386
- logout: ["signout", "sign out", "log out", "exit"],
387
- register: ["signup", "sign up", "join", "create account"],
388
- next: ["continue", "forward", "proceed", "advance"],
389
- previous: ["back", "backward", "return", "prior"],
390
- back: ["previous", "return", "backward"],
391
- start: ["begin", "launch", "initiate", "run", "execute"],
392
- stop: ["end", "halt", "pause", "terminate"],
393
- enable: ["activate", "turn on", "switch on"],
394
- disable: ["deactivate", "turn off", "switch off"],
395
- show: ["display", "reveal", "view", "open"],
396
- hide: ["conceal", "collapse", "close"],
397
- expand: ["open", "show", "unfold", "reveal"],
398
- collapse: ["close", "hide", "fold", "minimize"],
399
- yes: ["ok", "confirm", "agree", "accept"],
400
- no: ["cancel", "decline", "reject", "deny"],
401
- help: ["support", "assistance", "info", "information", "faq"],
402
- settings: ["preferences", "options", "config", "configuration"],
403
- profile: ["account", "user", "me"],
404
- download: ["export", "save", "get"],
405
- upload: ["import", "load", "attach"],
406
- refresh: ["reload", "update", "sync"],
407
- copy: ["duplicate", "clone"],
408
- paste: ["insert"],
409
- select: ["choose", "pick"],
410
- toggle: ["switch", "flip"],
411
- // Form fields
412
- email: ["e-mail", "mail"],
413
- password: ["pass", "pwd", "secret"],
414
- username: ["user", "login", "account", "name"],
415
- firstname: ["first name", "given name", "forename"],
416
- lastname: ["last name", "surname", "family name"],
417
- fullname: ["full name", "name", "complete name"],
418
- phone: ["telephone", "tel", "mobile", "cell"],
419
- address: ["location", "street"],
420
- city: ["town"],
421
- country: ["nation"],
422
- zip: ["zipcode", "postal", "postal code", "postcode"],
423
- // Navigation
424
- home: ["main", "start", "dashboard"],
425
- menu: ["navigation", "nav"],
426
- sidebar: ["side bar", "side panel", "side menu"]
427
- };
428
- var ELEMENT_ACTION_WORDS = {
429
- button: ["button", "btn", "click"],
430
- input: ["input", "field", "textbox", "box"],
431
- textarea: ["textarea", "text area", "text field", "multiline"],
432
- select: ["select", "dropdown", "combo", "picker", "chooser"],
433
- checkbox: ["checkbox", "check", "tick"],
434
- radio: ["radio", "option", "choice"],
435
- link: ["link", "anchor", "href"],
436
- form: ["form"],
437
- menu: ["menu"],
438
- menuitem: ["menu item", "option"],
439
- tab: ["tab"],
440
- dialog: ["dialog", "modal", "popup"],
441
- switch: ["switch", "toggle"],
442
- slider: ["slider", "range"]
443
- };
444
- function normalizeAlias(text) {
445
- return text.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
446
- }
447
- function extractWords(text) {
448
- const tokens = tokenize(text);
449
- return tokens.filter((t) => t.length >= 2);
450
- }
451
- function generateTextAliases(text, config) {
452
- if (!text || !config.includeText) return [];
453
- const aliases = [];
454
- const normalized = normalizeAlias(text);
455
- if (normalized.length >= config.minLength && normalized.length <= config.maxLength) {
456
- aliases.push(normalized);
457
- }
458
- const words = extractWords(text);
459
- for (const word of words) {
460
- if (word.length >= config.minLength) {
461
- aliases.push(word);
462
- }
463
- }
464
- if (words.length >= 2 && words.length <= 4) {
465
- const twoWords = words.slice(0, 2).join(" ");
466
- if (twoWords.length <= config.maxLength) {
467
- aliases.push(twoWords);
468
- }
469
- if (words.length > 2) {
470
- const lastTwo = words.slice(-2).join(" ");
471
- if (lastTwo.length <= config.maxLength) {
472
- aliases.push(lastTwo);
473
- }
474
- }
475
- }
476
- return aliases;
477
- }
478
- function generateSynonyms(aliases, config) {
479
- if (!config.includeSynonyms) return [];
480
- const synonyms = [];
481
- for (const alias of aliases) {
482
- const words = alias.toLowerCase().split(/\s+/);
483
- for (const word of words) {
484
- if (SYNONYMS[word]) {
485
- for (const synonym of SYNONYMS[word]) {
486
- const newAlias = alias.toLowerCase().replace(word, synonym);
487
- if (newAlias !== alias.toLowerCase()) {
488
- synonyms.push(newAlias);
489
- }
490
- if (synonym.length >= config.minLength) {
491
- synonyms.push(synonym);
492
- }
493
- }
494
- }
495
- }
496
- }
497
- return synonyms;
498
- }
499
- function generateTypeAliases(elementType) {
500
- const type = elementType.toLowerCase();
501
- return ELEMENT_ACTION_WORDS[type] || [type];
502
- }
503
- function generateAliases(input, config = {}) {
504
- const finalConfig = { ...DEFAULT_ALIAS_CONFIG, ...config };
505
- const aliasSet = /* @__PURE__ */ new Set();
506
- const addAlias = (alias) => {
507
- const normalized = normalizeAlias(alias);
508
- if (normalized.length >= finalConfig.minLength && normalized.length <= finalConfig.maxLength) {
509
- aliasSet.add(normalized);
510
- }
511
- };
512
- const addAliases = (aliases2) => {
513
- for (const alias of aliases2) {
514
- addAlias(alias);
515
- }
516
- };
517
- if (finalConfig.includeText && input.textContent) {
518
- addAliases(generateTextAliases(input.textContent, finalConfig));
519
- }
520
- if (finalConfig.includeAriaLabel && input.ariaLabel) {
521
- addAliases(generateTextAliases(input.ariaLabel, finalConfig));
522
- }
523
- if (finalConfig.includeAriaLabel && input.ariaLabelledBy) {
524
- addAliases(generateTextAliases(input.ariaLabelledBy, finalConfig));
525
- }
526
- if (finalConfig.includePlaceholder && input.placeholder) {
527
- addAliases(generateTextAliases(input.placeholder, finalConfig));
528
- }
529
- if (finalConfig.includeTitle && input.title) {
530
- addAliases(generateTextAliases(input.title, finalConfig));
531
- }
532
- if (input.labelText) {
533
- addAliases(generateTextAliases(input.labelText, finalConfig));
534
- }
535
- if (input.id) {
536
- addAliases(extractWords(input.id));
537
- }
538
- if (input.name) {
539
- addAliases(extractWords(input.name));
540
- }
541
- if (input.value && (input.elementType === "button" || input.inputType === "submit" || input.inputType === "button")) {
542
- addAliases(generateTextAliases(input.value, finalConfig));
543
- }
544
- if (input.elementType) {
545
- addAliases(generateTypeAliases(input.elementType));
546
- }
547
- if (input.inputType) {
548
- addAlias(input.inputType);
549
- if (input.inputType === "email") {
550
- addAliases(["email", "e-mail", "email address"]);
551
- } else if (input.inputType === "password") {
552
- addAliases(["password", "pass", "pwd"]);
553
- } else if (input.inputType === "tel") {
554
- addAliases(["phone", "telephone", "mobile"]);
555
- } else if (input.inputType === "url") {
556
- addAliases(["url", "website", "link", "address"]);
557
- } else if (input.inputType === "search") {
558
- addAliases(["search", "find", "query"]);
559
- }
560
- }
561
- if (finalConfig.includeSynonyms) {
562
- const currentAliases = Array.from(aliasSet);
563
- addAliases(generateSynonyms(currentAliases, finalConfig));
564
- }
565
- let aliases = Array.from(aliasSet);
566
- aliases.sort((a, b) => a.length - b.length);
567
- if (aliases.length > finalConfig.maxAliases) {
568
- aliases = aliases.slice(0, finalConfig.maxAliases);
569
- }
570
- return aliases;
571
- }
572
- function generateDescription(input) {
573
- const parts = [];
574
- let name = input.ariaLabel || input.labelText || input.textContent || input.placeholder || input.title || input.id || input.name;
575
- if (name) {
576
- name = name.trim();
577
- if (name.length > 30) {
578
- name = name.substring(0, 27) + "...";
579
- }
580
- parts.push(`"${name}"`);
581
- }
582
- const typeWords = ELEMENT_ACTION_WORDS[input.elementType || ""] || [input.elementType || "element"];
583
- parts.push(typeWords[0]);
584
- if (input.inputType && input.inputType !== "text") {
585
- parts.push(`(${input.inputType})`);
586
- }
587
- return parts.join(" ");
588
- }
589
-
590
- // src/core/registry.ts
591
- function getElementState(element) {
592
- const rect = element.getBoundingClientRect();
593
- const computedStyle = window.getComputedStyle(element);
594
- const state = {
595
- visible: isElementVisible(element, rect, computedStyle),
596
- enabled: !isElementDisabled(element),
597
- focused: document.activeElement === element,
598
- rect: {
599
- x: rect.x,
600
- y: rect.y,
601
- width: rect.width,
602
- height: rect.height,
603
- top: rect.top,
604
- right: rect.right,
605
- bottom: rect.bottom,
606
- left: rect.left
607
- },
608
- textContent: element.textContent?.trim() || void 0,
609
- computedStyles: {
610
- display: computedStyle.display,
611
- visibility: computedStyle.visibility,
612
- opacity: computedStyle.opacity,
613
- pointerEvents: computedStyle.pointerEvents
614
- }
615
- };
616
- if (element instanceof HTMLInputElement) {
617
- state.value = element.value;
618
- if (element.type === "checkbox" || element.type === "radio") {
619
- state.checked = element.checked;
620
- }
621
- } else if (element instanceof HTMLTextAreaElement) {
622
- state.value = element.value;
623
- } else if (element instanceof HTMLSelectElement) {
624
- state.value = element.value;
625
- state.selectedOptions = Array.from(element.selectedOptions).map((opt) => opt.value);
626
- }
627
- return state;
628
- }
629
- function isElementVisible(element, rect, style) {
630
- if (rect.width === 0 || rect.height === 0) return false;
631
- if (style.display === "none") return false;
632
- if (style.visibility === "hidden") return false;
633
- if (parseFloat(style.opacity) === 0) return false;
634
- const inViewport = rect.top < window.innerHeight && rect.bottom > 0 && rect.left < window.innerWidth && rect.right > 0;
635
- return inViewport;
636
- }
637
- function isElementDisabled(element) {
638
- if ("disabled" in element && element.disabled) {
639
- return true;
640
- }
641
- if (element.getAttribute("aria-disabled") === "true") {
642
- return true;
643
- }
644
- return false;
645
- }
646
- function inferActions(type) {
647
- const baseActions = ["focus", "blur", "hover"];
648
- switch (type) {
649
- case "button":
650
- return [...baseActions, "click", "doubleClick", "rightClick"];
651
- case "input":
652
- return [...baseActions, "click", "type", "clear"];
653
- case "textarea":
654
- return [...baseActions, "click", "type", "clear"];
655
- case "select":
656
- return [...baseActions, "click", "select"];
657
- case "checkbox":
658
- return [...baseActions, "click", "check", "uncheck", "toggle"];
659
- case "radio":
660
- return [...baseActions, "click", "check"];
661
- case "link":
662
- return [...baseActions, "click"];
663
- case "form":
664
- return ["focus", "blur"];
665
- case "menu":
666
- case "menuitem":
667
- return [...baseActions, "click"];
668
- case "tab":
669
- return [...baseActions, "click"];
670
- case "dialog":
671
- return ["focus", "blur"];
672
- case "custom":
673
- default:
674
- return [...baseActions, "click"];
675
- }
676
- }
677
- function inferElementType(element) {
678
- const tagName = element.tagName.toLowerCase();
679
- const role = element.getAttribute("role");
680
- if (role) {
681
- switch (role) {
682
- case "button":
683
- return "button";
684
- case "textbox":
685
- return "input";
686
- case "checkbox":
687
- return "checkbox";
688
- case "radio":
689
- return "radio";
690
- case "link":
691
- return "link";
692
- case "listbox":
693
- case "combobox":
694
- return "select";
695
- case "menu":
696
- return "menu";
697
- case "menuitem":
698
- return "menuitem";
699
- case "tab":
700
- return "tab";
701
- case "dialog":
702
- return "dialog";
703
- }
704
- }
705
- switch (tagName) {
706
- case "button":
707
- return "button";
708
- case "input": {
709
- const inputType = element.type;
710
- if (inputType === "checkbox") return "checkbox";
711
- if (inputType === "radio") return "radio";
712
- if (inputType === "submit" || inputType === "button") return "button";
713
- return "input";
714
- }
715
- case "textarea":
716
- return "textarea";
717
- case "select":
718
- return "select";
719
- case "a":
720
- return "link";
721
- case "form":
722
- return "form";
723
- default:
724
- return "custom";
725
- }
726
- }
727
- var UIBridgeRegistry = class {
728
- constructor(options = {}) {
729
- this.elements = /* @__PURE__ */ new Map();
730
- this.components = /* @__PURE__ */ new Map();
731
- this.workflows = /* @__PURE__ */ new Map();
732
- this.eventListeners = /* @__PURE__ */ new Map();
733
- // State management
734
- this.states = /* @__PURE__ */ new Map();
735
- this.stateGroups = /* @__PURE__ */ new Map();
736
- this.transitions = /* @__PURE__ */ new Map();
737
- this.activeStates = /* @__PURE__ */ new Set();
738
- this.options = options;
739
- }
740
- /**
741
- * Emit an event
742
- */
743
- emit(type, data) {
744
- const event = {
745
- type,
746
- timestamp: Date.now(),
747
- data
748
- };
749
- this.options.onEvent?.(event);
750
- const listeners = this.eventListeners.get(type);
751
- if (listeners) {
752
- for (const listener of listeners) {
753
- try {
754
- listener(event);
755
- } catch (error) {
756
- console.error(`Error in event listener for ${type}:`, error);
757
- }
758
- }
759
- }
760
- if (this.options.verbose) {
761
- console.log("[UIBridge]", type, data);
762
- }
763
- }
764
- /**
765
- * Register an event listener
766
- */
767
- on(type, listener) {
768
- if (!this.eventListeners.has(type)) {
769
- this.eventListeners.set(type, /* @__PURE__ */ new Set());
770
- }
771
- this.eventListeners.get(type).add(listener);
772
- return () => {
773
- this.eventListeners.get(type)?.delete(listener);
774
- };
775
- }
776
- /**
777
- * Remove an event listener
778
- */
779
- off(type, listener) {
780
- this.eventListeners.get(type)?.delete(listener);
781
- }
782
- /**
783
- * Register an element
784
- */
785
- registerElement(id, element, options = {}) {
786
- const type = options.type ?? inferElementType(element);
787
- const actions = options.actions ?? inferActions(type);
788
- const existingUiId = element.getAttribute("data-ui-id");
789
- const actualId = existingUiId || id;
790
- if (!existingUiId) {
791
- element.setAttribute("data-ui-id", actualId);
792
- }
793
- const registered = {
794
- id: actualId,
795
- element,
796
- type,
797
- label: options.label,
798
- actions,
799
- customActions: options.customActions,
800
- getState: () => getElementState(element),
801
- getIdentifier: () => createElementIdentifier(element),
802
- registeredAt: Date.now(),
803
- mounted: true
804
- };
805
- this.elements.set(actualId, registered);
806
- this.emit("element:registered", { id: actualId, type, label: options.label });
807
- return registered;
808
- }
809
- /**
810
- * Unregister an element
811
- */
812
- unregisterElement(id) {
813
- const registered = this.elements.get(id);
814
- if (registered) {
815
- registered.mounted = false;
816
- registered.element.removeAttribute("data-ui-id");
817
- this.elements.delete(id);
818
- this.emit("element:unregistered", { id });
819
- return true;
820
- }
821
- return false;
822
- }
823
- /**
824
- * Get a registered element
825
- */
826
- getElement(id) {
827
- return this.elements.get(id);
828
- }
829
- /**
830
- * Get all registered elements
831
- */
832
- getAllElements() {
833
- return Array.from(this.elements.values());
834
- }
835
- /**
836
- * Find element by DOM element reference
837
- */
838
- findByDOMElement(element) {
839
- for (const registered of this.elements.values()) {
840
- if (registered.element === element) {
841
- return registered;
842
- }
843
- }
844
- return void 0;
845
- }
846
- /**
847
- * Search for elements using AI search criteria
848
- */
849
- searchElements(criteria) {
850
- const results = [];
851
- const threshold = criteria.fuzzyThreshold ?? 0.7;
852
- for (const element of this.elements.values()) {
853
- if (!element.mounted) continue;
854
- const state = element.getState();
855
- if (!criteria.fuzzy && !state.visible) continue;
856
- const aliases = element.aliases ?? this.generateElementAliases(element);
857
- const textContent = state.textContent?.trim() || "";
858
- const label = element.label || "";
859
- let maxScore = 0;
860
- const matchReasons = [];
861
- const scores = {};
862
- if (criteria.text) {
863
- if (textContent.toLowerCase() === criteria.text.toLowerCase() || label.toLowerCase() === criteria.text.toLowerCase()) {
864
- maxScore = 1;
865
- matchReasons.push("exact text match");
866
- scores.text = 1;
867
- } else if (criteria.fuzzy !== false) {
868
- const textResult = fuzzyMatch(criteria.text, textContent, { threshold });
869
- const labelResult = fuzzyMatch(criteria.text, label, { threshold });
870
- const bestResult = textResult.similarity > labelResult.similarity ? textResult : labelResult;
871
- if (bestResult.isMatch) {
872
- scores.text = bestResult.similarity;
873
- if (bestResult.similarity > maxScore) {
874
- maxScore = bestResult.similarity;
875
- matchReasons.push(`text similarity: ${(bestResult.similarity * 100).toFixed(0)}%`);
876
- }
877
- }
878
- }
879
- }
880
- if (criteria.textContains) {
881
- if (textContent.toLowerCase().includes(criteria.textContains.toLowerCase()) || label.toLowerCase().includes(criteria.textContains.toLowerCase())) {
882
- const containsScore = 0.85;
883
- scores.text = Math.max(scores.text ?? 0, containsScore);
884
- if (containsScore > maxScore) {
885
- maxScore = containsScore;
886
- matchReasons.push("text contains");
887
- }
888
- }
889
- }
890
- if (criteria.accessibleName) {
891
- const ariaLabel = element.element.getAttribute("aria-label") || "";
892
- const accessibleName = ariaLabel || label || textContent;
893
- if (accessibleName.toLowerCase() === criteria.accessibleName.toLowerCase()) {
894
- scores.accessibility = 1;
895
- if (1 > maxScore) {
896
- maxScore = 1;
897
- matchReasons.push("accessible name match");
898
- }
899
- } else if (criteria.fuzzy !== false) {
900
- const result = fuzzyMatch(criteria.accessibleName, accessibleName, { threshold });
901
- if (result.isMatch) {
902
- scores.accessibility = result.similarity;
903
- if (result.similarity > maxScore) {
904
- maxScore = result.similarity;
905
- matchReasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
906
- }
907
- }
908
- }
909
- }
910
- if (criteria.role) {
911
- const role = element.element.getAttribute("role") || this.inferRole(element.type);
912
- if (role?.toLowerCase() === criteria.role.toLowerCase()) {
913
- scores.role = 1;
914
- if (1 > maxScore) {
915
- maxScore = 1;
916
- matchReasons.push(`role: ${criteria.role}`);
917
- }
918
- }
919
- }
920
- if (criteria.type) {
921
- if (element.type === criteria.type) {
922
- const typeScore = 0.9;
923
- scores.role = Math.max(scores.role ?? 0, typeScore);
924
- if (typeScore > maxScore) {
925
- maxScore = typeScore;
926
- matchReasons.push(`type: ${criteria.type}`);
927
- }
928
- }
929
- }
930
- for (const alias of aliases) {
931
- const searchText = criteria.text || criteria.textContains || criteria.accessibleName;
932
- if (searchText) {
933
- if (alias.toLowerCase() === searchText.toLowerCase()) {
934
- scores.fuzzy = 1;
935
- if (1 > maxScore) {
936
- maxScore = 1;
937
- matchReasons.push(`alias: "${alias}"`);
938
- }
939
- } else if (criteria.fuzzy !== false) {
940
- const result = fuzzyMatch(searchText, alias, { threshold });
941
- if (result.isMatch && result.similarity > (scores.fuzzy ?? 0)) {
942
- scores.fuzzy = result.similarity;
943
- if (result.similarity > maxScore) {
944
- maxScore = result.similarity;
945
- matchReasons.push(`fuzzy alias: "${alias}"`);
946
- }
947
- }
948
- }
949
- }
950
- }
951
- if (maxScore >= threshold) {
952
- const aiElement = {
953
- id: element.id,
954
- type: element.type,
955
- label: element.label,
956
- tagName: element.element.tagName.toLowerCase(),
957
- role: element.element.getAttribute("role") || void 0,
958
- accessibleName: element.element.getAttribute("aria-label") || element.label,
959
- actions: element.actions,
960
- state,
961
- registered: true,
962
- description: element.description || generateDescription({
963
- textContent,
964
- ariaLabel: element.element.getAttribute("aria-label"),
965
- elementType: element.type,
966
- id: element.id,
967
- labelText: element.label
968
- }),
969
- aliases,
970
- purpose: element.purpose,
971
- suggestedActions: [],
972
- semanticType: element.semanticType
973
- };
974
- results.push({
975
- element: aiElement,
976
- confidence: maxScore,
977
- matchReasons,
978
- scores
979
- });
980
- }
981
- }
982
- results.sort((a, b) => b.confidence - a.confidence);
983
- return results;
984
- }
985
- /**
986
- * Find element by visible text
987
- */
988
- findByText(text, fuzzy = true) {
989
- const results = this.searchElements({ text, fuzzy, fuzzyThreshold: fuzzy ? 0.7 : 1 });
990
- if (results.length > 0) {
991
- return this.elements.get(results[0].element.id);
992
- }
993
- return void 0;
994
- }
995
- /**
996
- * Find element by accessible name
997
- */
998
- findByAccessibleName(name) {
999
- const results = this.searchElements({ accessibleName: name, fuzzy: true });
1000
- if (results.length > 0) {
1001
- return this.elements.get(results[0].element.id);
1002
- }
1003
- return void 0;
1004
- }
1005
- /**
1006
- * Generate aliases for an element
1007
- */
1008
- generateElementAliases(element) {
1009
- const state = element.getState();
1010
- return generateAliases({
1011
- textContent: state.textContent,
1012
- ariaLabel: element.element.getAttribute("aria-label"),
1013
- placeholder: element.element.getAttribute("placeholder"),
1014
- title: element.element.getAttribute("title"),
1015
- elementType: element.type,
1016
- tagName: element.element.tagName.toLowerCase(),
1017
- id: element.id,
1018
- labelText: element.label
1019
- });
1020
- }
1021
- /**
1022
- * Infer ARIA role from element type
1023
- */
1024
- inferRole(type) {
1025
- const roleMap = {
1026
- button: "button",
1027
- input: "textbox",
1028
- select: "combobox",
1029
- checkbox: "checkbox",
1030
- radio: "radio",
1031
- link: "link",
1032
- form: void 0,
1033
- textarea: "textbox",
1034
- menu: "menu",
1035
- menuitem: "menuitem",
1036
- tab: "tab",
1037
- dialog: "dialog",
1038
- custom: void 0,
1039
- switch: "switch",
1040
- slider: "slider",
1041
- combobox: "combobox",
1042
- listbox: "listbox",
1043
- option: "option",
1044
- textbox: "textbox",
1045
- generic: void 0
1046
- };
1047
- return roleMap[type];
1048
- }
1049
- /**
1050
- * Register a component
1051
- */
1052
- registerComponent(id, options) {
1053
- const registered = {
1054
- id,
1055
- name: options.name,
1056
- description: options.description,
1057
- actions: options.actions?.map((a) => ({
1058
- id: a.id,
1059
- label: a.label,
1060
- description: a.description,
1061
- handler: a.handler
1062
- })) ?? [],
1063
- elementIds: options.elementIds,
1064
- registeredAt: Date.now(),
1065
- mounted: true
1066
- };
1067
- this.components.set(id, registered);
1068
- this.emit("component:registered", { id, name: options.name });
1069
- return registered;
1070
- }
1071
- /**
1072
- * Unregister a component
1073
- */
1074
- unregisterComponent(id) {
1075
- const component = this.components.get(id);
1076
- if (component) {
1077
- component.mounted = false;
1078
- this.components.delete(id);
1079
- this.emit("component:unregistered", { id });
1080
- return true;
1081
- }
1082
- return false;
1083
- }
1084
- /**
1085
- * Get a registered component
1086
- */
1087
- getComponent(id) {
1088
- return this.components.get(id);
1089
- }
1090
- /**
1091
- * Get all registered components
1092
- */
1093
- getAllComponents() {
1094
- return Array.from(this.components.values());
1095
- }
1096
- /**
1097
- * Register a workflow
1098
- */
1099
- registerWorkflow(workflow) {
1100
- this.workflows.set(workflow.id, workflow);
1101
- return workflow;
1102
- }
1103
- /**
1104
- * Unregister a workflow
1105
- */
1106
- unregisterWorkflow(id) {
1107
- return this.workflows.delete(id);
1108
- }
1109
- /**
1110
- * Get a workflow
1111
- */
1112
- getWorkflow(id) {
1113
- return this.workflows.get(id);
1114
- }
1115
- /**
1116
- * Get all workflows
1117
- */
1118
- getAllWorkflows() {
1119
- return Array.from(this.workflows.values());
1120
- }
1121
- // ==========================================================================
1122
- // State Management
1123
- // ==========================================================================
1124
- /**
1125
- * Register a state
1126
- */
1127
- registerState(state) {
1128
- this.states.set(state.id, state);
1129
- this.emit("element:registered", { id: state.id, type: "state", name: state.name });
1130
- return state;
1131
- }
1132
- /**
1133
- * Unregister a state
1134
- */
1135
- unregisterState(id) {
1136
- const state = this.states.get(id);
1137
- if (state) {
1138
- this.activeStates.delete(id);
1139
- this.states.delete(id);
1140
- this.emit("element:unregistered", { id, type: "state" });
1141
- return true;
1142
- }
1143
- return false;
1144
- }
1145
- /**
1146
- * Get a registered state
1147
- */
1148
- getState(id) {
1149
- return this.states.get(id);
1150
- }
1151
- /**
1152
- * Get all registered states
1153
- */
1154
- getAllStates() {
1155
- return Array.from(this.states.values());
1156
- }
1157
- /**
1158
- * Register a state group
1159
- */
1160
- registerStateGroup(group) {
1161
- this.stateGroups.set(group.id, group);
1162
- return group;
1163
- }
1164
- /**
1165
- * Unregister a state group
1166
- */
1167
- unregisterStateGroup(id) {
1168
- return this.stateGroups.delete(id);
1169
- }
1170
- /**
1171
- * Get a state group
1172
- */
1173
- getStateGroup(id) {
1174
- return this.stateGroups.get(id);
1175
- }
1176
- /**
1177
- * Get all state groups
1178
- */
1179
- getAllStateGroups() {
1180
- return Array.from(this.stateGroups.values());
1181
- }
1182
- /**
1183
- * Register a transition
1184
- */
1185
- registerTransition(transition) {
1186
- this.transitions.set(transition.id, transition);
1187
- return transition;
1188
- }
1189
- /**
1190
- * Unregister a transition
1191
- */
1192
- unregisterTransition(id) {
1193
- return this.transitions.delete(id);
1194
- }
1195
- /**
1196
- * Get a transition
1197
- */
1198
- getTransition(id) {
1199
- return this.transitions.get(id);
1200
- }
1201
- /**
1202
- * Get all transitions
1203
- */
1204
- getAllTransitions() {
1205
- return Array.from(this.transitions.values());
1206
- }
1207
- /**
1208
- * Get currently active states
1209
- */
1210
- getActiveStates() {
1211
- return Array.from(this.activeStates);
1212
- }
1213
- /**
1214
- * Check if a state is active
1215
- */
1216
- isStateActive(id) {
1217
- return this.activeStates.has(id);
1218
- }
1219
- /**
1220
- * Activate a state
1221
- */
1222
- activateState(id) {
1223
- const state = this.states.get(id);
1224
- if (!state) {
1225
- return false;
1226
- }
1227
- for (const activeId of this.activeStates) {
1228
- const activeState = this.states.get(activeId);
1229
- if (activeState?.blocking && activeState.id !== id) {
1230
- return false;
1231
- }
1232
- if (activeState?.blocks?.includes(id)) {
1233
- return false;
1234
- }
1235
- }
1236
- const wasActive = this.activeStates.has(id);
1237
- this.activeStates.add(id);
1238
- if (!wasActive) {
1239
- this.emit("element:stateChanged", {
1240
- stateId: id,
1241
- active: true,
1242
- activeStates: this.getActiveStates()
1243
- });
1244
- }
1245
- return true;
1246
- }
1247
- /**
1248
- * Deactivate a state
1249
- */
1250
- deactivateState(id) {
1251
- const wasActive = this.activeStates.has(id);
1252
- this.activeStates.delete(id);
1253
- if (wasActive) {
1254
- this.emit("element:stateChanged", {
1255
- stateId: id,
1256
- active: false,
1257
- activeStates: this.getActiveStates()
1258
- });
1259
- }
1260
- return wasActive;
1261
- }
1262
- /**
1263
- * Activate multiple states
1264
- */
1265
- activateStates(ids) {
1266
- const activated = [];
1267
- for (const id of ids) {
1268
- if (this.activateState(id)) {
1269
- activated.push(id);
1270
- }
1271
- }
1272
- return activated;
1273
- }
1274
- /**
1275
- * Deactivate multiple states
1276
- */
1277
- deactivateStates(ids) {
1278
- const deactivated = [];
1279
- for (const id of ids) {
1280
- if (this.deactivateState(id)) {
1281
- deactivated.push(id);
1282
- }
1283
- }
1284
- return deactivated;
1285
- }
1286
- /**
1287
- * Activate a state group (all states in the group)
1288
- */
1289
- activateStateGroup(groupId) {
1290
- const group = this.stateGroups.get(groupId);
1291
- if (!group) return [];
1292
- return this.activateStates(group.states);
1293
- }
1294
- /**
1295
- * Deactivate a state group (all states in the group)
1296
- */
1297
- deactivateStateGroup(groupId) {
1298
- const group = this.stateGroups.get(groupId);
1299
- if (!group) return [];
1300
- return this.deactivateStates(group.states);
1301
- }
1302
- /**
1303
- * Check if a transition can be executed from current state
1304
- */
1305
- canExecuteTransition(transitionId) {
1306
- const transition = this.transitions.get(transitionId);
1307
- if (!transition) return false;
1308
- return transition.fromStates.some((stateId) => this.activeStates.has(stateId));
1309
- }
1310
- /**
1311
- * Execute a transition
1312
- */
1313
- async executeTransition(transitionId) {
1314
- const startTime = performance.now();
1315
- const transition = this.transitions.get(transitionId);
1316
- if (!transition) {
1317
- return {
1318
- success: false,
1319
- activatedStates: [],
1320
- deactivatedStates: [],
1321
- error: `Transition not found: ${transitionId}`,
1322
- durationMs: performance.now() - startTime
1323
- };
1324
- }
1325
- if (!this.canExecuteTransition(transitionId)) {
1326
- return {
1327
- success: false,
1328
- activatedStates: [],
1329
- deactivatedStates: [],
1330
- error: "Precondition not met: none of the fromStates are active",
1331
- failedPhase: "precondition",
1332
- durationMs: performance.now() - startTime
1333
- };
1334
- }
1335
- try {
1336
- const deactivated = this.deactivateStates(transition.exitStates);
1337
- if (transition.exitGroups) {
1338
- for (const groupId of transition.exitGroups) {
1339
- deactivated.push(...this.deactivateStateGroup(groupId));
1340
- }
1341
- }
1342
- const activated = this.activateStates(transition.activateStates);
1343
- if (transition.activateGroups) {
1344
- for (const groupId of transition.activateGroups) {
1345
- activated.push(...this.activateStateGroup(groupId));
1346
- }
1347
- }
1348
- return {
1349
- success: true,
1350
- activatedStates: activated,
1351
- deactivatedStates: deactivated,
1352
- durationMs: performance.now() - startTime
1353
- };
1354
- } catch (error) {
1355
- return {
1356
- success: false,
1357
- activatedStates: [],
1358
- deactivatedStates: [],
1359
- error: error instanceof Error ? error.message : String(error),
1360
- failedPhase: "execution",
1361
- durationMs: performance.now() - startTime
1362
- };
1363
- }
1364
- }
1365
- /**
1366
- * Find a path from current state to target states
1367
- *
1368
- * Uses a simple BFS algorithm for pathfinding.
1369
- * For more advanced pathfinding (Dijkstra, A*), use the Python state manager service.
1370
- */
1371
- findPath(targetStates) {
1372
- if (targetStates.every((t) => this.activeStates.has(t))) {
1373
- return {
1374
- found: true,
1375
- transitions: [],
1376
- totalCost: 0,
1377
- targetStates,
1378
- estimatedSteps: 0
1379
- };
1380
- }
1381
- const queue = [
1382
- { activeStates: new Set(this.activeStates), path: [], cost: 0 }
1383
- ];
1384
- const visited = /* @__PURE__ */ new Set();
1385
- while (queue.length > 0) {
1386
- const current = queue.shift();
1387
- const stateKey = Array.from(current.activeStates).sort().join(",");
1388
- if (visited.has(stateKey)) continue;
1389
- visited.add(stateKey);
1390
- if (targetStates.every((t) => current.activeStates.has(t))) {
1391
- return {
1392
- found: true,
1393
- transitions: current.path,
1394
- totalCost: current.cost,
1395
- targetStates,
1396
- estimatedSteps: current.path.length
1397
- };
1398
- }
1399
- for (const transition of this.transitions.values()) {
1400
- const canExecute = transition.fromStates.some((s) => current.activeStates.has(s));
1401
- if (!canExecute) continue;
1402
- const newActive = new Set(current.activeStates);
1403
- for (const s of transition.exitStates) newActive.delete(s);
1404
- for (const s of transition.activateStates) newActive.add(s);
1405
- const newCost = current.cost + (transition.pathCost ?? 1);
1406
- queue.push({
1407
- activeStates: newActive,
1408
- path: [...current.path, transition.id],
1409
- cost: newCost
1410
- });
1411
- }
1412
- }
1413
- return {
1414
- found: false,
1415
- transitions: [],
1416
- totalCost: 0,
1417
- targetStates,
1418
- estimatedSteps: 0
1419
- };
1420
- }
1421
- /**
1422
- * Navigate to target states using pathfinding
1423
- */
1424
- async navigateTo(targetStates) {
1425
- const startTime = performance.now();
1426
- const path = this.findPath(targetStates);
1427
- if (!path.found) {
1428
- return {
1429
- success: false,
1430
- path,
1431
- executedTransitions: [],
1432
- finalActiveStates: this.getActiveStates(),
1433
- error: `No path found to target states: ${targetStates.join(", ")}`,
1434
- durationMs: performance.now() - startTime
1435
- };
1436
- }
1437
- const executedTransitions = [];
1438
- for (const transitionId of path.transitions) {
1439
- const result = await this.executeTransition(transitionId);
1440
- if (!result.success) {
1441
- return {
1442
- success: false,
1443
- path,
1444
- executedTransitions,
1445
- finalActiveStates: this.getActiveStates(),
1446
- error: result.error,
1447
- durationMs: performance.now() - startTime
1448
- };
1449
- }
1450
- executedTransitions.push(transitionId);
1451
- }
1452
- return {
1453
- success: true,
1454
- path,
1455
- executedTransitions,
1456
- finalActiveStates: this.getActiveStates(),
1457
- durationMs: performance.now() - startTime
1458
- };
1459
- }
1460
- /**
1461
- * Create a state snapshot
1462
- */
1463
- createStateSnapshot() {
1464
- return {
1465
- timestamp: Date.now(),
1466
- activeStates: this.getActiveStates(),
1467
- states: this.getAllStates(),
1468
- groups: this.getAllStateGroups(),
1469
- transitions: this.getAllTransitions()
1470
- };
1471
- }
1472
- /**
1473
- * Create a snapshot of the current state
1474
- */
1475
- createSnapshot() {
1476
- return {
1477
- timestamp: Date.now(),
1478
- elements: this.getAllElements().map((el) => ({
1479
- id: el.id,
1480
- type: el.type,
1481
- label: el.label,
1482
- identifier: el.getIdentifier(),
1483
- state: el.getState(),
1484
- actions: el.actions,
1485
- customActions: el.customActions ? Object.keys(el.customActions) : void 0
1486
- })),
1487
- components: this.getAllComponents().map((comp) => ({
1488
- id: comp.id,
1489
- name: comp.name,
1490
- description: comp.description,
1491
- actions: comp.actions.map((a) => a.id),
1492
- elementIds: comp.elementIds
1493
- })),
1494
- workflows: this.getAllWorkflows().map((wf) => ({
1495
- id: wf.id,
1496
- name: wf.name,
1497
- description: wf.description,
1498
- stepCount: wf.steps.length
1499
- }))
1500
- };
1501
- }
1502
- /**
1503
- * Clear all registrations
1504
- */
1505
- clear() {
1506
- this.elements.clear();
1507
- this.components.clear();
1508
- this.workflows.clear();
1509
- this.eventListeners.clear();
1510
- this.states.clear();
1511
- this.stateGroups.clear();
1512
- this.transitions.clear();
1513
- this.activeStates.clear();
1514
- }
1515
- /**
1516
- * Get registry statistics
1517
- */
1518
- getStats() {
1519
- const elements = this.getAllElements();
1520
- const components = this.getAllComponents();
1521
- return {
1522
- elementCount: elements.length,
1523
- componentCount: components.length,
1524
- workflowCount: this.workflows.size,
1525
- mountedElementCount: elements.filter((e) => e.mounted).length,
1526
- mountedComponentCount: components.filter((c) => c.mounted).length,
1527
- stateCount: this.states.size,
1528
- stateGroupCount: this.stateGroups.size,
1529
- transitionCount: this.transitions.size,
1530
- activeStateCount: this.activeStates.size
1531
- };
1532
- }
1533
- };
1534
- var globalRegistry = null;
1535
- function getGlobalRegistry() {
1536
- if (!globalRegistry) {
1537
- globalRegistry = new UIBridgeRegistry();
1538
- }
1539
- return globalRegistry;
1540
- }
1541
- function setGlobalRegistry(registry) {
1542
- globalRegistry = registry;
1543
- }
1544
- function resetGlobalRegistry() {
1545
- globalRegistry?.clear();
1546
- globalRegistry = null;
1547
- }
1548
-
1549
1
  // src/core/websocket-client.ts
1550
2
  function generateId() {
1551
3
  return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -1981,6 +433,6 @@ function createWSClient(config) {
1981
433
  return new UIBridgeWSClient(config);
1982
434
  }
1983
435
 
1984
- export { ID_ATTRIBUTES, UIBridgeRegistry, UIBridgeWSClient, createElementIdentifier, createWSClient, elementMatchesIdentifier, findAllElementsByIdentifier, findElementByIdentifier, generateCSSSelector, generateXPath, getBestIdentifier, getGlobalRegistry, resetGlobalRegistry, setGlobalRegistry };
436
+ export { UIBridgeWSClient, createWSClient };
1985
437
  //# sourceMappingURL=index.mjs.map
1986
438
  //# sourceMappingURL=index.mjs.map