@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
@@ -0,0 +1,2786 @@
1
+ // src/specs/types.ts
2
+ var SPEC_CONFIG_VERSION = "1.0.0";
3
+ var SPEC_FILE_EXTENSION = ".spec.uibridge.json";
4
+ var VALID_ASSERTION_TYPES = [
5
+ "visible",
6
+ "hidden",
7
+ "enabled",
8
+ "disabled",
9
+ "focused",
10
+ "checked",
11
+ "unchecked",
12
+ "hasText",
13
+ "containsText",
14
+ "hasValue",
15
+ "hasClass",
16
+ "exists",
17
+ "notExists",
18
+ "count",
19
+ "attribute",
20
+ "cssProperty"
21
+ ];
22
+ var VALID_SPEC_CATEGORIES = [
23
+ "element-presence",
24
+ "accessibility",
25
+ "form-validation",
26
+ "state-consistency",
27
+ "modal-dialog",
28
+ "navigation",
29
+ "cross-page-consistency",
30
+ "custom"
31
+ ];
32
+ var VALID_SPEC_SEVERITIES = [
33
+ "critical",
34
+ "warning",
35
+ "info"
36
+ ];
37
+ var VALID_SPEC_SOURCES = [
38
+ "auto",
39
+ "manual",
40
+ "ai-generated"
41
+ ];
42
+
43
+ // src/specs/validator.ts
44
+ function isValidAssertionType(value) {
45
+ return typeof value === "string" && VALID_ASSERTION_TYPES.includes(value);
46
+ }
47
+ function isValidSpecCategory(value) {
48
+ return typeof value === "string" && VALID_SPEC_CATEGORIES.includes(value);
49
+ }
50
+ function isValidSpecSeverity(value) {
51
+ return typeof value === "string" && VALID_SPEC_SEVERITIES.includes(value);
52
+ }
53
+ function isValidSpecSource(value) {
54
+ return typeof value === "string" && VALID_SPEC_SOURCES.includes(value);
55
+ }
56
+ function validateSpecAssertion(data, path = "assertion") {
57
+ const errors = [];
58
+ if (!data || typeof data !== "object") {
59
+ errors.push({ path, message: "must be an object" });
60
+ return errors;
61
+ }
62
+ const obj = data;
63
+ if (typeof obj.id !== "string" || obj.id.length === 0) {
64
+ errors.push({ path: `${path}.id`, message: "must be a non-empty string" });
65
+ }
66
+ if (typeof obj.description !== "string") {
67
+ errors.push({ path: `${path}.description`, message: "must be a string" });
68
+ }
69
+ if (!isValidSpecCategory(obj.category)) {
70
+ errors.push({
71
+ path: `${path}.category`,
72
+ message: `must be one of: ${VALID_SPEC_CATEGORIES.join(", ")}`
73
+ });
74
+ }
75
+ if (!isValidSpecSeverity(obj.severity)) {
76
+ errors.push({
77
+ path: `${path}.severity`,
78
+ message: `must be one of: ${VALID_SPEC_SEVERITIES.join(", ")}`
79
+ });
80
+ }
81
+ if (!obj.target || typeof obj.target !== "object") {
82
+ errors.push({ path: `${path}.target`, message: "must be an object" });
83
+ } else {
84
+ const target = obj.target;
85
+ if (target.type === "elementId") {
86
+ if (typeof target.elementId !== "string" || target.elementId.length === 0) {
87
+ errors.push({ path: `${path}.target.elementId`, message: "must be a non-empty string" });
88
+ }
89
+ } else if (target.type === "search") {
90
+ if (!target.criteria || typeof target.criteria !== "object") {
91
+ errors.push({ path: `${path}.target.criteria`, message: "must be an object" });
92
+ }
93
+ } else {
94
+ errors.push({ path: `${path}.target.type`, message: 'must be "elementId" or "search"' });
95
+ }
96
+ }
97
+ if (!isValidAssertionType(obj.assertionType)) {
98
+ errors.push({
99
+ path: `${path}.assertionType`,
100
+ message: `must be one of: ${VALID_ASSERTION_TYPES.join(", ")}`
101
+ });
102
+ }
103
+ if (!isValidSpecSource(obj.source)) {
104
+ errors.push({
105
+ path: `${path}.source`,
106
+ message: `must be one of: ${VALID_SPEC_SOURCES.join(", ")}`
107
+ });
108
+ }
109
+ if (typeof obj.reviewed !== "boolean") {
110
+ errors.push({ path: `${path}.reviewed`, message: "must be a boolean" });
111
+ }
112
+ if (typeof obj.enabled !== "boolean") {
113
+ errors.push({ path: `${path}.enabled`, message: "must be a boolean" });
114
+ }
115
+ if (obj.timeout !== void 0 && (typeof obj.timeout !== "number" || obj.timeout < 0)) {
116
+ errors.push({ path: `${path}.timeout`, message: "must be a non-negative number" });
117
+ }
118
+ return errors;
119
+ }
120
+ function validateSpecGroup(data, path = "group") {
121
+ const errors = [];
122
+ if (!data || typeof data !== "object") {
123
+ errors.push({ path, message: "must be an object" });
124
+ return errors;
125
+ }
126
+ const obj = data;
127
+ if (typeof obj.id !== "string" || obj.id.length === 0) {
128
+ errors.push({ path: `${path}.id`, message: "must be a non-empty string" });
129
+ }
130
+ if (typeof obj.name !== "string") {
131
+ errors.push({ path: `${path}.name`, message: "must be a string" });
132
+ }
133
+ if (typeof obj.description !== "string") {
134
+ errors.push({ path: `${path}.description`, message: "must be a string" });
135
+ }
136
+ if (!isValidSpecCategory(obj.category)) {
137
+ errors.push({
138
+ path: `${path}.category`,
139
+ message: `must be one of: ${VALID_SPEC_CATEGORIES.join(", ")}`
140
+ });
141
+ }
142
+ if (!isValidSpecSource(obj.source)) {
143
+ errors.push({
144
+ path: `${path}.source`,
145
+ message: `must be one of: ${VALID_SPEC_SOURCES.join(", ")}`
146
+ });
147
+ }
148
+ if (!Array.isArray(obj.assertions)) {
149
+ errors.push({ path: `${path}.assertions`, message: "must be an array" });
150
+ } else {
151
+ for (let i = 0; i < obj.assertions.length; i++) {
152
+ errors.push(...validateSpecAssertion(obj.assertions[i], `${path}.assertions[${i}]`));
153
+ }
154
+ }
155
+ return errors;
156
+ }
157
+ function validateSpecConfig(data) {
158
+ const errors = [];
159
+ if (!data || typeof data !== "object") {
160
+ return { valid: false, errors: [{ path: "", message: "must be an object" }] };
161
+ }
162
+ const obj = data;
163
+ if (obj.version !== SPEC_CONFIG_VERSION) {
164
+ errors.push({ path: "version", message: `must be "${SPEC_CONFIG_VERSION}"` });
165
+ }
166
+ if (obj.description !== void 0 && typeof obj.description !== "string") {
167
+ errors.push({ path: "description", message: "must be a string if provided" });
168
+ }
169
+ if (!Array.isArray(obj.groups)) {
170
+ errors.push({ path: "groups", message: "must be an array" });
171
+ } else {
172
+ for (let i = 0; i < obj.groups.length; i++) {
173
+ errors.push(...validateSpecGroup(obj.groups[i], `groups[${i}]`));
174
+ }
175
+ }
176
+ if (obj.assertions !== void 0) {
177
+ if (!Array.isArray(obj.assertions)) {
178
+ errors.push({ path: "assertions", message: "must be an array if provided" });
179
+ } else {
180
+ for (let i = 0; i < obj.assertions.length; i++) {
181
+ errors.push(...validateSpecAssertion(obj.assertions[i], `assertions[${i}]`));
182
+ }
183
+ }
184
+ }
185
+ if (obj.metadata !== void 0 && (typeof obj.metadata !== "object" || obj.metadata === null)) {
186
+ errors.push({ path: "metadata", message: "must be an object if provided" });
187
+ }
188
+ return { valid: errors.length === 0, errors };
189
+ }
190
+
191
+ // src/specs/migration.ts
192
+ function coerceAssertionType(raw) {
193
+ if (VALID_ASSERTION_TYPES.includes(raw)) {
194
+ return raw;
195
+ }
196
+ return null;
197
+ }
198
+ function coerceCategory(raw) {
199
+ const valid = [
200
+ "element-presence",
201
+ "accessibility",
202
+ "form-validation",
203
+ "state-consistency",
204
+ "modal-dialog",
205
+ "navigation",
206
+ "cross-page-consistency",
207
+ "custom"
208
+ ];
209
+ return valid.includes(raw) ? raw : "custom";
210
+ }
211
+ function coerceSeverity(raw) {
212
+ const valid = ["critical", "warning", "info"];
213
+ return valid.includes(raw) ? raw : "info";
214
+ }
215
+ function coerceSource(raw) {
216
+ if (raw === "auto" || raw === "manual" || raw === "ai-generated") return raw;
217
+ return "auto";
218
+ }
219
+ function migrateLegacyTarget(legacy) {
220
+ switch (legacy.type) {
221
+ case "elementId":
222
+ return {
223
+ type: "elementId",
224
+ elementId: legacy.elementId || "",
225
+ label: legacy.label
226
+ };
227
+ case "formId":
228
+ return {
229
+ type: "search",
230
+ criteria: {
231
+ idPattern: legacy.formId || "",
232
+ role: "form"
233
+ },
234
+ label: legacy.label
235
+ };
236
+ case "modalId":
237
+ return {
238
+ type: "search",
239
+ criteria: {
240
+ idPattern: legacy.modalId || "",
241
+ role: "dialog"
242
+ },
243
+ label: legacy.label
244
+ };
245
+ default:
246
+ return {
247
+ type: "elementId",
248
+ elementId: "",
249
+ label: legacy.label
250
+ };
251
+ }
252
+ }
253
+ function migrateLegacyAssertion(legacy) {
254
+ const assertionType = coerceAssertionType(legacy.assertionType);
255
+ return {
256
+ id: legacy.id,
257
+ description: legacy.description,
258
+ category: coerceCategory(legacy.category),
259
+ severity: coerceSeverity(legacy.severity),
260
+ target: migrateLegacyTarget(legacy.target),
261
+ assertionType: assertionType ?? "exists",
262
+ expected: legacy.expected,
263
+ attributeName: legacy.attributeName,
264
+ source: coerceSource(legacy.source),
265
+ reviewed: legacy.reviewed,
266
+ enabled: legacy.enabled,
267
+ notes: legacy.notes
268
+ };
269
+ }
270
+ function migrateFromTestGeneratorOutput(legacy) {
271
+ const groups = legacy.testSpecifications.map((spec) => ({
272
+ id: spec.id,
273
+ name: spec.name,
274
+ description: spec.description,
275
+ category: coerceCategory(spec.category),
276
+ assertions: spec.assertions.map(migrateLegacyAssertion),
277
+ stateId: spec.stateId,
278
+ transitionId: spec.transitionId,
279
+ source: coerceSource(spec.source)
280
+ }));
281
+ return {
282
+ version: "1.0.0",
283
+ description: legacy.generatorType ? `Migrated from ${legacy.generatorType} test generator output` : "Migrated from legacy test generator output",
284
+ groups,
285
+ metadata: {
286
+ createdAt: legacy.createdAt,
287
+ updatedAt: legacy.updatedAt,
288
+ ...legacy.snapshotMetadata?.pageUrl ? { pageUrl: legacy.snapshotMetadata.pageUrl } : {},
289
+ ...legacy.explorationMetadata?.targetUrl ? { pageUrl: legacy.explorationMetadata.targetUrl } : {}
290
+ }
291
+ };
292
+ }
293
+
294
+ // src/specs/store.ts
295
+ var SpecStore = class {
296
+ constructor() {
297
+ this.configs = /* @__PURE__ */ new Map();
298
+ this.listeners = /* @__PURE__ */ new Set();
299
+ }
300
+ // ---------------------------------------------------------------------------
301
+ // CRUD — Config Level
302
+ // ---------------------------------------------------------------------------
303
+ load(specId, config) {
304
+ this.configs.set(specId, config);
305
+ this.emit({ type: "spec:loaded", specId, timestamp: Date.now() });
306
+ }
307
+ unload(specId) {
308
+ const existed = this.configs.delete(specId);
309
+ if (existed) {
310
+ this.emit({ type: "spec:unloaded", specId, timestamp: Date.now() });
311
+ }
312
+ return existed;
313
+ }
314
+ get(specId) {
315
+ return this.configs.get(specId);
316
+ }
317
+ has(specId) {
318
+ return this.configs.has(specId);
319
+ }
320
+ getIds() {
321
+ return Array.from(this.configs.keys());
322
+ }
323
+ getAll() {
324
+ return new Map(this.configs);
325
+ }
326
+ get count() {
327
+ return this.configs.size;
328
+ }
329
+ clear() {
330
+ this.configs.clear();
331
+ this.emit({ type: "spec:cleared", timestamp: Date.now() });
332
+ }
333
+ // ---------------------------------------------------------------------------
334
+ // CRUD — Group Level
335
+ // ---------------------------------------------------------------------------
336
+ addGroup(specId, group) {
337
+ const config = this.configs.get(specId);
338
+ if (!config) return false;
339
+ config.groups.push(group);
340
+ this.emit({ type: "spec:group-added", specId, groupId: group.id, timestamp: Date.now() });
341
+ return true;
342
+ }
343
+ removeGroup(specId, groupId) {
344
+ const config = this.configs.get(specId);
345
+ if (!config) return false;
346
+ const idx = config.groups.findIndex((g) => g.id === groupId);
347
+ if (idx === -1) return false;
348
+ config.groups.splice(idx, 1);
349
+ this.emit({ type: "spec:group-removed", specId, groupId, timestamp: Date.now() });
350
+ return true;
351
+ }
352
+ getGroup(specId, groupId) {
353
+ const config = this.configs.get(specId);
354
+ if (!config) return void 0;
355
+ return config.groups.find((g) => g.id === groupId);
356
+ }
357
+ // ---------------------------------------------------------------------------
358
+ // CRUD — Assertion Level
359
+ // ---------------------------------------------------------------------------
360
+ addAssertion(specId, groupId, assertion) {
361
+ const config = this.configs.get(specId);
362
+ if (!config) return false;
363
+ if (groupId) {
364
+ const group = config.groups.find((g) => g.id === groupId);
365
+ if (!group) return false;
366
+ group.assertions.push(assertion);
367
+ } else {
368
+ if (!config.assertions) config.assertions = [];
369
+ config.assertions.push(assertion);
370
+ }
371
+ this.emit({
372
+ type: "spec:assertion-added",
373
+ specId,
374
+ groupId: groupId ?? void 0,
375
+ assertionId: assertion.id,
376
+ timestamp: Date.now()
377
+ });
378
+ return true;
379
+ }
380
+ removeAssertion(specId, groupId, assertionId) {
381
+ const config = this.configs.get(specId);
382
+ if (!config) return false;
383
+ let removed = false;
384
+ if (groupId) {
385
+ const group = config.groups.find((g) => g.id === groupId);
386
+ if (group) {
387
+ const idx = group.assertions.findIndex((a) => a.id === assertionId);
388
+ if (idx !== -1) {
389
+ group.assertions.splice(idx, 1);
390
+ removed = true;
391
+ }
392
+ }
393
+ } else if (config.assertions) {
394
+ const idx = config.assertions.findIndex((a) => a.id === assertionId);
395
+ if (idx !== -1) {
396
+ config.assertions.splice(idx, 1);
397
+ removed = true;
398
+ }
399
+ }
400
+ if (removed) {
401
+ this.emit({
402
+ type: "spec:assertion-removed",
403
+ specId,
404
+ groupId: groupId ?? void 0,
405
+ assertionId,
406
+ timestamp: Date.now()
407
+ });
408
+ }
409
+ return removed;
410
+ }
411
+ toggleAssertion(specId, groupId, assertionId) {
412
+ const assertion = this.findAssertion(specId, groupId, assertionId);
413
+ if (!assertion) return false;
414
+ assertion.enabled = !assertion.enabled;
415
+ this.emit({ type: "spec:updated", specId, timestamp: Date.now() });
416
+ return true;
417
+ }
418
+ markReviewed(specId, groupId, assertionId) {
419
+ const assertion = this.findAssertion(specId, groupId, assertionId);
420
+ if (!assertion) return false;
421
+ assertion.reviewed = !assertion.reviewed;
422
+ this.emit({ type: "spec:updated", specId, timestamp: Date.now() });
423
+ return true;
424
+ }
425
+ // ---------------------------------------------------------------------------
426
+ // Queries
427
+ // ---------------------------------------------------------------------------
428
+ getAllAssertions() {
429
+ const result = [];
430
+ for (const config of this.configs.values()) {
431
+ for (const group of config.groups) {
432
+ result.push(...group.assertions);
433
+ }
434
+ if (config.assertions) {
435
+ result.push(...config.assertions);
436
+ }
437
+ }
438
+ return result;
439
+ }
440
+ filterAssertions(opts) {
441
+ return this.getAllAssertions().filter((a) => {
442
+ if (opts.categories && !opts.categories.includes(a.category)) return false;
443
+ if (opts.severities && !opts.severities.includes(a.severity)) return false;
444
+ if (opts.enabledOnly && !a.enabled) return false;
445
+ if (opts.reviewedOnly && !a.reviewed) return false;
446
+ return true;
447
+ });
448
+ }
449
+ // ---------------------------------------------------------------------------
450
+ // Coverage
451
+ // ---------------------------------------------------------------------------
452
+ getCoverage(allElementIds) {
453
+ const specifiedIdSet = /* @__PURE__ */ new Set();
454
+ for (const assertion of this.getAllAssertions()) {
455
+ if (assertion.target.type === "elementId") {
456
+ specifiedIdSet.add(assertion.target.elementId);
457
+ }
458
+ }
459
+ const specifiedIds = [];
460
+ const unspecifiedIds = [];
461
+ for (const id of allElementIds) {
462
+ if (specifiedIdSet.has(id)) {
463
+ specifiedIds.push(id);
464
+ } else {
465
+ unspecifiedIds.push(id);
466
+ }
467
+ }
468
+ const total = allElementIds.length;
469
+ return {
470
+ totalElements: total,
471
+ specifiedElements: specifiedIds.length,
472
+ coveragePercent: total > 0 ? specifiedIds.length / total * 100 : 0,
473
+ specifiedIds,
474
+ unspecifiedIds,
475
+ timestamp: Date.now()
476
+ };
477
+ }
478
+ // ---------------------------------------------------------------------------
479
+ // Import / Export
480
+ // ---------------------------------------------------------------------------
481
+ importConfig(specId, config) {
482
+ const result = validateSpecConfig(config);
483
+ if (!result.valid) return false;
484
+ this.configs.set(specId, config);
485
+ this.emit({ type: "spec:loaded", specId, timestamp: Date.now() });
486
+ return true;
487
+ }
488
+ exportConfig(specId) {
489
+ const config = this.configs.get(specId);
490
+ if (!config) return void 0;
491
+ return {
492
+ ...config,
493
+ version: SPEC_CONFIG_VERSION,
494
+ metadata: {
495
+ ...config.metadata,
496
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
497
+ }
498
+ };
499
+ }
500
+ // ---------------------------------------------------------------------------
501
+ // Events
502
+ // ---------------------------------------------------------------------------
503
+ on(listener) {
504
+ this.listeners.add(listener);
505
+ return () => {
506
+ this.listeners.delete(listener);
507
+ };
508
+ }
509
+ emit(event) {
510
+ for (const listener of this.listeners) {
511
+ try {
512
+ listener(event);
513
+ } catch {
514
+ }
515
+ }
516
+ }
517
+ // ---------------------------------------------------------------------------
518
+ // Private Helpers
519
+ // ---------------------------------------------------------------------------
520
+ findAssertion(specId, groupId, assertionId) {
521
+ const config = this.configs.get(specId);
522
+ if (!config) return void 0;
523
+ if (groupId) {
524
+ const group = config.groups.find((g) => g.id === groupId);
525
+ if (!group) return void 0;
526
+ return group.assertions.find((a) => a.id === assertionId);
527
+ }
528
+ return config.assertions?.find((a) => a.id === assertionId);
529
+ }
530
+ };
531
+ var globalStore = null;
532
+ function getGlobalSpecStore() {
533
+ if (!globalStore) {
534
+ globalStore = new SpecStore();
535
+ }
536
+ return globalStore;
537
+ }
538
+ function resetGlobalSpecStore() {
539
+ globalStore = null;
540
+ }
541
+
542
+ // src/ai/fuzzy-matcher.ts
543
+ var DEFAULT_FUZZY_CONFIG = {
544
+ threshold: 0.7,
545
+ levenshteinWeight: 0.3,
546
+ jaroWinklerWeight: 0.4,
547
+ ngramWeight: 0.3,
548
+ ngramSize: 2,
549
+ caseSensitive: false,
550
+ ignoreWhitespace: true
551
+ };
552
+ function levenshteinDistance(s1, s2) {
553
+ const len1 = s1.length;
554
+ const len2 = s2.length;
555
+ const matrix = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0));
556
+ for (let i = 0; i <= len1; i++) matrix[i][0] = i;
557
+ for (let j = 0; j <= len2; j++) matrix[0][j] = j;
558
+ for (let i = 1; i <= len1; i++) {
559
+ for (let j = 1; j <= len2; j++) {
560
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
561
+ matrix[i][j] = Math.min(
562
+ matrix[i - 1][j] + 1,
563
+ // deletion
564
+ matrix[i][j - 1] + 1,
565
+ // insertion
566
+ matrix[i - 1][j - 1] + cost
567
+ // substitution
568
+ );
569
+ }
570
+ }
571
+ return matrix[len1][len2];
572
+ }
573
+ function levenshteinSimilarity(s1, s2) {
574
+ if (s1.length === 0 && s2.length === 0) return 1;
575
+ if (s1.length === 0 || s2.length === 0) return 0;
576
+ const distance = levenshteinDistance(s1, s2);
577
+ const maxLength = Math.max(s1.length, s2.length);
578
+ return 1 - distance / maxLength;
579
+ }
580
+ function jaroSimilarity(s1, s2) {
581
+ if (s1.length === 0 && s2.length === 0) return 1;
582
+ if (s1.length === 0 || s2.length === 0) return 0;
583
+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
584
+ const s1Matches = new Array(s1.length).fill(false);
585
+ const s2Matches = new Array(s2.length).fill(false);
586
+ let matches = 0;
587
+ let transpositions = 0;
588
+ for (let i = 0; i < s1.length; i++) {
589
+ const start = Math.max(0, i - matchDistance);
590
+ const end = Math.min(i + matchDistance + 1, s2.length);
591
+ for (let j = start; j < end; j++) {
592
+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
593
+ s1Matches[i] = true;
594
+ s2Matches[j] = true;
595
+ matches++;
596
+ break;
597
+ }
598
+ }
599
+ if (matches === 0) return 0;
600
+ let k = 0;
601
+ for (let i = 0; i < s1.length; i++) {
602
+ if (!s1Matches[i]) continue;
603
+ while (!s2Matches[k]) k++;
604
+ if (s1[i] !== s2[k]) transpositions++;
605
+ k++;
606
+ }
607
+ return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
608
+ }
609
+ function jaroWinklerSimilarity(s1, s2, prefixScale = 0.1) {
610
+ const jaroSim = jaroSimilarity(s1, s2);
611
+ let prefixLength = 0;
612
+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
613
+ for (let i = 0; i < maxPrefix; i++) {
614
+ if (s1[i] === s2[i]) {
615
+ prefixLength++;
616
+ } else {
617
+ break;
618
+ }
619
+ }
620
+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
621
+ }
622
+ function generateNgrams(s, n) {
623
+ const ngrams = /* @__PURE__ */ new Set();
624
+ if (s.length < n) {
625
+ ngrams.add(s);
626
+ return ngrams;
627
+ }
628
+ for (let i = 0; i <= s.length - n; i++) {
629
+ ngrams.add(s.substring(i, i + n));
630
+ }
631
+ return ngrams;
632
+ }
633
+ function ngramSimilarity(s1, s2, n = 2) {
634
+ if (s1.length === 0 && s2.length === 0) return 1;
635
+ if (s1.length === 0 || s2.length === 0) return 0;
636
+ const ngrams1 = generateNgrams(s1, n);
637
+ const ngrams2 = generateNgrams(s2, n);
638
+ let intersection = 0;
639
+ for (const ngram of ngrams1) {
640
+ if (ngrams2.has(ngram)) {
641
+ intersection++;
642
+ }
643
+ }
644
+ const union = ngrams1.size + ngrams2.size - intersection;
645
+ return union === 0 ? 0 : intersection / union;
646
+ }
647
+ function normalizeString(s, config = {}) {
648
+ let normalized = s;
649
+ if (!config.caseSensitive) {
650
+ normalized = normalized.toLowerCase();
651
+ }
652
+ if (config.ignoreWhitespace !== false) {
653
+ normalized = normalized.replace(/\s+/g, " ").trim();
654
+ }
655
+ return normalized;
656
+ }
657
+ function fuzzyMatch(source, target, config = {}) {
658
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
659
+ const normalizedSource = normalizeString(source, finalConfig);
660
+ const normalizedTarget = normalizeString(target, finalConfig);
661
+ const levenshteinScore = levenshteinSimilarity(normalizedSource, normalizedTarget);
662
+ const jaroWinklerScore = jaroWinklerSimilarity(normalizedSource, normalizedTarget);
663
+ const ngramScore = ngramSimilarity(normalizedSource, normalizedTarget, finalConfig.ngramSize);
664
+ const similarity = levenshteinScore * finalConfig.levenshteinWeight + jaroWinklerScore * finalConfig.jaroWinklerWeight + ngramScore * finalConfig.ngramWeight;
665
+ return {
666
+ similarity,
667
+ isMatch: similarity >= finalConfig.threshold,
668
+ scores: {
669
+ levenshtein: levenshteinScore,
670
+ jaroWinkler: jaroWinklerScore,
671
+ ngram: ngramScore
672
+ },
673
+ normalizedSource,
674
+ normalizedTarget
675
+ };
676
+ }
677
+ function fuzzyContains(source, target, config = {}) {
678
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
679
+ const normalizedSource = normalizeString(source, finalConfig);
680
+ const normalizedTarget = normalizeString(target, finalConfig);
681
+ if (normalizedSource.includes(normalizedTarget)) {
682
+ return true;
683
+ }
684
+ const sourceWords = normalizedSource.split(/\s+/);
685
+ const targetWords = normalizedTarget.split(/\s+/);
686
+ for (const targetWord of targetWords) {
687
+ const hasMatch = sourceWords.some((sourceWord) => {
688
+ const result = fuzzyMatch(sourceWord, targetWord, { ...finalConfig, threshold: 0.8 });
689
+ return result.isMatch;
690
+ });
691
+ if (!hasMatch) {
692
+ return false;
693
+ }
694
+ }
695
+ return true;
696
+ }
697
+ function wordSimilarity(s1, s2, config = {}) {
698
+ const finalConfig = { ...DEFAULT_FUZZY_CONFIG, ...config };
699
+ const words1 = normalizeString(s1, finalConfig).split(/\s+/);
700
+ const words2 = normalizeString(s2, finalConfig).split(/\s+/);
701
+ if (words1.length === 0 && words2.length === 0) return 1;
702
+ if (words1.length === 0 || words2.length === 0) return 0;
703
+ let totalSimilarity = 0;
704
+ let matchCount = 0;
705
+ for (const word1 of words1) {
706
+ let bestSim = 0;
707
+ for (const word2 of words2) {
708
+ const result = fuzzyMatch(word1, word2, finalConfig);
709
+ if (result.similarity > bestSim) {
710
+ bestSim = result.similarity;
711
+ }
712
+ }
713
+ totalSimilarity += bestSim;
714
+ if (bestSim >= finalConfig.threshold) {
715
+ matchCount++;
716
+ }
717
+ }
718
+ const avgSimilarity = totalSimilarity / words1.length;
719
+ const matchRatio = matchCount / Math.max(words1.length, words2.length);
720
+ return avgSimilarity * 0.5 + matchRatio * 0.5;
721
+ }
722
+ function tokenize(s) {
723
+ return s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase().split(" ").filter((token) => token.length > 0);
724
+ }
725
+ function tokenSimilarity(s1, s2) {
726
+ const tokens1 = tokenize(s1);
727
+ const tokens2 = tokenize(s2);
728
+ if (tokens1.length === 0 && tokens2.length === 0) return 1;
729
+ if (tokens1.length === 0 || tokens2.length === 0) return 0;
730
+ const set1 = new Set(tokens1);
731
+ const set2 = new Set(tokens2);
732
+ let intersection = 0;
733
+ for (const token of set1) {
734
+ if (set2.has(token)) {
735
+ intersection++;
736
+ }
737
+ }
738
+ const union = set1.size + set2.size - intersection;
739
+ return union === 0 ? 0 : intersection / union;
740
+ }
741
+
742
+ // src/ai/alias-generator.ts
743
+ var DEFAULT_ALIAS_CONFIG = {
744
+ includeText: true,
745
+ includeAriaLabel: true,
746
+ includePlaceholder: true,
747
+ includeTitle: true,
748
+ includeSynonyms: true,
749
+ maxAliases: 20,
750
+ minLength: 2,
751
+ maxLength: 50
752
+ };
753
+ var SYNONYMS = {
754
+ // Submit-related
755
+ submit: ["send", "go", "confirm", "ok", "apply", "save", "done", "finish"],
756
+ send: ["submit", "deliver", "post"],
757
+ save: ["submit", "store", "keep", "apply"],
758
+ cancel: ["close", "dismiss", "abort", "back", "exit", "quit", "nevermind"],
759
+ close: ["cancel", "dismiss", "exit", "x"],
760
+ delete: ["remove", "trash", "erase", "clear", "destroy"],
761
+ remove: ["delete", "clear", "discard"],
762
+ edit: ["modify", "change", "update", "alter"],
763
+ update: ["edit", "modify", "save", "refresh"],
764
+ add: ["create", "new", "plus", "insert"],
765
+ create: ["add", "new", "make"],
766
+ search: ["find", "lookup", "query", "filter"],
767
+ find: ["search", "locate", "lookup"],
768
+ login: ["signin", "sign in", "log in", "authenticate", "enter"],
769
+ logout: ["signout", "sign out", "log out", "exit"],
770
+ register: ["signup", "sign up", "join", "create account"],
771
+ next: ["continue", "forward", "proceed", "advance"],
772
+ previous: ["back", "backward", "return", "prior"],
773
+ back: ["previous", "return", "backward"],
774
+ start: ["begin", "launch", "initiate", "run", "execute"],
775
+ stop: ["end", "halt", "pause", "terminate"],
776
+ enable: ["activate", "turn on", "switch on"],
777
+ disable: ["deactivate", "turn off", "switch off"],
778
+ show: ["display", "reveal", "view", "open"],
779
+ hide: ["conceal", "collapse", "close"],
780
+ expand: ["open", "show", "unfold", "reveal"],
781
+ collapse: ["close", "hide", "fold", "minimize"],
782
+ yes: ["ok", "confirm", "agree", "accept"],
783
+ no: ["cancel", "decline", "reject", "deny"],
784
+ help: ["support", "assistance", "info", "information", "faq"],
785
+ settings: ["preferences", "options", "config", "configuration"],
786
+ profile: ["account", "user", "me"],
787
+ download: ["export", "save", "get"],
788
+ upload: ["import", "load", "attach"],
789
+ refresh: ["reload", "update", "sync"],
790
+ copy: ["duplicate", "clone"],
791
+ paste: ["insert"],
792
+ select: ["choose", "pick"],
793
+ toggle: ["switch", "flip"],
794
+ // Form fields
795
+ email: ["e-mail", "mail"],
796
+ password: ["pass", "pwd", "secret"],
797
+ username: ["user", "login", "account", "name"],
798
+ firstname: ["first name", "given name", "forename"],
799
+ lastname: ["last name", "surname", "family name"],
800
+ fullname: ["full name", "name", "complete name"],
801
+ phone: ["telephone", "tel", "mobile", "cell"],
802
+ address: ["location", "street"],
803
+ city: ["town"],
804
+ country: ["nation"],
805
+ zip: ["zipcode", "postal", "postal code", "postcode"],
806
+ // Navigation
807
+ home: ["main", "start", "dashboard"],
808
+ menu: ["navigation", "nav"],
809
+ sidebar: ["side bar", "side panel", "side menu"]
810
+ };
811
+ var ELEMENT_ACTION_WORDS = {
812
+ button: ["button", "btn", "click"],
813
+ input: ["input", "field", "textbox", "box"],
814
+ textarea: ["textarea", "text area", "text field", "multiline"],
815
+ select: ["select", "dropdown", "combo", "picker", "chooser"],
816
+ checkbox: ["checkbox", "check", "tick"],
817
+ radio: ["radio", "option", "choice"],
818
+ link: ["link", "anchor", "href"],
819
+ form: ["form"],
820
+ menu: ["menu"],
821
+ menuitem: ["menu item", "option"],
822
+ tab: ["tab"],
823
+ dialog: ["dialog", "modal", "popup"],
824
+ switch: ["switch", "toggle"],
825
+ slider: ["slider", "range"]
826
+ };
827
+ function normalizeAlias(text) {
828
+ return text.toLowerCase().replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
829
+ }
830
+ function extractWords(text) {
831
+ const tokens = tokenize(text);
832
+ return tokens.filter((t) => t.length >= 2);
833
+ }
834
+ function generateTextAliases(text, config) {
835
+ if (!text || !config.includeText) return [];
836
+ const aliases = [];
837
+ const normalized = normalizeAlias(text);
838
+ if (normalized.length >= config.minLength && normalized.length <= config.maxLength) {
839
+ aliases.push(normalized);
840
+ }
841
+ const words = extractWords(text);
842
+ for (const word of words) {
843
+ if (word.length >= config.minLength) {
844
+ aliases.push(word);
845
+ }
846
+ }
847
+ if (words.length >= 2 && words.length <= 4) {
848
+ const twoWords = words.slice(0, 2).join(" ");
849
+ if (twoWords.length <= config.maxLength) {
850
+ aliases.push(twoWords);
851
+ }
852
+ if (words.length > 2) {
853
+ const lastTwo = words.slice(-2).join(" ");
854
+ if (lastTwo.length <= config.maxLength) {
855
+ aliases.push(lastTwo);
856
+ }
857
+ }
858
+ }
859
+ return aliases;
860
+ }
861
+ function generateSynonyms(aliases, config) {
862
+ if (!config.includeSynonyms) return [];
863
+ const synonyms = [];
864
+ for (const alias of aliases) {
865
+ const words = alias.toLowerCase().split(/\s+/);
866
+ for (const word of words) {
867
+ if (SYNONYMS[word]) {
868
+ for (const synonym of SYNONYMS[word]) {
869
+ const newAlias = alias.toLowerCase().replace(word, synonym);
870
+ if (newAlias !== alias.toLowerCase()) {
871
+ synonyms.push(newAlias);
872
+ }
873
+ if (synonym.length >= config.minLength) {
874
+ synonyms.push(synonym);
875
+ }
876
+ }
877
+ }
878
+ }
879
+ }
880
+ return synonyms;
881
+ }
882
+ function generateTypeAliases(elementType) {
883
+ const type = elementType.toLowerCase();
884
+ return ELEMENT_ACTION_WORDS[type] || [type];
885
+ }
886
+ function generateAliases(input, config = {}) {
887
+ const finalConfig = { ...DEFAULT_ALIAS_CONFIG, ...config };
888
+ const aliasSet = /* @__PURE__ */ new Set();
889
+ const addAlias = (alias) => {
890
+ const normalized = normalizeAlias(alias);
891
+ if (normalized.length >= finalConfig.minLength && normalized.length <= finalConfig.maxLength) {
892
+ aliasSet.add(normalized);
893
+ }
894
+ };
895
+ const addAliases = (aliases2) => {
896
+ for (const alias of aliases2) {
897
+ addAlias(alias);
898
+ }
899
+ };
900
+ if (finalConfig.includeText && input.textContent) {
901
+ addAliases(generateTextAliases(input.textContent, finalConfig));
902
+ }
903
+ if (finalConfig.includeAriaLabel && input.ariaLabel) {
904
+ addAliases(generateTextAliases(input.ariaLabel, finalConfig));
905
+ }
906
+ if (finalConfig.includeAriaLabel && input.ariaLabelledBy) {
907
+ addAliases(generateTextAliases(input.ariaLabelledBy, finalConfig));
908
+ }
909
+ if (finalConfig.includePlaceholder && input.placeholder) {
910
+ addAliases(generateTextAliases(input.placeholder, finalConfig));
911
+ }
912
+ if (finalConfig.includeTitle && input.title) {
913
+ addAliases(generateTextAliases(input.title, finalConfig));
914
+ }
915
+ if (input.labelText) {
916
+ addAliases(generateTextAliases(input.labelText, finalConfig));
917
+ }
918
+ if (input.id) {
919
+ addAliases(extractWords(input.id));
920
+ }
921
+ if (input.name) {
922
+ addAliases(extractWords(input.name));
923
+ }
924
+ if (input.value && (input.elementType === "button" || input.inputType === "submit" || input.inputType === "button")) {
925
+ addAliases(generateTextAliases(input.value, finalConfig));
926
+ }
927
+ if (input.elementType) {
928
+ addAliases(generateTypeAliases(input.elementType));
929
+ }
930
+ if (input.inputType) {
931
+ addAlias(input.inputType);
932
+ if (input.inputType === "email") {
933
+ addAliases(["email", "e-mail", "email address"]);
934
+ } else if (input.inputType === "password") {
935
+ addAliases(["password", "pass", "pwd"]);
936
+ } else if (input.inputType === "tel") {
937
+ addAliases(["phone", "telephone", "mobile"]);
938
+ } else if (input.inputType === "url") {
939
+ addAliases(["url", "website", "link", "address"]);
940
+ } else if (input.inputType === "search") {
941
+ addAliases(["search", "find", "query"]);
942
+ }
943
+ }
944
+ if (finalConfig.includeSynonyms) {
945
+ const currentAliases = Array.from(aliasSet);
946
+ addAliases(generateSynonyms(currentAliases, finalConfig));
947
+ }
948
+ let aliases = Array.from(aliasSet);
949
+ aliases.sort((a, b) => a.length - b.length);
950
+ if (aliases.length > finalConfig.maxAliases) {
951
+ aliases = aliases.slice(0, finalConfig.maxAliases);
952
+ }
953
+ return aliases;
954
+ }
955
+ function generateDescription(input) {
956
+ const parts = [];
957
+ let name = input.ariaLabel || input.labelText || input.textContent || input.placeholder || input.title || input.id || input.name;
958
+ if (name) {
959
+ name = name.trim();
960
+ if (name.length > 30) {
961
+ name = name.substring(0, 27) + "...";
962
+ }
963
+ parts.push(`"${name}"`);
964
+ }
965
+ const typeWords = ELEMENT_ACTION_WORDS[input.elementType || ""] || [
966
+ input.elementType || "element"
967
+ ];
968
+ parts.push(typeWords[0]);
969
+ if (input.inputType && input.inputType !== "text") {
970
+ parts.push(`(${input.inputType})`);
971
+ }
972
+ return parts.join(" ");
973
+ }
974
+ var CONTENT_TYPES = /* @__PURE__ */ new Set([
975
+ "heading",
976
+ "paragraph",
977
+ "list-item",
978
+ "table-cell",
979
+ "table-header",
980
+ "label",
981
+ "caption",
982
+ "blockquote",
983
+ "code-block",
984
+ "badge",
985
+ "status-message",
986
+ "metric-value",
987
+ "description-text",
988
+ "nav-text",
989
+ "content-generic"
990
+ ]);
991
+ function generatePurpose(input) {
992
+ const text = (input.textContent || input.ariaLabel || input.title || "").toLowerCase();
993
+ const type = input.elementType?.toLowerCase() || "";
994
+ const inputType = input.inputType?.toLowerCase() || "";
995
+ if (CONTENT_TYPES.has(type)) {
996
+ switch (type) {
997
+ case "heading":
998
+ return "Section heading";
999
+ case "paragraph":
1000
+ return "Body text content";
1001
+ case "list-item":
1002
+ return "List item";
1003
+ case "table-cell":
1004
+ return "Table data cell";
1005
+ case "table-header":
1006
+ return "Table column header";
1007
+ case "label":
1008
+ return "Field label or definition term";
1009
+ case "caption":
1010
+ return "Figure or table caption";
1011
+ case "blockquote":
1012
+ return "Quoted content";
1013
+ case "code-block":
1014
+ return "Code or preformatted text";
1015
+ case "badge":
1016
+ return "Status badge or tag";
1017
+ case "status-message":
1018
+ return "Dynamic status indicator";
1019
+ case "metric-value":
1020
+ return "Metric or statistic value";
1021
+ case "description-text":
1022
+ return "Description or definition";
1023
+ case "nav-text":
1024
+ return "Navigation label";
1025
+ case "content-generic":
1026
+ return "Text content";
1027
+ default:
1028
+ return "Static content";
1029
+ }
1030
+ }
1031
+ if (type === "button" || inputType === "submit") {
1032
+ if (text.match(/submit|send|save|confirm|ok|done|finish|apply/)) {
1033
+ return "Submits the form";
1034
+ }
1035
+ if (text.match(/cancel|close|dismiss|back|exit/)) {
1036
+ return "Cancels or closes the current action";
1037
+ }
1038
+ if (text.match(/delete|remove|trash|clear/)) {
1039
+ return "Deletes or removes an item";
1040
+ }
1041
+ if (text.match(/edit|modify|change|update/)) {
1042
+ return "Edits or modifies an item";
1043
+ }
1044
+ if (text.match(/add|create|new|\+/)) {
1045
+ return "Creates or adds a new item";
1046
+ }
1047
+ if (text.match(/search|find|lookup/)) {
1048
+ return "Performs a search";
1049
+ }
1050
+ if (text.match(/login|sign.?in/)) {
1051
+ return "Signs the user in";
1052
+ }
1053
+ if (text.match(/logout|sign.?out/)) {
1054
+ return "Signs the user out";
1055
+ }
1056
+ if (text.match(/register|sign.?up|join/)) {
1057
+ return "Creates a new account";
1058
+ }
1059
+ if (text.match(/next|continue|proceed/)) {
1060
+ return "Proceeds to the next step";
1061
+ }
1062
+ if (text.match(/previous|back|return/)) {
1063
+ return "Returns to the previous step";
1064
+ }
1065
+ }
1066
+ if (type === "input" || type === "textarea") {
1067
+ if (inputType === "email") return "Accepts email address input";
1068
+ if (inputType === "password") return "Accepts password input";
1069
+ if (inputType === "search") return "Accepts search query input";
1070
+ if (inputType === "tel") return "Accepts phone number input";
1071
+ if (inputType === "url") return "Accepts URL input";
1072
+ if (inputType === "number") return "Accepts numeric input";
1073
+ if (inputType === "date") return "Accepts date input";
1074
+ if (inputType === "file") return "Accepts file upload";
1075
+ }
1076
+ if (type === "checkbox") {
1077
+ return "Toggles an option on or off";
1078
+ }
1079
+ if (type === "radio") {
1080
+ return "Selects one option from a group";
1081
+ }
1082
+ if (type === "select") {
1083
+ return "Selects an option from a dropdown";
1084
+ }
1085
+ if (type === "link") {
1086
+ return "Navigates to another page";
1087
+ }
1088
+ return void 0;
1089
+ }
1090
+ function generateSuggestedActions(input) {
1091
+ const type = input.elementType?.toLowerCase() || "";
1092
+ const inputType = input.inputType?.toLowerCase() || "";
1093
+ const text = (input.textContent || input.ariaLabel || "").toLowerCase();
1094
+ const actions = [];
1095
+ if (CONTENT_TYPES.has(type)) {
1096
+ actions.push("read text content", "verify text matches expected");
1097
+ return actions;
1098
+ }
1099
+ switch (type) {
1100
+ case "button":
1101
+ actions.push(`click "${text || "this button"}"`);
1102
+ break;
1103
+ case "input":
1104
+ if (inputType === "checkbox") {
1105
+ actions.push("check to enable", "uncheck to disable");
1106
+ } else if (inputType === "radio") {
1107
+ actions.push("select this option");
1108
+ } else {
1109
+ actions.push(`type into "${text || "this field"}"`);
1110
+ actions.push("clear the field");
1111
+ }
1112
+ break;
1113
+ case "textarea":
1114
+ actions.push(`type into "${text || "this text area"}"`);
1115
+ actions.push("clear the content");
1116
+ break;
1117
+ case "select":
1118
+ actions.push(`select an option from "${text || "this dropdown"}"`);
1119
+ break;
1120
+ case "checkbox":
1121
+ actions.push("check to enable", "uncheck to disable");
1122
+ break;
1123
+ case "radio":
1124
+ actions.push("select this option");
1125
+ break;
1126
+ case "link":
1127
+ actions.push(`click to navigate to "${text || "the linked page"}"`);
1128
+ break;
1129
+ case "switch":
1130
+ actions.push("toggle on", "toggle off");
1131
+ break;
1132
+ default:
1133
+ actions.push("click");
1134
+ }
1135
+ return actions;
1136
+ }
1137
+ function areSynonyms(word1, word2) {
1138
+ const w1 = word1.toLowerCase().trim();
1139
+ const w2 = word2.toLowerCase().trim();
1140
+ if (w1 === w2) return true;
1141
+ const synonyms1 = SYNONYMS[w1] || [];
1142
+ const synonyms2 = SYNONYMS[w2] || [];
1143
+ return synonyms1.includes(w2) || synonyms2.includes(w1);
1144
+ }
1145
+
1146
+ // src/annotations/types.ts
1147
+ var ANNOTATION_CONFIG_VERSION = "1.0.0";
1148
+
1149
+ // src/annotations/store.ts
1150
+ var AnnotationStore = class {
1151
+ constructor() {
1152
+ this.store = /* @__PURE__ */ new Map();
1153
+ this.listeners = /* @__PURE__ */ new Set();
1154
+ }
1155
+ /**
1156
+ * Get an annotation by element ID.
1157
+ */
1158
+ get(elementId) {
1159
+ return this.store.get(elementId);
1160
+ }
1161
+ /**
1162
+ * Get all annotations as a record.
1163
+ */
1164
+ getAll() {
1165
+ const result = {};
1166
+ for (const [id, annotation] of this.store) {
1167
+ result[id] = annotation;
1168
+ }
1169
+ return result;
1170
+ }
1171
+ /**
1172
+ * Set an annotation for an element. Auto-sets `updatedAt`.
1173
+ */
1174
+ set(elementId, annotation) {
1175
+ const updated = {
1176
+ ...annotation,
1177
+ updatedAt: Date.now()
1178
+ };
1179
+ this.store.set(elementId, updated);
1180
+ this.emit({
1181
+ type: "annotation:set",
1182
+ elementId,
1183
+ annotation: updated,
1184
+ timestamp: Date.now()
1185
+ });
1186
+ }
1187
+ /**
1188
+ * Delete an annotation by element ID.
1189
+ *
1190
+ * @returns true if the annotation existed and was deleted
1191
+ */
1192
+ delete(elementId) {
1193
+ const existed = this.store.delete(elementId);
1194
+ if (existed) {
1195
+ this.emit({
1196
+ type: "annotation:deleted",
1197
+ elementId,
1198
+ timestamp: Date.now()
1199
+ });
1200
+ }
1201
+ return existed;
1202
+ }
1203
+ /**
1204
+ * Check if an annotation exists for an element.
1205
+ */
1206
+ has(elementId) {
1207
+ return this.store.has(elementId);
1208
+ }
1209
+ /**
1210
+ * Get the number of stored annotations.
1211
+ */
1212
+ get count() {
1213
+ return this.store.size;
1214
+ }
1215
+ /**
1216
+ * Clear all annotations.
1217
+ */
1218
+ clear() {
1219
+ this.store.clear();
1220
+ this.emit({
1221
+ type: "annotation:cleared",
1222
+ timestamp: Date.now()
1223
+ });
1224
+ }
1225
+ /**
1226
+ * Import annotations from a config object.
1227
+ *
1228
+ * Merges with existing annotations (new values overwrite per element ID).
1229
+ *
1230
+ * @returns Number of annotations imported
1231
+ *
1232
+ * @example
1233
+ * ```ts
1234
+ * const config: AnnotationConfig = {
1235
+ * version: '1.0.0',
1236
+ * annotations: {
1237
+ * 'btn-1': { description: 'Submit button', tags: ['form'] },
1238
+ * 'input-1': { description: 'Name field' },
1239
+ * },
1240
+ * };
1241
+ * const count = store.importConfig(config); // 2
1242
+ * ```
1243
+ */
1244
+ importConfig(config) {
1245
+ let count = 0;
1246
+ for (const [id, annotation] of Object.entries(config.annotations)) {
1247
+ this.store.set(id, {
1248
+ ...annotation,
1249
+ updatedAt: annotation.updatedAt ?? Date.now()
1250
+ });
1251
+ count++;
1252
+ }
1253
+ this.emit({
1254
+ type: "annotation:imported",
1255
+ count,
1256
+ timestamp: Date.now()
1257
+ });
1258
+ return count;
1259
+ }
1260
+ /**
1261
+ * Export all annotations as a config object.
1262
+ *
1263
+ * The returned object can be serialized to JSON and saved to a file,
1264
+ * then later re-imported with {@link importConfig}.
1265
+ *
1266
+ * @param metadata - Optional metadata to include (appName, description, etc.)
1267
+ * @returns AnnotationConfig with all current annotations
1268
+ *
1269
+ * @example
1270
+ * ```ts
1271
+ * const config = store.exportConfig({ appName: 'MyApp' });
1272
+ * // config.version === '1.0.0'
1273
+ * // config.annotations === { 'btn-1': { ... }, 'input-1': { ... } }
1274
+ * // config.metadata === { appName: 'MyApp', exportedAt: 1706900000000 }
1275
+ *
1276
+ * // Save to file
1277
+ * fs.writeFileSync('annotations.json', JSON.stringify(config, null, 2));
1278
+ * ```
1279
+ */
1280
+ exportConfig(metadata) {
1281
+ return {
1282
+ version: ANNOTATION_CONFIG_VERSION,
1283
+ annotations: this.getAll(),
1284
+ metadata: {
1285
+ ...metadata,
1286
+ exportedAt: Date.now()
1287
+ }
1288
+ };
1289
+ }
1290
+ /**
1291
+ * Compute annotation coverage against a set of known element IDs.
1292
+ *
1293
+ * Compares the store's annotations against the provided list of element IDs
1294
+ * to determine what percentage of elements have been annotated.
1295
+ *
1296
+ * @param allElementIds - Array of all known element IDs in the UI
1297
+ * @returns Coverage statistics including percentages and lists of annotated/unannotated IDs
1298
+ *
1299
+ * @example
1300
+ * ```ts
1301
+ * store.set('btn-1', { description: 'Submit' });
1302
+ * store.set('input-1', { description: 'Name' });
1303
+ *
1304
+ * const coverage = store.getCoverage(['btn-1', 'input-1', 'input-2', 'link-1']);
1305
+ * // coverage.totalElements === 4
1306
+ * // coverage.annotatedElements === 2
1307
+ * // coverage.coveragePercent === 50
1308
+ * // coverage.annotatedIds === ['btn-1', 'input-1']
1309
+ * // coverage.unannotatedIds === ['input-2', 'link-1']
1310
+ * ```
1311
+ */
1312
+ getCoverage(allElementIds) {
1313
+ const annotatedIds = [];
1314
+ const unannotatedIds = [];
1315
+ for (const id of allElementIds) {
1316
+ if (this.store.has(id)) {
1317
+ annotatedIds.push(id);
1318
+ } else {
1319
+ unannotatedIds.push(id);
1320
+ }
1321
+ }
1322
+ const total = allElementIds.length;
1323
+ return {
1324
+ totalElements: total,
1325
+ annotatedElements: annotatedIds.length,
1326
+ coveragePercent: total > 0 ? annotatedIds.length / total * 100 : 0,
1327
+ annotatedIds,
1328
+ unannotatedIds,
1329
+ timestamp: Date.now()
1330
+ };
1331
+ }
1332
+ /**
1333
+ * Subscribe to annotation events.
1334
+ *
1335
+ * The listener is called whenever annotations are set, deleted, imported,
1336
+ * or cleared. Returns an unsubscribe function to stop listening.
1337
+ *
1338
+ * @param listener - Callback function receiving {@link AnnotationEvent} objects
1339
+ * @returns Unsubscribe function - call it to remove the listener
1340
+ *
1341
+ * @example
1342
+ * ```ts
1343
+ * const unsubscribe = store.on((event) => {
1344
+ * if (event.type === 'annotation:set') {
1345
+ * console.log(`Element ${event.elementId} annotated:`, event.annotation);
1346
+ * }
1347
+ * });
1348
+ *
1349
+ * store.set('btn-1', { description: 'Submit' });
1350
+ * // Logs: "Element btn-1 annotated: { description: 'Submit', updatedAt: ... }"
1351
+ *
1352
+ * unsubscribe(); // Stop listening
1353
+ * ```
1354
+ */
1355
+ on(listener) {
1356
+ this.listeners.add(listener);
1357
+ return () => {
1358
+ this.listeners.delete(listener);
1359
+ };
1360
+ }
1361
+ /**
1362
+ * Emit an event to all listeners.
1363
+ */
1364
+ emit(event) {
1365
+ for (const listener of this.listeners) {
1366
+ try {
1367
+ listener(event);
1368
+ } catch {
1369
+ }
1370
+ }
1371
+ }
1372
+ };
1373
+ var globalStore2 = null;
1374
+ function getGlobalAnnotationStore() {
1375
+ if (!globalStore2) {
1376
+ globalStore2 = new AnnotationStore();
1377
+ }
1378
+ return globalStore2;
1379
+ }
1380
+
1381
+ // src/ai/search-engine.ts
1382
+ var DEFAULT_SEARCH_CONFIG = {
1383
+ fuzzyThreshold: 0.7,
1384
+ textWeight: 0.35,
1385
+ accessibilityWeight: 0.25,
1386
+ roleWeight: 0.15,
1387
+ spatialWeight: 0.1,
1388
+ aliasWeight: 0.15,
1389
+ maxResults: 20,
1390
+ includeHidden: false
1391
+ };
1392
+ var SearchEngine = class {
1393
+ // Cache valid for 100ms
1394
+ constructor(config = {}) {
1395
+ this.cachedElements = [];
1396
+ this.cacheTimestamp = 0;
1397
+ this.cacheValidityMs = 100;
1398
+ this.config = { ...DEFAULT_SEARCH_CONFIG, ...config };
1399
+ }
1400
+ /**
1401
+ * Update cached elements from various sources
1402
+ */
1403
+ updateElements(elements, getState) {
1404
+ this.cachedElements = elements.map((el) => this.toSearchable(el, getState));
1405
+ this.cacheTimestamp = Date.now();
1406
+ }
1407
+ /**
1408
+ * Convert an element to searchable format
1409
+ */
1410
+ toSearchable(element, getState) {
1411
+ let state;
1412
+ let textContent;
1413
+ let tagName;
1414
+ let role;
1415
+ let ariaLabel;
1416
+ let placeholder;
1417
+ let title;
1418
+ let labelText;
1419
+ let value;
1420
+ if ("getState" in element && typeof element.getState === "function") {
1421
+ state = getState ? getState(element) : element.getState();
1422
+ textContent = state.textContent || void 0;
1423
+ try {
1424
+ tagName = element.element.tagName.toLowerCase();
1425
+ } catch {
1426
+ tagName = element.type || "unknown";
1427
+ }
1428
+ try {
1429
+ role = element.element.getAttribute("role") || void 0;
1430
+ ariaLabel = element.element.getAttribute("aria-label") || void 0;
1431
+ placeholder = element.element.getAttribute("placeholder") || void 0;
1432
+ title = element.element.getAttribute("title") || void 0;
1433
+ } catch {
1434
+ }
1435
+ if (!ariaLabel && element.label) {
1436
+ ariaLabel = element.label;
1437
+ }
1438
+ try {
1439
+ if (element.element.id) {
1440
+ const labelEl = document.querySelector(`label[for="${element.element.id}"]`);
1441
+ labelText = labelEl?.textContent?.trim() || void 0;
1442
+ }
1443
+ } catch {
1444
+ }
1445
+ if (!labelText && element.label) {
1446
+ labelText = element.label;
1447
+ }
1448
+ if (!textContent && element.label) {
1449
+ textContent = element.label;
1450
+ }
1451
+ try {
1452
+ if (element.element instanceof HTMLInputElement || element.element instanceof HTMLTextAreaElement || element.element instanceof HTMLSelectElement) {
1453
+ value = element.element.value || void 0;
1454
+ }
1455
+ } catch {
1456
+ value = state.value || void 0;
1457
+ }
1458
+ } else {
1459
+ const discovered = element;
1460
+ state = discovered.state;
1461
+ textContent = state.textContent || void 0;
1462
+ tagName = discovered.tagName;
1463
+ role = discovered.role || void 0;
1464
+ ariaLabel = discovered.accessibleName || void 0;
1465
+ if (!labelText && element.label) {
1466
+ labelText = element.label;
1467
+ }
1468
+ }
1469
+ let aliases = generateAliases({
1470
+ textContent,
1471
+ ariaLabel,
1472
+ placeholder,
1473
+ title,
1474
+ elementType: element.type,
1475
+ id: element.id,
1476
+ labelText,
1477
+ value
1478
+ });
1479
+ if ("aliases" in element && Array.isArray(element.aliases) && element.aliases.length > 0) {
1480
+ const aliasSet = /* @__PURE__ */ new Set([
1481
+ ...aliases,
1482
+ ...element.aliases.map((a) => a.toLowerCase())
1483
+ ]);
1484
+ aliases = [...aliasSet];
1485
+ }
1486
+ let description = generateDescription({
1487
+ textContent,
1488
+ ariaLabel,
1489
+ placeholder,
1490
+ title,
1491
+ elementType: element.type,
1492
+ id: element.id,
1493
+ labelText
1494
+ });
1495
+ if (!description && "description" in element && element.description) {
1496
+ description = element.description;
1497
+ }
1498
+ const annotation = getGlobalAnnotationStore().get(element.id);
1499
+ if (annotation) {
1500
+ if (annotation.description) {
1501
+ description = annotation.description;
1502
+ }
1503
+ if (annotation.tags && annotation.tags.length > 0) {
1504
+ const tagSet = /* @__PURE__ */ new Set([...aliases, ...annotation.tags.map((t) => t.toLowerCase())]);
1505
+ aliases = [...tagSet];
1506
+ }
1507
+ if (annotation.notes) {
1508
+ aliases.push(annotation.notes.toLowerCase());
1509
+ }
1510
+ }
1511
+ return {
1512
+ id: element.id,
1513
+ element,
1514
+ state,
1515
+ textContent,
1516
+ ariaLabel,
1517
+ placeholder,
1518
+ title,
1519
+ role,
1520
+ tagName,
1521
+ type: element.type,
1522
+ aliases,
1523
+ description,
1524
+ rect: state.rect,
1525
+ labelText,
1526
+ value
1527
+ };
1528
+ }
1529
+ /**
1530
+ * Search for elements matching the criteria
1531
+ */
1532
+ search(criteria, elements) {
1533
+ const startTime = performance.now();
1534
+ if (elements) {
1535
+ this.updateElements(elements);
1536
+ }
1537
+ let searchableElements = this.cachedElements;
1538
+ if (!this.config.includeHidden && !criteria.fuzzy) {
1539
+ searchableElements = searchableElements.filter((el) => el.state.visible);
1540
+ }
1541
+ const results = [];
1542
+ for (const searchable of searchableElements) {
1543
+ const result = this.scoreElement(searchable, criteria);
1544
+ if (result.confidence >= (criteria.fuzzyThreshold ?? this.config.fuzzyThreshold)) {
1545
+ results.push(result);
1546
+ }
1547
+ }
1548
+ results.sort((a, b) => b.confidence - a.confidence);
1549
+ const limitedResults = results.slice(0, this.config.maxResults);
1550
+ return {
1551
+ results: limitedResults,
1552
+ bestMatch: limitedResults.length > 0 ? limitedResults[0] : null,
1553
+ scannedCount: searchableElements.length,
1554
+ durationMs: performance.now() - startTime,
1555
+ criteria,
1556
+ timestamp: Date.now()
1557
+ };
1558
+ }
1559
+ /**
1560
+ * Find the best matching element
1561
+ */
1562
+ findBest(criteria, elements) {
1563
+ const response = this.search(criteria, elements);
1564
+ return response.bestMatch;
1565
+ }
1566
+ /**
1567
+ * Find elements by text content
1568
+ */
1569
+ findByText(text, fuzzy = true, elements) {
1570
+ return this.search({ text, fuzzy }, elements).results;
1571
+ }
1572
+ /**
1573
+ * Find elements by role
1574
+ */
1575
+ findByRole(role, name, elements) {
1576
+ const criteria = { role };
1577
+ if (name) {
1578
+ criteria.accessibleName = name;
1579
+ }
1580
+ return this.search(criteria, elements).results;
1581
+ }
1582
+ /**
1583
+ * Find elements by accessible name
1584
+ */
1585
+ findByAccessibleName(name, elements) {
1586
+ return this.search({ accessibleName: name, fuzzy: true }, elements).results;
1587
+ }
1588
+ /**
1589
+ * Find elements near another element
1590
+ */
1591
+ findNear(referenceId, criteria, elements) {
1592
+ return this.search({ ...criteria, near: referenceId }, elements).results;
1593
+ }
1594
+ /**
1595
+ * Find elements within a container
1596
+ */
1597
+ findWithin(containerId, criteria, elements) {
1598
+ return this.search({ ...criteria, within: containerId }, elements).results;
1599
+ }
1600
+ /**
1601
+ * Score an element against search criteria
1602
+ */
1603
+ scoreElement(searchable, criteria) {
1604
+ const scores = {};
1605
+ const matchReasons = [];
1606
+ let totalWeight = 0;
1607
+ let weightedScore = 0;
1608
+ const fuzzyConfig = {
1609
+ ...DEFAULT_FUZZY_CONFIG,
1610
+ threshold: criteria.fuzzyThreshold ?? this.config.fuzzyThreshold
1611
+ };
1612
+ if (criteria.text) {
1613
+ const textScore = this.scoreTextMatch(
1614
+ searchable,
1615
+ criteria.text,
1616
+ criteria.fuzzy !== false,
1617
+ fuzzyConfig.threshold
1618
+ );
1619
+ scores.text = textScore.score;
1620
+ if (textScore.score > 0) {
1621
+ matchReasons.push(...textScore.reasons);
1622
+ }
1623
+ weightedScore += textScore.score * this.config.textWeight;
1624
+ totalWeight += this.config.textWeight;
1625
+ }
1626
+ if (criteria.textContent && !criteria.text) {
1627
+ const alternatives = criteria.textContent.includes("|") ? criteria.textContent.split("|").map((s) => s.trim()).filter(Boolean) : [criteria.textContent];
1628
+ let bestScore = 0;
1629
+ let bestReasons = [];
1630
+ for (const alt of alternatives) {
1631
+ const exactScore = this.scoreTextMatch(
1632
+ searchable,
1633
+ alt,
1634
+ criteria.fuzzy !== false,
1635
+ fuzzyConfig.threshold
1636
+ );
1637
+ const containsScore = this.scoreContainsMatch(searchable, alt, criteria.fuzzy !== false);
1638
+ const altBest = Math.max(exactScore.score, containsScore.score);
1639
+ if (altBest > bestScore) {
1640
+ bestScore = altBest;
1641
+ bestReasons = exactScore.score >= containsScore.score ? exactScore.reasons : containsScore.reasons;
1642
+ }
1643
+ }
1644
+ scores.text = bestScore;
1645
+ if (bestScore > 0) {
1646
+ matchReasons.push(...bestReasons);
1647
+ }
1648
+ weightedScore += bestScore * this.config.textWeight;
1649
+ totalWeight += this.config.textWeight;
1650
+ }
1651
+ if (criteria.textContains) {
1652
+ const containsScore = this.scoreContainsMatch(
1653
+ searchable,
1654
+ criteria.textContains,
1655
+ criteria.fuzzy !== false
1656
+ );
1657
+ scores.text = Math.max(scores.text || 0, containsScore.score);
1658
+ if (containsScore.score > 0 && containsScore.reasons.length > 0) {
1659
+ matchReasons.push(...containsScore.reasons);
1660
+ }
1661
+ weightedScore += containsScore.score * this.config.textWeight;
1662
+ totalWeight += this.config.textWeight;
1663
+ }
1664
+ if (criteria.accessibleName) {
1665
+ const accessibilityScore = this.scoreAccessibilityMatch(
1666
+ searchable,
1667
+ criteria.accessibleName,
1668
+ criteria.fuzzy !== false,
1669
+ fuzzyConfig.threshold
1670
+ );
1671
+ scores.accessibility = accessibilityScore.score;
1672
+ if (accessibilityScore.score > 0) {
1673
+ matchReasons.push(...accessibilityScore.reasons);
1674
+ }
1675
+ weightedScore += accessibilityScore.score * this.config.accessibilityWeight;
1676
+ totalWeight += this.config.accessibilityWeight;
1677
+ }
1678
+ if (criteria.role) {
1679
+ const roleScore = this.scoreRoleMatch(searchable, criteria.role);
1680
+ scores.role = roleScore.score;
1681
+ if (roleScore.score > 0) {
1682
+ matchReasons.push(...roleScore.reasons);
1683
+ }
1684
+ weightedScore += roleScore.score * this.config.roleWeight;
1685
+ totalWeight += this.config.roleWeight;
1686
+ }
1687
+ if (criteria.type) {
1688
+ const typeMatch = searchable.type.toLowerCase() === criteria.type.toLowerCase();
1689
+ if (typeMatch) {
1690
+ matchReasons.push(`type: ${criteria.type}`);
1691
+ weightedScore += 1 * this.config.roleWeight;
1692
+ totalWeight += this.config.roleWeight;
1693
+ }
1694
+ }
1695
+ if (criteria.near) {
1696
+ const spatialScore = this.scoreSpatialMatch(searchable, criteria.near);
1697
+ scores.spatial = spatialScore.score;
1698
+ if (spatialScore.score > 0) {
1699
+ matchReasons.push(...spatialScore.reasons);
1700
+ }
1701
+ weightedScore += spatialScore.score * this.config.spatialWeight;
1702
+ totalWeight += this.config.spatialWeight;
1703
+ }
1704
+ if (criteria.placeholder && searchable.placeholder) {
1705
+ const placeholderResult = fuzzyMatch(
1706
+ searchable.placeholder,
1707
+ criteria.placeholder,
1708
+ fuzzyConfig
1709
+ );
1710
+ if (placeholderResult.isMatch) {
1711
+ matchReasons.push(`placeholder matches`);
1712
+ weightedScore += placeholderResult.similarity * this.config.textWeight;
1713
+ totalWeight += this.config.textWeight;
1714
+ }
1715
+ }
1716
+ if (criteria.title && searchable.title) {
1717
+ const titleResult = fuzzyMatch(searchable.title, criteria.title, fuzzyConfig);
1718
+ if (titleResult.isMatch) {
1719
+ matchReasons.push(`title matches`);
1720
+ weightedScore += titleResult.similarity * this.config.textWeight;
1721
+ totalWeight += this.config.textWeight;
1722
+ }
1723
+ }
1724
+ if (criteria.idPattern) {
1725
+ const idMatch = this.matchPattern(searchable.id, criteria.idPattern);
1726
+ if (idMatch) {
1727
+ matchReasons.push(`id matches pattern`);
1728
+ weightedScore += 1 * this.config.textWeight;
1729
+ totalWeight += this.config.textWeight;
1730
+ }
1731
+ }
1732
+ const aliasScore = this.scoreAliasMatch(searchable, criteria, fuzzyConfig.threshold);
1733
+ if (aliasScore.score > 0) {
1734
+ scores.fuzzy = aliasScore.score;
1735
+ matchReasons.push(...aliasScore.reasons);
1736
+ weightedScore += aliasScore.score * this.config.aliasWeight;
1737
+ totalWeight += this.config.aliasWeight;
1738
+ }
1739
+ const confidence = totalWeight > 0 ? weightedScore / totalWeight : 0;
1740
+ const aiElement = this.toAIDiscoveredElement(searchable);
1741
+ return {
1742
+ element: aiElement,
1743
+ confidence,
1744
+ matchReasons,
1745
+ scores
1746
+ };
1747
+ }
1748
+ /**
1749
+ * Score text match
1750
+ */
1751
+ scoreTextMatch(searchable, text, fuzzy, threshold) {
1752
+ const reasons = [];
1753
+ let maxScore = 0;
1754
+ const textsToMatch = [searchable.textContent, searchable.labelText, searchable.value].filter(
1755
+ Boolean
1756
+ );
1757
+ for (const targetText of textsToMatch) {
1758
+ if (targetText.toLowerCase() === text.toLowerCase()) {
1759
+ maxScore = Math.max(maxScore, 1);
1760
+ reasons.push("exact text match");
1761
+ continue;
1762
+ }
1763
+ if (fuzzy) {
1764
+ const result = fuzzyMatch(targetText, text, { threshold });
1765
+ if (result.isMatch && result.similarity > maxScore) {
1766
+ maxScore = result.similarity;
1767
+ reasons.push(`text similarity: ${(result.similarity * 100).toFixed(0)}%`);
1768
+ }
1769
+ const wordSim = wordSimilarity(targetText, text, { threshold });
1770
+ if (wordSim > maxScore && wordSim >= threshold) {
1771
+ maxScore = wordSim;
1772
+ reasons.push(`word match: ${(wordSim * 100).toFixed(0)}%`);
1773
+ }
1774
+ }
1775
+ }
1776
+ return { score: maxScore, reasons };
1777
+ }
1778
+ /**
1779
+ * Score contains match
1780
+ */
1781
+ scoreContainsMatch(searchable, text, fuzzy) {
1782
+ const reasons = [];
1783
+ let maxScore = 0;
1784
+ const textsToMatch = [
1785
+ searchable.textContent,
1786
+ searchable.labelText,
1787
+ searchable.ariaLabel
1788
+ ].filter(Boolean);
1789
+ for (const targetText of textsToMatch) {
1790
+ if (targetText.toLowerCase().includes(text.toLowerCase())) {
1791
+ maxScore = Math.max(maxScore, 0.9);
1792
+ reasons.push("text contains match");
1793
+ continue;
1794
+ }
1795
+ if (fuzzy && fuzzyContains(targetText, text)) {
1796
+ maxScore = Math.max(maxScore, 0.7);
1797
+ reasons.push("fuzzy contains match");
1798
+ }
1799
+ }
1800
+ return { score: maxScore, reasons };
1801
+ }
1802
+ /**
1803
+ * Score accessibility match
1804
+ */
1805
+ scoreAccessibilityMatch(searchable, name, fuzzy, threshold) {
1806
+ const reasons = [];
1807
+ let maxScore = 0;
1808
+ const accessibleNames = [
1809
+ searchable.ariaLabel,
1810
+ searchable.ariaLabelledBy,
1811
+ searchable.labelText,
1812
+ searchable.title
1813
+ ].filter(Boolean);
1814
+ for (const accessibleName of accessibleNames) {
1815
+ if (accessibleName.toLowerCase() === name.toLowerCase()) {
1816
+ maxScore = Math.max(maxScore, 1);
1817
+ reasons.push("exact accessible name match");
1818
+ continue;
1819
+ }
1820
+ if (fuzzy) {
1821
+ const result = fuzzyMatch(accessibleName, name, { threshold });
1822
+ if (result.isMatch && result.similarity > maxScore) {
1823
+ maxScore = result.similarity;
1824
+ reasons.push(`accessible name similarity: ${(result.similarity * 100).toFixed(0)}%`);
1825
+ }
1826
+ }
1827
+ }
1828
+ return { score: maxScore, reasons };
1829
+ }
1830
+ /**
1831
+ * Score role match
1832
+ */
1833
+ scoreRoleMatch(searchable, role) {
1834
+ const reasons = [];
1835
+ const normalizedRole = role.toLowerCase();
1836
+ if (searchable.role?.toLowerCase() === normalizedRole) {
1837
+ return { score: 1, reasons: [`role: ${role}`] };
1838
+ }
1839
+ const tagRoleMap = {
1840
+ button: ["button", "input[type=button]", "input[type=submit]"],
1841
+ textbox: ["input", "textarea"],
1842
+ checkbox: ["input[type=checkbox]"],
1843
+ radio: ["input[type=radio]"],
1844
+ link: ["a"],
1845
+ listbox: ["select"],
1846
+ combobox: ["select", "input[list]"],
1847
+ navigation: ["nav"],
1848
+ main: ["main"],
1849
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"]
1850
+ };
1851
+ const inferredRoles = tagRoleMap[normalizedRole] || [];
1852
+ if (inferredRoles.some(
1853
+ (r) => searchable.tagName === r || searchable.type.toLowerCase() === normalizedRole
1854
+ )) {
1855
+ return { score: 0.8, reasons: [`inferred role: ${role}`] };
1856
+ }
1857
+ return { score: 0, reasons };
1858
+ }
1859
+ /**
1860
+ * Score spatial match (proximity to another element)
1861
+ */
1862
+ scoreSpatialMatch(searchable, nearId) {
1863
+ const reference = this.cachedElements.find((el) => el.id === nearId);
1864
+ if (!reference) {
1865
+ return { score: 0, reasons: [] };
1866
+ }
1867
+ const distance = this.calculateDistance(searchable.rect, reference.rect);
1868
+ const nearThreshold = 200;
1869
+ if (distance > nearThreshold * 3) {
1870
+ return { score: 0, reasons: [] };
1871
+ }
1872
+ const score = Math.max(0, 1 - distance / (nearThreshold * 3));
1873
+ return {
1874
+ score,
1875
+ reasons: [`${distance.toFixed(0)}px from ${nearId}`]
1876
+ };
1877
+ }
1878
+ /**
1879
+ * Calculate distance between two element rectangles
1880
+ */
1881
+ calculateDistance(rect1, rect2) {
1882
+ const center1 = {
1883
+ x: rect1.x + rect1.width / 2,
1884
+ y: rect1.y + rect1.height / 2
1885
+ };
1886
+ const center2 = {
1887
+ x: rect2.x + rect2.width / 2,
1888
+ y: rect2.y + rect2.height / 2
1889
+ };
1890
+ return Math.sqrt(Math.pow(center1.x - center2.x, 2) + Math.pow(center1.y - center2.y, 2));
1891
+ }
1892
+ /**
1893
+ * Score alias match
1894
+ */
1895
+ scoreAliasMatch(searchable, criteria, threshold) {
1896
+ const reasons = [];
1897
+ let maxScore = 0;
1898
+ const searchTerms = [];
1899
+ if (criteria.text) searchTerms.push(criteria.text);
1900
+ if (criteria.textContains) searchTerms.push(criteria.textContains);
1901
+ if (criteria.accessibleName) searchTerms.push(criteria.accessibleName);
1902
+ for (const searchTerm of searchTerms) {
1903
+ const termLower = searchTerm.toLowerCase();
1904
+ for (const alias of searchable.aliases) {
1905
+ if (alias === termLower) {
1906
+ maxScore = Math.max(maxScore, 1);
1907
+ reasons.push(`alias match: "${alias}"`);
1908
+ continue;
1909
+ }
1910
+ const searchWords = termLower.split(/\s+/);
1911
+ const aliasWords = alias.split(/\s+/);
1912
+ for (const searchWord of searchWords) {
1913
+ for (const aliasWord of aliasWords) {
1914
+ if (areSynonyms(searchWord, aliasWord)) {
1915
+ maxScore = Math.max(maxScore, 0.85);
1916
+ reasons.push(`synonym match: "${searchWord}" ~ "${aliasWord}"`);
1917
+ }
1918
+ }
1919
+ }
1920
+ const result = fuzzyMatch(alias, termLower, { threshold });
1921
+ if (result.isMatch && result.similarity > maxScore) {
1922
+ maxScore = result.similarity;
1923
+ reasons.push(`fuzzy alias: "${alias}" (${(result.similarity * 100).toFixed(0)}%)`);
1924
+ }
1925
+ const tokenSim = tokenSimilarity(alias, termLower);
1926
+ if (tokenSim > maxScore && tokenSim >= threshold) {
1927
+ maxScore = tokenSim;
1928
+ reasons.push(`token match: "${alias}"`);
1929
+ }
1930
+ }
1931
+ }
1932
+ return { score: maxScore, reasons };
1933
+ }
1934
+ /**
1935
+ * Match a string against a pattern (supports * wildcard)
1936
+ */
1937
+ matchPattern(str, pattern) {
1938
+ const regexPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
1939
+ return new RegExp(`^${regexPattern}$`, "i").test(str);
1940
+ }
1941
+ /**
1942
+ * Convert searchable element to AI discovered element
1943
+ */
1944
+ toAIDiscoveredElement(searchable) {
1945
+ const discoveredBase = "getState" in searchable.element ? {
1946
+ id: searchable.id,
1947
+ type: searchable.type,
1948
+ label: searchable.element.label,
1949
+ tagName: searchable.tagName,
1950
+ role: searchable.role,
1951
+ accessibleName: searchable.ariaLabel,
1952
+ actions: searchable.element.actions,
1953
+ state: searchable.state,
1954
+ registered: true
1955
+ } : searchable.element;
1956
+ return {
1957
+ ...discoveredBase,
1958
+ description: searchable.description,
1959
+ aliases: searchable.aliases,
1960
+ purpose: generatePurpose({
1961
+ textContent: searchable.textContent,
1962
+ ariaLabel: searchable.ariaLabel,
1963
+ elementType: searchable.type,
1964
+ tagName: searchable.tagName
1965
+ }),
1966
+ parentContext: void 0,
1967
+ // Would need DOM traversal
1968
+ suggestedActions: generateSuggestedActions({
1969
+ textContent: searchable.textContent,
1970
+ ariaLabel: searchable.ariaLabel,
1971
+ elementType: searchable.type,
1972
+ tagName: searchable.tagName
1973
+ }),
1974
+ semanticType: this.inferSemanticType(searchable),
1975
+ labelText: searchable.labelText,
1976
+ placeholder: searchable.placeholder,
1977
+ title: searchable.title
1978
+ };
1979
+ }
1980
+ /**
1981
+ * Infer a semantic type for the element
1982
+ */
1983
+ inferSemanticType(searchable) {
1984
+ const text = (searchable.textContent || searchable.ariaLabel || "").toLowerCase();
1985
+ const type = searchable.type.toLowerCase();
1986
+ if (type === "input" || type === "textarea") {
1987
+ if (searchable.placeholder?.toLowerCase().includes("email") || text.includes("email")) {
1988
+ return "email-input";
1989
+ }
1990
+ if (searchable.placeholder?.toLowerCase().includes("password") || text.includes("password")) {
1991
+ return "password-input";
1992
+ }
1993
+ if (searchable.placeholder?.toLowerCase().includes("search") || text.includes("search")) {
1994
+ return "search-input";
1995
+ }
1996
+ return "text-input";
1997
+ }
1998
+ if (type === "button") {
1999
+ if (text.match(/submit|save|confirm|ok|done|apply/)) return "submit-button";
2000
+ if (text.match(/cancel|close|dismiss/)) return "cancel-button";
2001
+ if (text.match(/delete|remove|trash/)) return "delete-button";
2002
+ if (text.match(/add|create|new|\+/)) return "add-button";
2003
+ if (text.match(/edit|modify/)) return "edit-button";
2004
+ if (text.match(/next|continue/)) return "next-button";
2005
+ if (text.match(/back|previous/)) return "back-button";
2006
+ return "action-button";
2007
+ }
2008
+ if (type === "link") {
2009
+ if (text.match(/home|dashboard/)) return "home-link";
2010
+ if (text.match(/login|sign.?in/)) return "login-link";
2011
+ if (text.match(/logout|sign.?out/)) return "logout-link";
2012
+ return "navigation-link";
2013
+ }
2014
+ return type;
2015
+ }
2016
+ };
2017
+
2018
+ // src/ai/assertions.ts
2019
+ var DEFAULT_ASSERTION_CONFIG = {
2020
+ defaultTimeout: 5e3,
2021
+ pollInterval: 100,
2022
+ fuzzyThreshold: 0.7,
2023
+ includeSuggestions: true
2024
+ };
2025
+ var AssertionExecutor = class {
2026
+ constructor(config = {}) {
2027
+ this.elements = [];
2028
+ this.config = { ...DEFAULT_ASSERTION_CONFIG, ...config };
2029
+ this.searchEngine = new SearchEngine({ fuzzyThreshold: this.config.fuzzyThreshold });
2030
+ }
2031
+ /**
2032
+ * Update available elements for assertions
2033
+ */
2034
+ updateElements(elements) {
2035
+ this.elements = elements;
2036
+ this.searchEngine.updateElements(elements);
2037
+ }
2038
+ /**
2039
+ * Execute a single assertion
2040
+ */
2041
+ async assert(request) {
2042
+ const startTime = performance.now();
2043
+ const timeout = request.timeout ?? this.config.defaultTimeout;
2044
+ const searchResult = this.findElementDetailed(request.target, request.fuzzy !== false);
2045
+ const element = searchResult?.element ?? null;
2046
+ const searchDetails = searchResult ? {
2047
+ confidence: searchResult.confidence,
2048
+ matchReasons: searchResult.matchReasons,
2049
+ candidateCount: this.elements.length
2050
+ } : void 0;
2051
+ if (!element && request.type !== "notExists") {
2052
+ const result2 = this.createResult(
2053
+ false,
2054
+ typeof request.target === "string" ? request.target : JSON.stringify(request.target),
2055
+ "element not found",
2056
+ request.type === "exists" ? true : request.expected,
2057
+ null,
2058
+ "Element could not be found",
2059
+ this.config.includeSuggestions ? "Check if the element exists and is properly labeled" : void 0,
2060
+ startTime
2061
+ );
2062
+ if (searchDetails) {
2063
+ result2.searchDetails = searchDetails;
2064
+ }
2065
+ return result2;
2066
+ }
2067
+ const result = await this.executeAssertion(request, element, timeout, startTime);
2068
+ if (searchDetails) {
2069
+ result.searchDetails = searchDetails;
2070
+ }
2071
+ return result;
2072
+ }
2073
+ /**
2074
+ * Execute multiple assertions
2075
+ */
2076
+ async assertBatch(request) {
2077
+ const startTime = performance.now();
2078
+ const results = [];
2079
+ let passedCount = 0;
2080
+ let failedCount = 0;
2081
+ for (const assertion of request.assertions) {
2082
+ const result = await this.assert(assertion);
2083
+ results.push(result);
2084
+ if (result.passed) {
2085
+ passedCount++;
2086
+ } else {
2087
+ failedCount++;
2088
+ if (request.stopOnFailure) {
2089
+ break;
2090
+ }
2091
+ }
2092
+ }
2093
+ const passed = request.mode === "all" ? failedCount === 0 : passedCount > 0;
2094
+ return {
2095
+ passed,
2096
+ results,
2097
+ passedCount,
2098
+ failedCount,
2099
+ durationMs: performance.now() - startTime,
2100
+ timestamp: Date.now()
2101
+ };
2102
+ }
2103
+ /**
2104
+ * Convenience method: assert element is visible
2105
+ */
2106
+ async assertVisible(target, timeout) {
2107
+ return this.assert({ target, type: "visible", timeout });
2108
+ }
2109
+ /**
2110
+ * Convenience method: assert element is hidden
2111
+ */
2112
+ async assertHidden(target, timeout) {
2113
+ return this.assert({ target, type: "hidden", timeout });
2114
+ }
2115
+ /**
2116
+ * Convenience method: assert element is enabled
2117
+ */
2118
+ async assertEnabled(target, timeout) {
2119
+ return this.assert({ target, type: "enabled", timeout });
2120
+ }
2121
+ /**
2122
+ * Convenience method: assert element is disabled
2123
+ */
2124
+ async assertDisabled(target, timeout) {
2125
+ return this.assert({ target, type: "disabled", timeout });
2126
+ }
2127
+ /**
2128
+ * Convenience method: assert element has text
2129
+ */
2130
+ async assertHasText(target, text, timeout) {
2131
+ return this.assert({ target, type: "hasText", expected: text, timeout });
2132
+ }
2133
+ /**
2134
+ * Convenience method: assert element contains text
2135
+ */
2136
+ async assertContainsText(target, text, timeout) {
2137
+ return this.assert({ target, type: "containsText", expected: text, timeout });
2138
+ }
2139
+ /**
2140
+ * Convenience method: assert element has value
2141
+ */
2142
+ async assertHasValue(target, value, timeout) {
2143
+ return this.assert({ target, type: "hasValue", expected: value, timeout });
2144
+ }
2145
+ /**
2146
+ * Convenience method: assert element exists
2147
+ */
2148
+ async assertExists(target, timeout) {
2149
+ return this.assert({ target, type: "exists", timeout });
2150
+ }
2151
+ /**
2152
+ * Convenience method: assert element does not exist
2153
+ */
2154
+ async assertNotExists(target, timeout) {
2155
+ return this.assert({ target, type: "notExists", timeout });
2156
+ }
2157
+ /**
2158
+ * Convenience method: assert checkbox is checked
2159
+ */
2160
+ async assertChecked(target, timeout) {
2161
+ return this.assert({ target, type: "checked", timeout });
2162
+ }
2163
+ /**
2164
+ * Convenience method: assert checkbox is unchecked
2165
+ */
2166
+ async assertUnchecked(target, timeout) {
2167
+ return this.assert({ target, type: "unchecked", timeout });
2168
+ }
2169
+ /**
2170
+ * Convenience method: assert element count
2171
+ */
2172
+ async assertCount(target, expectedCount, timeout) {
2173
+ return this.assert({ target, type: "count", expected: expectedCount, timeout });
2174
+ }
2175
+ /**
2176
+ * Find element by target with full search metadata.
2177
+ * Returns the SearchResult (including confidence, matchReasons, scores)
2178
+ * or null if no match above the fuzzy threshold.
2179
+ */
2180
+ findElementDetailed(target, fuzzy = true) {
2181
+ const criteria = typeof target === "string" ? { text: target, fuzzy } : { ...target, fuzzy };
2182
+ const searchResult = this.searchEngine.findBest(criteria, this.elements);
2183
+ if (searchResult && searchResult.confidence >= this.config.fuzzyThreshold) {
2184
+ return searchResult;
2185
+ }
2186
+ return null;
2187
+ }
2188
+ /**
2189
+ * Find element by target (string or criteria).
2190
+ * Public for use by condition evaluation in SpecExecutor.
2191
+ */
2192
+ async findElement(target, fuzzy = true) {
2193
+ const result = this.findElementDetailed(target, fuzzy);
2194
+ return result?.element ?? null;
2195
+ }
2196
+ /**
2197
+ * Execute the actual assertion
2198
+ */
2199
+ async executeAssertion(request, element, timeout, startTime) {
2200
+ const targetStr = typeof request.target === "string" ? request.target : JSON.stringify(request.target);
2201
+ const elementDescription = element?.description || targetStr;
2202
+ switch (request.type) {
2203
+ case "visible":
2204
+ return this.assertVisibility(
2205
+ element,
2206
+ true,
2207
+ elementDescription,
2208
+ request.message,
2209
+ startTime
2210
+ );
2211
+ case "hidden":
2212
+ return this.assertVisibility(
2213
+ element,
2214
+ false,
2215
+ elementDescription,
2216
+ request.message,
2217
+ startTime
2218
+ );
2219
+ case "enabled":
2220
+ return this.assertEnabledState(
2221
+ element,
2222
+ true,
2223
+ elementDescription,
2224
+ request.message,
2225
+ startTime
2226
+ );
2227
+ case "disabled":
2228
+ return this.assertEnabledState(
2229
+ element,
2230
+ false,
2231
+ elementDescription,
2232
+ request.message,
2233
+ startTime
2234
+ );
2235
+ case "focused":
2236
+ return this.assertFocused(element, elementDescription, request.message, startTime);
2237
+ case "checked":
2238
+ return this.assertCheckedState(
2239
+ element,
2240
+ true,
2241
+ elementDescription,
2242
+ request.message,
2243
+ startTime
2244
+ );
2245
+ case "unchecked":
2246
+ return this.assertCheckedState(
2247
+ element,
2248
+ false,
2249
+ elementDescription,
2250
+ request.message,
2251
+ startTime
2252
+ );
2253
+ case "hasText":
2254
+ return this.assertTextMatch(
2255
+ element,
2256
+ request.expected,
2257
+ true,
2258
+ elementDescription,
2259
+ request.message,
2260
+ startTime
2261
+ );
2262
+ case "containsText":
2263
+ return this.assertTextMatch(
2264
+ element,
2265
+ request.expected,
2266
+ false,
2267
+ elementDescription,
2268
+ request.message,
2269
+ startTime
2270
+ );
2271
+ case "hasValue":
2272
+ return this.assertValue(
2273
+ element,
2274
+ request.expected,
2275
+ elementDescription,
2276
+ request.message,
2277
+ startTime
2278
+ );
2279
+ case "exists":
2280
+ return this.createResult(
2281
+ element !== null,
2282
+ targetStr,
2283
+ elementDescription,
2284
+ true,
2285
+ element !== null,
2286
+ element === null ? "Element does not exist" : void 0,
2287
+ void 0,
2288
+ startTime,
2289
+ element?.state
2290
+ );
2291
+ case "notExists":
2292
+ return this.createResult(
2293
+ element === null,
2294
+ targetStr,
2295
+ elementDescription,
2296
+ false,
2297
+ element === null,
2298
+ element !== null ? "Element exists but should not" : void 0,
2299
+ void 0,
2300
+ startTime,
2301
+ element?.state
2302
+ );
2303
+ case "count":
2304
+ return this.assertElementCount(
2305
+ request.target,
2306
+ request.expected,
2307
+ targetStr,
2308
+ request.message,
2309
+ startTime
2310
+ );
2311
+ case "attribute":
2312
+ return this.assertAttribute(
2313
+ element,
2314
+ request.attributeName,
2315
+ request.expected,
2316
+ elementDescription,
2317
+ request.message,
2318
+ startTime
2319
+ );
2320
+ case "hasClass":
2321
+ return this.assertHasClass(
2322
+ element,
2323
+ request.expected,
2324
+ elementDescription,
2325
+ request.message,
2326
+ startTime
2327
+ );
2328
+ case "cssProperty":
2329
+ return this.assertCssProperty(
2330
+ element,
2331
+ request.propertyName,
2332
+ request.expected,
2333
+ elementDescription,
2334
+ request.message,
2335
+ startTime
2336
+ );
2337
+ default:
2338
+ return this.createResult(
2339
+ false,
2340
+ targetStr,
2341
+ elementDescription,
2342
+ void 0,
2343
+ void 0,
2344
+ `Unknown assertion type: ${request.type}`,
2345
+ void 0,
2346
+ startTime
2347
+ );
2348
+ }
2349
+ }
2350
+ /**
2351
+ * Assert visibility state
2352
+ */
2353
+ assertVisibility(element, expectedVisible, description, message, startTime = performance.now()) {
2354
+ const isVisible = element.state.visible;
2355
+ const passed = isVisible === expectedVisible;
2356
+ return this.createResult(
2357
+ passed,
2358
+ element.id,
2359
+ description,
2360
+ expectedVisible,
2361
+ isVisible,
2362
+ passed ? void 0 : message || `Element is ${isVisible ? "visible" : "hidden"} but expected ${expectedVisible ? "visible" : "hidden"}`,
2363
+ passed ? void 0 : "Check if element is covered by another element or has display:none",
2364
+ startTime,
2365
+ element.state
2366
+ );
2367
+ }
2368
+ /**
2369
+ * Assert enabled state
2370
+ */
2371
+ assertEnabledState(element, expectedEnabled, description, message, startTime = performance.now()) {
2372
+ const isEnabled = element.state.enabled;
2373
+ const passed = isEnabled === expectedEnabled;
2374
+ return this.createResult(
2375
+ passed,
2376
+ element.id,
2377
+ description,
2378
+ expectedEnabled,
2379
+ isEnabled,
2380
+ passed ? void 0 : message || `Element is ${isEnabled ? "enabled" : "disabled"} but expected ${expectedEnabled ? "enabled" : "disabled"}`,
2381
+ passed ? void 0 : "Check if the element has a disabled attribute or aria-disabled",
2382
+ startTime,
2383
+ element.state
2384
+ );
2385
+ }
2386
+ /**
2387
+ * Assert focused state
2388
+ */
2389
+ assertFocused(element, description, message, startTime = performance.now()) {
2390
+ const isFocused = element.state.focused;
2391
+ return this.createResult(
2392
+ isFocused,
2393
+ element.id,
2394
+ description,
2395
+ true,
2396
+ isFocused,
2397
+ isFocused ? void 0 : message || "Element is not focused",
2398
+ isFocused ? void 0 : "Click or focus the element first",
2399
+ startTime,
2400
+ element.state
2401
+ );
2402
+ }
2403
+ /**
2404
+ * Assert checked state
2405
+ */
2406
+ assertCheckedState(element, expectedChecked, description, message, startTime = performance.now()) {
2407
+ const isChecked = element.state.checked ?? false;
2408
+ const passed = isChecked === expectedChecked;
2409
+ return this.createResult(
2410
+ passed,
2411
+ element.id,
2412
+ description,
2413
+ expectedChecked,
2414
+ isChecked,
2415
+ passed ? void 0 : message || `Element is ${isChecked ? "checked" : "unchecked"} but expected ${expectedChecked ? "checked" : "unchecked"}`,
2416
+ passed ? void 0 : "Click the checkbox to change its state",
2417
+ startTime,
2418
+ element.state
2419
+ );
2420
+ }
2421
+ /**
2422
+ * Assert text content
2423
+ */
2424
+ assertTextMatch(element, expectedText, exact, description, message, startTime = performance.now()) {
2425
+ const actualText = element.state.textContent || "";
2426
+ const passed = exact ? actualText === expectedText : actualText.includes(expectedText);
2427
+ return this.createResult(
2428
+ passed,
2429
+ element.id,
2430
+ description,
2431
+ expectedText,
2432
+ actualText,
2433
+ passed ? void 0 : message || (exact ? `Text "${actualText}" does not match expected "${expectedText}"` : `Text "${actualText}" does not contain "${expectedText}"`),
2434
+ passed ? void 0 : "Verify the element contains the expected text",
2435
+ startTime,
2436
+ element.state
2437
+ );
2438
+ }
2439
+ /**
2440
+ * Assert input value
2441
+ */
2442
+ assertValue(element, expectedValue, description, message, startTime = performance.now()) {
2443
+ const actualValue = element.state.value || "";
2444
+ const passed = actualValue === expectedValue;
2445
+ return this.createResult(
2446
+ passed,
2447
+ element.id,
2448
+ description,
2449
+ expectedValue,
2450
+ actualValue,
2451
+ passed ? void 0 : message || `Value "${actualValue}" does not match expected "${expectedValue}"`,
2452
+ passed ? void 0 : "Type the expected value into the input",
2453
+ startTime,
2454
+ element.state
2455
+ );
2456
+ }
2457
+ /**
2458
+ * Assert element count
2459
+ */
2460
+ assertElementCount(criteria, expectedCount, targetStr, message, startTime = performance.now()) {
2461
+ const searchResponse = this.searchEngine.search(criteria);
2462
+ const actualCount = searchResponse.results.length;
2463
+ const passed = actualCount === expectedCount;
2464
+ return this.createResult(
2465
+ passed,
2466
+ targetStr,
2467
+ `${actualCount} elements matching criteria`,
2468
+ expectedCount,
2469
+ actualCount,
2470
+ passed ? void 0 : message || `Found ${actualCount} elements but expected ${expectedCount}`,
2471
+ passed ? void 0 : "Adjust search criteria or wait for elements to load",
2472
+ startTime
2473
+ );
2474
+ }
2475
+ /**
2476
+ * Assert attribute value (placeholder for DOM attribute assertions)
2477
+ */
2478
+ assertAttribute(element, attributeName, expectedValue, description, message, startTime = performance.now()) {
2479
+ let actualValue;
2480
+ switch (attributeName.toLowerCase()) {
2481
+ case "placeholder":
2482
+ actualValue = element.placeholder;
2483
+ break;
2484
+ case "title":
2485
+ actualValue = element.title;
2486
+ break;
2487
+ default:
2488
+ return this.createResult(
2489
+ false,
2490
+ element.id,
2491
+ description,
2492
+ expectedValue,
2493
+ void 0,
2494
+ `Cannot check attribute "${attributeName}" without DOM access`,
2495
+ "Use the server API to check element attributes",
2496
+ startTime,
2497
+ element.state
2498
+ );
2499
+ }
2500
+ const passed = actualValue === expectedValue;
2501
+ return this.createResult(
2502
+ passed,
2503
+ element.id,
2504
+ description,
2505
+ expectedValue,
2506
+ actualValue,
2507
+ passed ? void 0 : message || `Attribute "${attributeName}" is "${actualValue}" but expected "${expectedValue}"`,
2508
+ void 0,
2509
+ startTime,
2510
+ element.state
2511
+ );
2512
+ }
2513
+ /**
2514
+ * Assert element has CSS class
2515
+ */
2516
+ assertHasClass(element, className, description, message, startTime = performance.now()) {
2517
+ return this.createResult(
2518
+ false,
2519
+ element.id,
2520
+ description,
2521
+ className,
2522
+ void 0,
2523
+ "Cannot check CSS classes without DOM access",
2524
+ "Use the server API to check element classes",
2525
+ startTime,
2526
+ element.state
2527
+ );
2528
+ }
2529
+ /**
2530
+ * Assert CSS property value
2531
+ */
2532
+ assertCssProperty(element, propertyName, expectedValue, description, message, startTime = performance.now()) {
2533
+ const computedStyles = element.state.computedStyles;
2534
+ if (!computedStyles) {
2535
+ return this.createResult(
2536
+ false,
2537
+ element.id,
2538
+ description,
2539
+ expectedValue,
2540
+ void 0,
2541
+ "Computed styles not available",
2542
+ "Request element state with computed styles",
2543
+ startTime,
2544
+ element.state
2545
+ );
2546
+ }
2547
+ const styleKey = propertyName;
2548
+ const actualValue = computedStyles[styleKey];
2549
+ const passed = actualValue === expectedValue;
2550
+ return this.createResult(
2551
+ passed,
2552
+ element.id,
2553
+ description,
2554
+ expectedValue,
2555
+ actualValue,
2556
+ passed ? void 0 : message || `CSS property "${propertyName}" is "${actualValue}" but expected "${expectedValue}"`,
2557
+ void 0,
2558
+ startTime,
2559
+ element.state
2560
+ );
2561
+ }
2562
+ /**
2563
+ * Create an assertion result
2564
+ */
2565
+ createResult(passed, target, targetDescription, expected, actual, failureReason, suggestion, startTime = performance.now(), elementState) {
2566
+ return {
2567
+ passed,
2568
+ target,
2569
+ targetDescription,
2570
+ expected,
2571
+ actual,
2572
+ failureReason,
2573
+ suggestion: this.config.includeSuggestions ? suggestion : void 0,
2574
+ elementState,
2575
+ durationMs: performance.now() - startTime,
2576
+ timestamp: Date.now()
2577
+ };
2578
+ }
2579
+ };
2580
+
2581
+ // src/specs/executor.ts
2582
+ function resolveTarget(target) {
2583
+ switch (target.type) {
2584
+ case "elementId":
2585
+ return { idPattern: target.elementId, fuzzy: false };
2586
+ case "search":
2587
+ return target.criteria;
2588
+ }
2589
+ }
2590
+ var SpecExecutor = class {
2591
+ constructor(config) {
2592
+ this.assertionExecutor = new AssertionExecutor(config);
2593
+ }
2594
+ /**
2595
+ * Update the element registry (pass-through to AssertionExecutor).
2596
+ */
2597
+ updateElements(elements) {
2598
+ this.assertionExecutor.updateElements(elements);
2599
+ }
2600
+ /**
2601
+ * Convert a SpecAssertion to an AssertionRequest.
2602
+ */
2603
+ toAssertionRequest(assertion) {
2604
+ return {
2605
+ target: resolveTarget(assertion.target),
2606
+ type: assertion.assertionType,
2607
+ expected: assertion.expected,
2608
+ attributeName: assertion.attributeName,
2609
+ propertyName: assertion.propertyName,
2610
+ timeout: assertion.timeout,
2611
+ message: assertion.message
2612
+ };
2613
+ }
2614
+ /**
2615
+ * Evaluate a condition to determine if an assertion should be executed.
2616
+ * Returns true if the condition is met (assertion should run),
2617
+ * false if condition is not met (assertion should skip/pass).
2618
+ */
2619
+ async evaluateCondition(condition) {
2620
+ const target = resolveTarget(condition.target);
2621
+ const element = await this.assertionExecutor.findElement(target, false);
2622
+ switch (condition.type) {
2623
+ case "exists":
2624
+ return element !== null;
2625
+ case "notExists":
2626
+ return element === null;
2627
+ case "hasText": {
2628
+ if (!element) return false;
2629
+ const textContent = element.state?.textContent || element.accessibleName || element.label || element.description || "";
2630
+ return textContent.toLowerCase().includes(condition.text.toLowerCase());
2631
+ }
2632
+ default:
2633
+ return true;
2634
+ }
2635
+ }
2636
+ /**
2637
+ * Execute a single SpecAssertion.
2638
+ */
2639
+ async executeAssertion(assertion) {
2640
+ if (!assertion.enabled) {
2641
+ return {
2642
+ assertionId: assertion.id,
2643
+ severity: assertion.severity,
2644
+ category: assertion.category,
2645
+ skipped: true,
2646
+ result: null
2647
+ };
2648
+ }
2649
+ if (assertion.condition) {
2650
+ const conditionMet = await this.evaluateCondition(assertion.condition);
2651
+ if (!conditionMet) {
2652
+ return {
2653
+ assertionId: assertion.id,
2654
+ severity: assertion.severity,
2655
+ category: assertion.category,
2656
+ skipped: true,
2657
+ skipReason: "condition_not_met",
2658
+ result: null
2659
+ };
2660
+ }
2661
+ }
2662
+ const request = this.toAssertionRequest(assertion);
2663
+ const result = await this.assertionExecutor.assert(request);
2664
+ return {
2665
+ assertionId: assertion.id,
2666
+ severity: assertion.severity,
2667
+ category: assertion.category,
2668
+ skipped: false,
2669
+ result
2670
+ };
2671
+ }
2672
+ /**
2673
+ * Execute all assertions in a SpecGroup.
2674
+ */
2675
+ async executeGroup(group, options) {
2676
+ const startTime = Date.now();
2677
+ const assertionResults = [];
2678
+ let passedCount = 0;
2679
+ let failedCount = 0;
2680
+ let skippedCount = 0;
2681
+ for (const assertion of group.assertions) {
2682
+ if (shouldSkip(assertion, options)) {
2683
+ assertionResults.push({
2684
+ assertionId: assertion.id,
2685
+ groupId: group.id,
2686
+ severity: assertion.severity,
2687
+ category: assertion.category,
2688
+ skipped: true,
2689
+ result: null
2690
+ });
2691
+ skippedCount++;
2692
+ continue;
2693
+ }
2694
+ const result = await this.executeAssertion(assertion);
2695
+ result.groupId = group.id;
2696
+ assertionResults.push(result);
2697
+ if (result.skipped) {
2698
+ skippedCount++;
2699
+ } else if (result.result?.passed) {
2700
+ passedCount++;
2701
+ } else {
2702
+ failedCount++;
2703
+ if (options?.stopOnFailure) break;
2704
+ }
2705
+ }
2706
+ return {
2707
+ groupId: group.id,
2708
+ groupName: group.name,
2709
+ assertionResults,
2710
+ passedCount,
2711
+ failedCount,
2712
+ skippedCount,
2713
+ passed: failedCount === 0,
2714
+ durationMs: Date.now() - startTime,
2715
+ timestamp: Date.now()
2716
+ };
2717
+ }
2718
+ /**
2719
+ * Execute a full SpecConfig.
2720
+ */
2721
+ async execute(config, options) {
2722
+ const startTime = Date.now();
2723
+ const groupResults = [];
2724
+ for (const group of config.groups) {
2725
+ if (options?.groupIds && !options.groupIds.includes(group.id)) continue;
2726
+ const groupResult = await this.executeGroup(group, options);
2727
+ groupResults.push(groupResult);
2728
+ if (options?.stopOnFailure && !groupResult.passed) break;
2729
+ }
2730
+ const ungroupedResults = [];
2731
+ if (config.assertions) {
2732
+ for (const assertion of config.assertions) {
2733
+ if (shouldSkip(assertion, options)) {
2734
+ ungroupedResults.push({
2735
+ assertionId: assertion.id,
2736
+ severity: assertion.severity,
2737
+ category: assertion.category,
2738
+ skipped: true,
2739
+ result: null
2740
+ });
2741
+ continue;
2742
+ }
2743
+ const result = await this.executeAssertion(assertion);
2744
+ ungroupedResults.push(result);
2745
+ if (options?.stopOnFailure && !result.skipped && !result.result?.passed) break;
2746
+ }
2747
+ }
2748
+ let passedCount = 0;
2749
+ let failedCount = 0;
2750
+ let skippedCount = 0;
2751
+ for (const gr of groupResults) {
2752
+ passedCount += gr.passedCount;
2753
+ failedCount += gr.failedCount;
2754
+ skippedCount += gr.skippedCount;
2755
+ }
2756
+ for (const ur of ungroupedResults) {
2757
+ if (ur.skipped) skippedCount++;
2758
+ else if (ur.result?.passed) passedCount++;
2759
+ else failedCount++;
2760
+ }
2761
+ return {
2762
+ specVersion: config.version ?? SPEC_CONFIG_VERSION,
2763
+ groupResults,
2764
+ ungroupedResults,
2765
+ totalAssertions: passedCount + failedCount + skippedCount,
2766
+ passedCount,
2767
+ failedCount,
2768
+ skippedCount,
2769
+ passed: failedCount === 0,
2770
+ durationMs: Date.now() - startTime,
2771
+ timestamp: Date.now()
2772
+ };
2773
+ }
2774
+ };
2775
+ function shouldSkip(assertion, options) {
2776
+ if (!assertion.enabled) return true;
2777
+ if (options?.assertionIds && !options.assertionIds.includes(assertion.id)) return true;
2778
+ if (options?.categories && !options.categories.includes(assertion.category)) return true;
2779
+ if (options?.severities && !options.severities.includes(assertion.severity)) return true;
2780
+ if (options?.skipUnreviewed && !assertion.reviewed) return true;
2781
+ return false;
2782
+ }
2783
+
2784
+ export { SPEC_CONFIG_VERSION, SPEC_FILE_EXTENSION, SpecExecutor, SpecStore, VALID_ASSERTION_TYPES, VALID_SPEC_CATEGORIES, VALID_SPEC_SEVERITIES, VALID_SPEC_SOURCES, coerceAssertionType, getGlobalSpecStore, isValidAssertionType, isValidSpecCategory, isValidSpecSeverity, isValidSpecSource, migrateFromTestGeneratorOutput, migrateLegacyAssertion, migrateLegacyTarget, resetGlobalSpecStore, resolveTarget, validateSpecAssertion, validateSpecConfig, validateSpecGroup };
2785
+ //# sourceMappingURL=index.mjs.map
2786
+ //# sourceMappingURL=index.mjs.map