@rind-ui/testing 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2007 @@
1
+ import { a as mirror, i as isEnvFactory, n as UntilTimeout } from "./compose-DPLnCCnJ.mjs";
2
+ import { a as navigationLog, i as interceptNativeNavigation, n as installErrorLog, o as installAnnouncementLog, r as fakeRouter, s as recordingAnnouncer, t as domEnv } from "./dom-DZtl6G1E.mjs";
3
+ import { n as playwrightEnv, r as watchPageErrors, t as isPage } from "./playwright-C2LKzGS_.mjs";
4
+ import { accordionContract, buttonContract, checkboxContract, checkboxGroupContract, collapsibleContract, createService, fieldContract, fieldsetContract, formContract, headingContract, labelContract, linkContract, platforms, platforms as platforms$1, quirkActive, radioGroupContract, segmentedControlContract, separatorContract, separatorContractFor, switchContract, tabsContract, textFieldContract, toggleContract, toggleGroupContract, toolbarContract, withEngine, withEngine as withEngine$1 } from "@rind-ui/core";
5
+ //#region src/accordion-invariants.ts
6
+ const NAVIGATION_KEYS = /* @__PURE__ */ new Set([
7
+ "ArrowUp",
8
+ "ArrowDown",
9
+ "ArrowLeft",
10
+ "ArrowRight",
11
+ "Home",
12
+ "End"
13
+ ]);
14
+ const expandedIn = (root) => Array.from(root?.querySelectorAll("[data-scope=\"accordion\"][data-part=\"trigger\"]") ?? []).filter((t) => t.getAttribute("aria-expanded") === "true").map((t) => t.id).join(" ");
15
+ /**
16
+ * - `accordion-expanded-matches-value` (when `value` and `labels` are given): each trigger's
17
+ * `aria-expanded` equals its item's membership in the value the consumer tracks through
18
+ * `onValueChange` (`labels`: item value → trigger label), so a variant that does not report
19
+ * a close (ark#1656) fails;
20
+ * - `accordion-arrows-inert`: without `keyboardNavigation`, an arrow, Home or End key on a
21
+ * trigger moves no focus, changes no expanded item and is not prevented.
22
+ */
23
+ function accordionStepInvariants(options = {}) {
24
+ let presses = [];
25
+ const onKey = (e) => {
26
+ const t = e.target;
27
+ if (!(t instanceof HTMLElement) || !NAVIGATION_KEYS.has(e.key)) return;
28
+ if (t.getAttribute("data-scope") !== "accordion" || t.getAttribute("data-part") !== "trigger") return;
29
+ const root = t.closest("[data-scope=\"accordion\"][data-part=\"root\"]");
30
+ presses.push({
31
+ key: e.key,
32
+ target: t,
33
+ expanded: expandedIn(root),
34
+ prevented: false
35
+ });
36
+ };
37
+ const onKeyAfter = (e) => {
38
+ const p = presses.find((x) => x.target === e.target && x.key === e.key);
39
+ if (p) p.prevented = e.defaultPrevented;
40
+ };
41
+ document.addEventListener("keydown", onKey, true);
42
+ window.addEventListener("keydown", onKeyAfter);
43
+ const { value, labels } = options;
44
+ return {
45
+ invariants: [...value && labels ? [{
46
+ name: "accordion-expanded-matches-value",
47
+ check: async ({ env }) => {
48
+ const open = value();
49
+ for (const [item, label] of Object.entries(labels)) {
50
+ const t = env.part("trigger", {
51
+ role: "button",
52
+ name: label
53
+ });
54
+ if (!await t.exists()) continue;
55
+ const expanded = await t.attr("aria-expanded") === "true";
56
+ if (expanded !== open.includes(item)) return `"${label}" is ${expanded ? "expanded" : "collapsed"} but the value ${JSON.stringify(open)} ${open.includes(item) ? "contains" : "does not contain"} "${item}"`;
57
+ }
58
+ }
59
+ }] : [], {
60
+ name: "accordion-arrows-inert",
61
+ check: async ({ props }) => {
62
+ const seen = presses;
63
+ presses = [];
64
+ if (props["keyboardNavigation"] === true) return void 0;
65
+ for (const p of seen) {
66
+ const root = p.target.closest("[data-scope=\"accordion\"][data-part=\"root\"]");
67
+ if (p.prevented) return `${p.key} on a trigger was prevented without keyboardNavigation`;
68
+ if (p.target.ownerDocument.activeElement !== p.target) return `${p.key} on a trigger moved focus without keyboardNavigation`;
69
+ if (expandedIn(root) !== p.expanded) return `${p.key} on a trigger changed the expanded items without keyboardNavigation`;
70
+ }
71
+ }
72
+ }],
73
+ reset() {
74
+ presses = [];
75
+ },
76
+ dispose() {
77
+ document.removeEventListener("keydown", onKey, true);
78
+ window.removeEventListener("keydown", onKeyAfter);
79
+ }
80
+ };
81
+ }
82
+ //#endregion
83
+ //#region src/aria-snapshot.ts
84
+ /** The expected lines missing from `actual`, in order (empty when it matches). */
85
+ function missingAriaLines(actual, expected) {
86
+ const lines = (s) => s.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
87
+ const have = lines(actual);
88
+ const missing = [];
89
+ let from = 0;
90
+ for (const line of lines(expected)) {
91
+ const at = have.indexOf(line, from);
92
+ if (at === -1) missing.push(line);
93
+ else from = at + 1;
94
+ }
95
+ return missing;
96
+ }
97
+ //#endregion
98
+ //#region src/checkbox-invariants.ts
99
+ const isControl = (t) => t instanceof HTMLElement && t.getAttribute("data-scope") === "checkbox" && t.getAttribute("data-part") === "control";
100
+ /** `checkbox-enter-never-changes`: an Enter key on the Control never changes its value. */
101
+ function checkboxStepInvariants() {
102
+ let presses = [];
103
+ const onKey = (e) => {
104
+ if (e.key !== "Enter" || !isControl(e.target)) return;
105
+ presses.push({
106
+ target: e.target,
107
+ before: e.target.getAttribute("aria-checked")
108
+ });
109
+ };
110
+ document.addEventListener("keydown", onKey, true);
111
+ return {
112
+ invariants: [{
113
+ name: "checkbox-enter-never-changes",
114
+ check: async () => {
115
+ const seen = presses;
116
+ presses = [];
117
+ for (const p of seen) {
118
+ const after = p.target.getAttribute("aria-checked");
119
+ if (after !== p.before) return `Enter on the control changed aria-checked from "${p.before}" to "${after}"`;
120
+ }
121
+ }
122
+ }],
123
+ reset() {
124
+ presses = [];
125
+ },
126
+ dispose() {
127
+ document.removeEventListener("keydown", onKey, true);
128
+ }
129
+ };
130
+ }
131
+ //#endregion
132
+ //#region src/driver.ts
133
+ /** Resolves a target to its adapter by duck typing: `locator` means Playwright. */
134
+ function toEnvFactory(target) {
135
+ if (isEnvFactory(target)) return target;
136
+ if (typeof target.locator === "function") return playwrightEnv(target);
137
+ const isContainer = typeof Element !== "undefined" && target instanceof Element;
138
+ return domEnv(isContainer ? { root: target } : {});
139
+ }
140
+ /** Wraps keyboard input so horizontal arrows are mirrored in right-to-left runs. */
141
+ function directed(env, direction) {
142
+ if (direction === "ltr") return env;
143
+ const wrap = (part) => ({
144
+ ...part,
145
+ press: (key, options) => part.press(mirror(key, direction), options),
146
+ nth: (i) => wrap(part.nth(i)),
147
+ all: async () => (await part.all()).map(wrap),
148
+ scoped: (scope, inner) => wrap(part.scoped(scope, inner)),
149
+ withAttr: (name, value) => wrap(part.withAttr(name, value)),
150
+ labelled: () => wrap(part.labelled())
151
+ });
152
+ return {
153
+ ...env,
154
+ part: (name, by) => wrap(env.part(name, by)),
155
+ find: (by) => wrap(env.find(by)),
156
+ focused: () => wrap(env.focused()),
157
+ keyboard: (key, options) => env.keyboard(mirror(key, direction), options)
158
+ };
159
+ }
160
+ /** Reads every query of the contract, for failure messages. */
161
+ async function observe(contract, env) {
162
+ const out = {};
163
+ for (const [name, query] of Object.entries(contract.queries)) {
164
+ if (query.length > 1) continue;
165
+ out[name] = await query(env).catch((e) => `<${e instanceof Error ? e.message : String(e)}>`);
166
+ }
167
+ return out;
168
+ }
169
+ /** Runs one action in one modality and waits for its postcondition. */
170
+ async function runAction(contract, env, name, args, checkDone = true) {
171
+ const { modality } = env;
172
+ const action = contract.actions[name];
173
+ if (!action) throw new Error(`${contract.scope}.${name} is not an action`);
174
+ const impl = action[modality] ?? (modality === "virtual" ? action.pointer : void 0);
175
+ if (!impl) throw new Error(`${contract.scope}.${name} has no "${modality}" implementation`);
176
+ await env.markNavigations();
177
+ await impl(env, ...args);
178
+ if (!checkDone) return;
179
+ const { done } = action;
180
+ const check = typeof done === "function" ? () => done(env, ...args) : async () => {
181
+ const seen = await observe(contract, env);
182
+ return Object.entries(done).every(([q, v]) => Object.is(seen[q], v));
183
+ };
184
+ try {
185
+ await env.until(check, (ok) => ok);
186
+ } catch (e) {
187
+ const seen = await observe(contract, env);
188
+ const expected = typeof done === "function" ? "its postcondition" : JSON.stringify(done);
189
+ throw new Error(`${contract.scope}.${name} [${modality}]: expected ${expected}, observed ${JSON.stringify(seen)}${e instanceof UntilTimeout ? "" : ` (${e instanceof Error ? e.message : String(e)})`}`);
190
+ }
191
+ }
192
+ const PREFERENCE = [
193
+ "pointer",
194
+ "keyboard",
195
+ "touch"
196
+ ];
197
+ function make(contract, factory, anchor, options) {
198
+ const direction = options.direction ?? "ltr";
199
+ const envs = /* @__PURE__ */ new Map();
200
+ const envFor = (modality) => {
201
+ let env = envs.get(modality);
202
+ if (!env) {
203
+ env = directed(factory.create({
204
+ scope: contract.scope,
205
+ anchor,
206
+ modality,
207
+ ...options.platform ? { platform: options.platform } : {}
208
+ }), direction);
209
+ envs.set(modality, env);
210
+ }
211
+ return env;
212
+ };
213
+ const base = envFor(options.modality ?? "pointer");
214
+ const start = base.announcements().then((log) => log.length, () => 0);
215
+ const driver = {
216
+ announcements: async () => (await base.announcements()).slice(await start),
217
+ contract,
218
+ modality: base.modality,
219
+ env: base,
220
+ via: (modality) => make(contract, factory, anchor, {
221
+ ...options,
222
+ modality
223
+ }),
224
+ part: (name, by) => base.part(name, by)
225
+ };
226
+ for (const [name, action] of Object.entries(contract.actions)) {
227
+ const modality = options.modality ?? PREFERENCE.find((m) => m in action) ?? "pointer";
228
+ driver[name] = (...args) => runAction(contract, envFor(modality), name, args);
229
+ }
230
+ for (const [name, query] of Object.entries(contract.queries)) driver[name] = (...args) => query(base, ...args);
231
+ return driver;
232
+ }
233
+ /**
234
+ * A typed driver for one component instance, located by the contract's anchor (role and
235
+ * exact accessible name). The target picks the adapter.
236
+ */
237
+ function createDriver(contract, target, ...anchor) {
238
+ return createDriverWith(contract, target, anchor);
239
+ }
240
+ /** `createDriver` with options (modality, direction). */
241
+ function createDriverWith(contract, target, anchor, options = {}) {
242
+ const by = contract.locate(...anchor);
243
+ return make(contract, toEnvFactory(target), by, options);
244
+ }
245
+ //#endregion
246
+ //#region src/components/accordion.ts
247
+ /** A driver for the Accordion that has a trigger named `item`. */
248
+ function getAccordion(target, anchor, options) {
249
+ return createDriverWith(accordionContract, target, [anchor], options);
250
+ }
251
+ //#endregion
252
+ //#region src/components/button.ts
253
+ /** A driver for the Button named `name` (role `link` when rendered as a link). */
254
+ function getButton(target, anchor, options) {
255
+ return createDriverWith(buttonContract, target, [anchor], options);
256
+ }
257
+ //#endregion
258
+ //#region src/components/checkbox.ts
259
+ /** A driver for the Checkbox named `name`. */
260
+ function getCheckbox(target, anchor, options) {
261
+ return createDriverWith(checkboxContract, target, [anchor], options);
262
+ }
263
+ //#endregion
264
+ //#region src/components/checkbox-group.ts
265
+ /** A driver for the Checkbox Group named `name`. */
266
+ function getCheckboxGroup(target, anchor, options) {
267
+ return createDriverWith(checkboxGroupContract, target, [anchor], options);
268
+ }
269
+ //#endregion
270
+ //#region src/components/collapsible.ts
271
+ /** A driver for the Collapsible whose trigger is named `name`. */
272
+ function getCollapsible(target, anchor, options) {
273
+ return createDriverWith(collapsibleContract, target, [anchor], options);
274
+ }
275
+ //#endregion
276
+ //#region src/components/field.ts
277
+ /**
278
+ * A driver for the Field labelled `label`. `.control(getX)` builds the control's driver,
279
+ * located by the name the Field's Label gives it (driver composition, spec "Contract").
280
+ */
281
+ function getField(target, anchor, options) {
282
+ const driver = createDriverWith(fieldContract, target, [anchor], options);
283
+ return Object.assign(driver, { control(get) {
284
+ return get(target, { name: typeof anchor.label === "string" ? anchor.label : "" }, options);
285
+ } });
286
+ }
287
+ //#endregion
288
+ //#region src/components/fieldset.ts
289
+ /** A driver for the Fieldset named `name`: name, description, disabled, invalid, errors. */
290
+ function getFieldset(target, anchor, options) {
291
+ return createDriverWith(fieldsetContract, target, [anchor], options);
292
+ }
293
+ //#endregion
294
+ //#region src/components/form.ts
295
+ /** A driver for the Form named `name`: `submit`, `reset`, `validate`, and its queries. */
296
+ function getForm(target, anchor, options) {
297
+ return createDriverWith(formContract, target, [anchor], options);
298
+ }
299
+ //#endregion
300
+ //#region src/components/heading.ts
301
+ /** A driver for the heading named `name`: `level()`. */
302
+ function getHeading(target, anchor, options) {
303
+ return createDriverWith(headingContract, target, [anchor], options);
304
+ }
305
+ //#endregion
306
+ //#region src/components/label.ts
307
+ /** A driver for the Label with exactly this text: `click`, `doubleClick` and queries. */
308
+ function getLabel(target, anchor, options) {
309
+ return createDriverWith(labelContract, target, [anchor], options);
310
+ }
311
+ //#endregion
312
+ //#region src/components/link.ts
313
+ /** A driver for the Link named `name`: `follow`, `followInNewTab`, `middleClick` and queries. */
314
+ function getLink(target, anchor, options) {
315
+ return createDriverWith(linkContract, target, [anchor], options);
316
+ }
317
+ //#endregion
318
+ //#region src/components/radio-group.ts
319
+ /** A driver for the Radio Group named `name`. */
320
+ function getRadioGroup(target, anchor, options) {
321
+ return createDriverWith(radioGroupContract, target, [anchor], options);
322
+ }
323
+ //#endregion
324
+ //#region src/components/segmented-control.ts
325
+ /** A driver for the Segmented Control named `name`. */
326
+ function getSegmentedControl(target, anchor, options) {
327
+ return createDriverWith(segmentedControlContract, target, [anchor], options);
328
+ }
329
+ //#endregion
330
+ //#region src/components/separator.ts
331
+ /**
332
+ * A driver for a Separator: the one named `name`, or the one separator part inside
333
+ * `within` (a container element or a Playwright locator; default the target). `host`: the
334
+ * scope of the component that draws it (`"toolbar"` for `Toolbar.Separator`).
335
+ */
336
+ function getSeparator(target, anchor = {}, options) {
337
+ const { within, name, host } = anchor;
338
+ return createDriverWith(host === void 0 ? separatorContract : separatorContractFor(host), within ?? target, [name === void 0 ? {} : { name }], options);
339
+ }
340
+ //#endregion
341
+ //#region src/components/switch.ts
342
+ /** A driver for the Switch named `name`. */
343
+ function getSwitch(target, anchor, options) {
344
+ return createDriverWith(switchContract, target, [anchor], options);
345
+ }
346
+ //#endregion
347
+ //#region src/components/tabs.ts
348
+ /** A driver for the Tabs (tab list) named `name`. */
349
+ function getTabs(target, anchor, options) {
350
+ return createDriverWith(tabsContract, target, [anchor], options);
351
+ }
352
+ //#endregion
353
+ //#region src/components/text-field.ts
354
+ /** A driver for the Text Field named `name`: type, fill, clear, compose, blur, queries. */
355
+ function getTextField(target, anchor, options) {
356
+ return createDriverWith(textFieldContract, target, [anchor], options);
357
+ }
358
+ //#endregion
359
+ //#region src/components/toggle.ts
360
+ /** A driver for the Toggle named `name`. */
361
+ function getToggle(target, anchor, options) {
362
+ return createDriverWith(toggleContract, target, [anchor], options);
363
+ }
364
+ //#endregion
365
+ //#region src/components/toggle-group.ts
366
+ /** A driver for the Toggle Group named `name`. */
367
+ function getToggleGroup(target, anchor, options) {
368
+ return createDriverWith(toggleGroupContract, target, [anchor], options);
369
+ }
370
+ //#endregion
371
+ //#region src/components/toolbar.ts
372
+ /** A driver for the Toolbar named `name`. */
373
+ function getToolbar(target, anchor, options) {
374
+ return createDriverWith(toolbarContract, target, [anchor], options);
375
+ }
376
+ //#endregion
377
+ //#region src/form-invariants.ts
378
+ /**
379
+ * - `form-focus-only-on-attempt`: a step that is not a submit attempt (Validate, Reset)
380
+ * never moves focus into a Field (ariakit#2397, ariakit#6307);
381
+ * - `form-no-field-announcement`: an attempt announces the Form's summary only, never a
382
+ * Field's own message. `isSummary` recognises the summary (default: the English one).
383
+ */
384
+ function formStepInvariants(isSummary = (m) => m.endsWith("fields have errors")) {
385
+ let lastStep = null;
386
+ let seen = 0;
387
+ return {
388
+ invariants: [{
389
+ name: "form-focus-only-on-attempt",
390
+ check: async ({ env }) => {
391
+ const step = lastStep;
392
+ lastStep = null;
393
+ if (step !== "Validate" && step !== "Reset") return void 0;
394
+ for (const f of await env.part("root").scoped("field", "root").all()) if (await f.attr("data-focus") !== null) return `a "${step}" step moved focus into the Field "${await f.attr("data-name") ?? ""}"`;
395
+ }
396
+ }, {
397
+ name: "form-no-field-announcement",
398
+ check: async () => {
399
+ const log = installAnnouncementLog();
400
+ const added = log.slice(seen);
401
+ seen = log.length;
402
+ const field = added.find((a) => !isSummary(a.message));
403
+ return field ? `a Field announced "${field.message}" besides the Form summary` : void 0;
404
+ }
405
+ }],
406
+ track() {
407
+ const onClick = (e) => {
408
+ const name = e.target?.closest("button")?.textContent;
409
+ if (name === "Submit" || name === "Reset" || name === "Validate") lastStep = name;
410
+ };
411
+ document.addEventListener("click", onClick, true);
412
+ return () => document.removeEventListener("click", onClick, true);
413
+ },
414
+ reset() {
415
+ lastStep = null;
416
+ seen = 0;
417
+ installAnnouncementLog().length = 0;
418
+ }
419
+ };
420
+ }
421
+ //#endregion
422
+ //#region src/graph.ts
423
+ const list = (t) => t === void 0 ? [] : Array.isArray(t) ? t : [t];
424
+ /** Extracts the static graph from a machine definition, without running it. */
425
+ function toGraph(machine) {
426
+ const def = machine.def;
427
+ const nodes = {};
428
+ const edges = [];
429
+ const add = (source, event, transitions) => {
430
+ for (const t of list(transitions)) {
431
+ const tr = typeof t === "string" ? { target: t } : t;
432
+ edges.push({
433
+ source,
434
+ target: tr.target ?? null,
435
+ event,
436
+ guard: tr.guard ?? null,
437
+ actions: tr.actions ?? []
438
+ });
439
+ }
440
+ };
441
+ for (const [state, sd] of Object.entries(def.states)) {
442
+ nodes[state] = {
443
+ tags: sd.tags ?? [],
444
+ entry: sd.entry ?? [],
445
+ exit: sd.exit ?? [],
446
+ effects: sd.effects ?? []
447
+ };
448
+ for (const [event, t] of Object.entries(sd.on ?? {})) add(state, event, t);
449
+ for (const [event, t] of Object.entries(def.on ?? {})) if (!sd.on?.[event]) add(state, event, t);
450
+ for (const [delay, t] of Object.entries(sd.after ?? {})) add(state, `after:${delay}`, t);
451
+ for (const [key, ctl] of Object.entries(def.values ?? {})) for (const target of Object.keys(ctl.states ?? {})) if (target !== state) add(state, `$sync:${key}`, target);
452
+ }
453
+ for (const [prop, event] of Object.entries(def.onProps ?? {})) for (const edge of edges.filter((e) => e.event === event)) edges.push({
454
+ ...edge,
455
+ event: `$props:${prop}`
456
+ });
457
+ return {
458
+ id: def.id,
459
+ initial: def.initial,
460
+ nodes,
461
+ edges
462
+ };
463
+ }
464
+ /** The target state of an edge (internal edges stay in their source). */
465
+ const after = (edge) => edge.target ?? edge.source;
466
+ /**
467
+ * Shortest paths from the initial state covering every state, or every edge (default).
468
+ * Paths that are prefixes of other paths are dropped.
469
+ */
470
+ function paths(graph, options = {}) {
471
+ const walkable = graph.edges.filter(options.walkable ?? (() => true));
472
+ const initial = options.initial ?? graph.initial;
473
+ const to = /* @__PURE__ */ new Map([[initial, []]]);
474
+ for (const [state, path] of to) for (const edge of walkable) if (edge.source === state && !to.has(after(edge))) to.set(after(edge), [...path, edge]);
475
+ const found = options.cover === "states" ? [...to.values()] : walkable.flatMap((edge) => {
476
+ const prefix = to.get(edge.source);
477
+ return prefix ? [[...prefix, edge]] : [];
478
+ });
479
+ const isPrefix = (a, b) => a.length < b.length && a.every((e, i) => b[i] === e);
480
+ return found.filter((p, i) => p.length > 0 && !found.some((q, j) => isPrefix(p, q) || i > j && same(p, q)));
481
+ }
482
+ const same = (a, b) => a.length === b.length && a.every((e, i) => b[i] === e);
483
+ /** Edges no path covers (unreachable, or not walkable). */
484
+ function uncovered(graph, found) {
485
+ const covered = new Set(found.flat());
486
+ return graph.edges.filter((e) => !covered.has(e));
487
+ }
488
+ //#endregion
489
+ //#region src/invariants.ts
490
+ const NAME_REQUIRED = /* @__PURE__ */ new Set([
491
+ "button",
492
+ "link",
493
+ "checkbox",
494
+ "radio",
495
+ "switch",
496
+ "tab",
497
+ "menuitem",
498
+ "menuitemcheckbox",
499
+ "menuitemradio",
500
+ "option",
501
+ "treeitem",
502
+ "textbox",
503
+ "searchbox",
504
+ "combobox",
505
+ "listbox",
506
+ "slider",
507
+ "spinbutton",
508
+ "dialog",
509
+ "alertdialog",
510
+ "img",
511
+ "progressbar",
512
+ "meter",
513
+ "tree",
514
+ "grid",
515
+ "treegrid",
516
+ "region",
517
+ "form"
518
+ ]);
519
+ const exposed = (el) => !el.hidden && !el.inAriaHidden && !el.inInert;
520
+ const isTrue = (v) => v === "true";
521
+ const items = (s, part = "item") => s.elements.filter((el) => el.part === part);
522
+ /** The composite's item part (contract semantics, default `item`). */
523
+ const itemPart = (f) => f.semantics["item"] ?? "item";
524
+ /** An item's selection flag: `data-selected`, or `data-state="checked"` (radios). */
525
+ const selectedFlag = (el) => el.attrs["data-selected"] !== void 0 || el.role === "radio" && el.attrs["data-state"] === "checked";
526
+ const ids = (v) => (v ?? "").split(/\s+/).filter(Boolean);
527
+ const isOpen = (f) => f.open;
528
+ /**
529
+ * The contents that should be closed: with several triggers (an accordion), those whose
530
+ * trigger (aria-controls) is not expanded; otherwise every content while the state is closed.
531
+ */
532
+ function closedContents(f) {
533
+ const contents = partNamed(f.after, f.semantics["content"]);
534
+ const triggers = partNamed(f.after, f.semantics["trigger"]);
535
+ if (triggers.length > 1) {
536
+ const open = new Set(triggers.filter((t) => t.attrs["aria-expanded"] === "true").map((t) => t.attrs["aria-controls"]));
537
+ return contents.filter((c) => !open.has(c.attrs["id"]));
538
+ }
539
+ return isOpen(f) ? [] : contents;
540
+ }
541
+ /** At most one item is data-highlighted, and it is the oracle's highlighted key. */
542
+ function highlightChecks(f) {
543
+ const lit = items(f.after, itemPart(f)).filter((el) => el.attrs["data-highlighted"] !== void 0);
544
+ const out = lit.length > 1 ? [`${lit.length} items are data-highlighted: ${lit.map((el) => el.describe).join(", ")}`] : [];
545
+ const want = f.context?.["highlightedKey"];
546
+ if (want !== void 0 && lit.length <= 1) {
547
+ const have = lit[0]?.attrs["data-key"] ?? null;
548
+ if (have !== want) out.push(`the highlighted item is ${have === null ? "none" : `"${have}"`}, the machine's is ${want === null ? "none" : `"${String(want)}"`}`);
549
+ }
550
+ return out;
551
+ }
552
+ const anchor = (f) => f.anchorCount === 1 ? [] : [`exactly one element must match the anchor; found ${f.anchorCount}`];
553
+ const noErrors = (f) => f.errors.map((e) => `error during the step: ${e}`);
554
+ /** Every part (items included) carries the data-state the contract declares for it. */
555
+ const dataState = (f) => {
556
+ const out = [];
557
+ for (const p of f.after.parts) {
558
+ const want = f.expected(p).dataState;
559
+ if (want === void 0) continue;
560
+ const have = p.attrs["data-state"];
561
+ if (have === void 0) out.push(`${p.describe} has no data-state, expected "${want}"`);
562
+ else if (have !== want) out.push(`${p.describe} has data-state="${have}", expected "${want}"`);
563
+ }
564
+ return out;
565
+ };
566
+ /** (6) ARIA state attributes equal what the machine's state implies (contract `attrs`). */
567
+ const machineAttrs = (f) => {
568
+ const out = [];
569
+ for (const p of f.after.parts) for (const [name, want] of Object.entries(f.expected(p).attrs ?? {})) {
570
+ const have = p.attrs[name] ?? null;
571
+ if (have !== want) out.push(`${p.describe} ${name}=${JSON.stringify(have)}, expected ${JSON.stringify(want)} in ${f.state}`);
572
+ }
573
+ return out;
574
+ };
575
+ /** (1) Every element whose role requires a name has one. */
576
+ const names = (f) => f.after.elements.filter((el) => exposed(el) && el.role && NAME_REQUIRED.has(el.role) && el.name === "").map((el) => `${el.describe} (role ${el.role}) has no accessible name`);
577
+ /** (5) What a visible label/title part labels has the label's text in its name. */
578
+ const labelText = (f) => {
579
+ const labelPart = f.semantics["label"];
580
+ const label = f.after.parts.find((p) => p.part === labelPart && exposed(p));
581
+ if (!label?.id || label.text === "") return [];
582
+ const id = label.id;
583
+ return f.after.elements.filter((el) => ids(el.attrs["aria-labelledby"]).includes(id) || label.attrs["for"] === el.id).filter((el) => !el.name.includes(label.text)).map((el) => `${el.describe}'s accessible name "${el.name}" does not contain its label "${label.text}"`);
584
+ };
585
+ /** (2) Every IDREF resolves; (3) every rendered id is unique. */
586
+ const refs = (f) => [...f.after.refs.filter((r) => !r.exists).map((r) => `${r.from} ${r.attr}="${r.id}": no element has id "${r.id}"`), ...f.after.duplicateIds.map((id) => `id "${id}" is not unique in the document`)];
587
+ /** Name sources stay reachable: labelledby/describedby targets are not inert. */
588
+ const nameSourcesNotInert = (f) => f.after.refs.filter((r) => (r.attr === "aria-labelledby" || r.attr === "aria-describedby") && r.targetInInert).map((r) => `${r.from} ${r.attr} points at "${r.id}", which is inside an inert subtree`);
589
+ const CHECKED = {
590
+ true: "checked",
591
+ false: "unchecked",
592
+ mixed: "indeterminate"
593
+ };
594
+ /** Roles that support aria-selected (WAI-ARIA 1.2). */
595
+ const SELECTABLE_ROLES = /* @__PURE__ */ new Set([
596
+ "tab",
597
+ "option",
598
+ "gridcell",
599
+ "row",
600
+ "columnheader",
601
+ "rowheader",
602
+ "treeitem"
603
+ ]);
604
+ /** (6) State attributes agree with their data-* counterparts. */
605
+ const stateAttrs = (f) => {
606
+ const out = [];
607
+ const pairs = [
608
+ ["aria-disabled", "data-disabled"],
609
+ ["aria-invalid", "data-invalid"],
610
+ ["aria-selected", "data-selected"]
611
+ ];
612
+ for (const el of f.after.elements) {
613
+ if (el.attrs["data-scope"] === void 0) continue;
614
+ for (const [aria, data] of pairs) {
615
+ if (el.attrs[aria] === void 0 && el.attrs[data] === void 0) continue;
616
+ const on = isTrue(el.attrs[aria]) || aria === "aria-disabled" && el.attrs["disabled"] !== void 0;
617
+ const flagged = el.attrs[data] !== void 0;
618
+ if (flagged && !on && !el.focusable) continue;
619
+ if (aria === "aria-selected" && !SELECTABLE_ROLES.has(el.role ?? "")) continue;
620
+ if (flagged && !on && aria === "aria-invalid" && el.role === "radio" && f.after.elements.some((g) => g.role === "radiogroup" && isTrue(g.attrs["aria-invalid"]) && g.id !== null && el.within.includes(g.id))) continue;
621
+ if (on !== flagged) out.push(`${el.describe}: ${aria}="${el.attrs[aria] ?? ""}" disagrees with ${data}`);
622
+ }
623
+ const ds = el.attrs["data-state"];
624
+ const expanded = el.attrs["aria-expanded"];
625
+ if (expanded !== void 0 && (ds === "open" || ds === "closed") && isTrue(expanded) !== (ds === "open")) out.push(`${el.describe}: aria-expanded="${expanded}" disagrees with data-state="${ds}"`);
626
+ const pressedAttr = el.attrs["aria-pressed"];
627
+ if (pressedAttr !== void 0 && (ds === "on" || ds === "off") && isTrue(pressedAttr) !== (ds === "on")) out.push(`${el.describe}: aria-pressed="${pressedAttr}" disagrees with data-state="${ds}"`);
628
+ const checked = el.attrs["aria-checked"];
629
+ if (checked !== void 0 && ds !== void 0 && Object.values(CHECKED).includes(ds) && CHECKED[checked] !== ds) out.push(`${el.describe}: aria-checked="${checked}" disagrees with data-state="${ds}"`);
630
+ }
631
+ return out;
632
+ };
633
+ /** (10) Focus is never inside aria-hidden or inert; nothing focusable is aria-hidden. */
634
+ const hiddenFocus = (f) => {
635
+ const out = [];
636
+ const focused = f.after.focus.element;
637
+ if (focused?.inAriaHidden) out.push(`focus is on ${focused.describe}, inside aria-hidden`);
638
+ if (focused?.inInert) out.push(`focus is on ${focused.describe}, inside inert`);
639
+ for (const el of f.after.elements) {
640
+ const formInput = el.attrs["data-scope"] !== void 0 && el.attrs["data-part"] === "hidden-input" && el.attrs["tabindex"] === "-1";
641
+ if (el.focusable && el.inAriaHidden && !el.hidden && !formInput) out.push(`${el.describe} is focusable inside aria-hidden`);
642
+ }
643
+ return out;
644
+ };
645
+ /**
646
+ * (11) Focus that was inside the component stays inside it — never on body. Moving to
647
+ * another element is leaving (Tab out) when the machine took a transition to another state
648
+ * (focused → idle); without one, the component lost focus.
649
+ */
650
+ const focusKept = (f) => f.before?.focus.inInstance && !f.after.focus.inInstance && (f.after.focus.onBody || f.from === null || f.from === f.state) ? [`focus left the component (now ${f.after.focus.onBody ? "<body>" : f.after.focus.element?.describe})`] : [];
651
+ /** (23) No live region of its own unless the contract declares `live-region`. */
652
+ const liveRegions = (f) => f.traits.includes("live-region") ? [] : f.after.liveRegions.map((r) => `${r} is a live region; announce through the Announcer`);
653
+ /**
654
+ * html/body never hidden; what the component added outside its parts (html, body and
655
+ * body's other children) is gone once it is back in its initial state.
656
+ */
657
+ const documentClean = (f) => {
658
+ const out = [];
659
+ for (const [tag, attrs] of [["html", f.after.html], ["body", f.after.body]]) {
660
+ if (attrs["aria-hidden"] !== void 0) out.push(`<${tag}> has aria-hidden`);
661
+ if (attrs["inert"] !== void 0) out.push(`<${tag}> is inert`);
662
+ }
663
+ if (!f.atInitial) return out;
664
+ const compare = (where, now, then) => {
665
+ for (const key of [
666
+ "aria-hidden",
667
+ "inert",
668
+ "data-rind-scroll-locked"
669
+ ]) if ((now[key] ?? null) !== (then[key] ?? null)) out.push(`${where} ${key}="${now[key] ?? ""}" was not restored to "${then[key] ?? ""}"`);
670
+ const declarations = (css) => new Map((css ?? "").split(";").map((d) => d.split(":").map((x) => x.trim())).filter(([k]) => k !== "").map(([k, v]) => [k, v ?? ""]));
671
+ const nowStyle = declarations(now["style"]);
672
+ const thenStyle = declarations(then["style"]);
673
+ for (const prop of /* @__PURE__ */ new Set([...nowStyle.keys(), ...thenStyle.keys()])) if (nowStyle.get(prop) !== thenStyle.get(prop)) out.push(`${where} style ${prop}: "${nowStyle.get(prop) ?? ""}" was not restored to "${thenStyle.get(prop) ?? ""}"`);
674
+ };
675
+ compare("<html>", f.after.html, f.baseline.html);
676
+ compare("<body>", f.after.body, f.baseline.body);
677
+ for (const [child, then] of Object.entries(f.baseline.outside)) {
678
+ const now = f.after.outside[child];
679
+ if (now) compare(child, now, then);
680
+ }
681
+ return out;
682
+ };
683
+ /** Name and description are never identical (no double reading). */
684
+ const nameNotDescription = (f) => f.after.elements.filter((el) => exposed(el) && el.name !== "" && el.name === el.description).map((el) => `${el.describe}'s accessible name and description are both "${el.name}"`);
685
+ /** (12) No ring after a pointer step; the focused or highlighted part has it after a key. */
686
+ const focusVisibleModality = (f) => {
687
+ const out = [];
688
+ if (f.modality === "pointer" || f.modality === "touch") {
689
+ for (const p of f.after.parts) if (p.attrs["data-focus-visible"] !== void 0) out.push(`${p.describe} has data-focus-visible after a ${f.modality} step`);
690
+ } else if (f.modality === "keyboard") {
691
+ const focused = f.after.focus.element;
692
+ const targets = [...focused?.part ? [focused] : [], ...f.after.parts.filter((p) => p.attrs["data-highlighted"] !== void 0)];
693
+ for (const t of targets) if (t.attrs["data-focus-visible"] === void 0) out.push(`${t.describe} lacks data-focus-visible after a keyboard step`);
694
+ }
695
+ return out;
696
+ };
697
+ const genericInvariants = {
698
+ anchor,
699
+ "no-errors": noErrors,
700
+ "data-state": dataState,
701
+ "machine-attrs": machineAttrs,
702
+ names,
703
+ "label-text": labelText,
704
+ refs,
705
+ "name-sources-not-inert": nameSourcesNotInert,
706
+ "state-attrs": stateAttrs,
707
+ "hidden-focus": hiddenFocus,
708
+ "focus-kept": focusKept,
709
+ "live-regions": liveRegions,
710
+ "document-clean": documentClean,
711
+ "name-not-description": nameNotDescription,
712
+ "focus-visible-modality": focusVisibleModality
713
+ };
714
+ const partNamed = (s, name) => name === void 0 ? [] : s.parts.filter((p) => p.part === name);
715
+ const traitInvariants = {
716
+ /**
717
+ * (field-control) Inside a Field, the control is named by the Field's Label, described by
718
+ * exactly the Field parts that are rendered, aria-invalid exactly when the Field displays
719
+ * invalid, and disabled / read-only / required as the Field says.
720
+ */
721
+ /**
722
+ * hidden-form-input: the input mirrors the oracle's value as properties, is hidden from
723
+ * AT and never focused, and dispatches one `change` per user change, no `click` ever.
724
+ */
725
+ "form-associated": (f) => {
726
+ const out = [];
727
+ if (!f.formInput) return out;
728
+ const multiple = f.formInput.multiple === true;
729
+ const inputs = f.after.formInputs.filter((i) => !i.inParent);
730
+ if (!multiple && inputs.length !== 1) return [`${inputs.length} hidden inputs rendered; expected exactly one`];
731
+ for (const input of inputs) {
732
+ const want = f.formInput.expected(input);
733
+ for (const key of [
734
+ "checked",
735
+ "indeterminate",
736
+ "value"
737
+ ]) if (want[key] !== void 0 && input[key] !== want[key]) out.push(`${input.describe} ${key} is ${String(input[key])}, expected ${String(want[key])}`);
738
+ if (input.ariaHidden !== "true") out.push(`${input.describe} is not aria-hidden`);
739
+ if (input.tabIndex !== -1) out.push(`${input.describe} has tabIndex ${input.tabIndex}`);
740
+ if (input.focused) out.push(`${input.describe} has focus`);
741
+ if (input.clicks > 0) out.push(`${input.describe} received ${input.clicks} click events (a synthetic click reaches ancestors)`);
742
+ }
743
+ const sum = (list) => list.filter((i) => !i.inParent).reduce((n, i) => n + i.changes, 0);
744
+ const changes = sum(f.after.formInputs) - sum(f.baseline.formInputs);
745
+ if (changes !== f.formInput.userChanges) out.push(`the hidden input${multiple ? "s" : ""} dispatched ${changes} change events for ${f.formInput.userChanges} user changes`);
746
+ return out;
747
+ },
748
+ "field-associated": (f) => {
749
+ const field = f.after.field;
750
+ if (!field) return [];
751
+ const label = field.label;
752
+ const control = f.after.parts.find((p) => label?.for != null && p.id === label.for) ?? f.after.parts.find((p) => label && p.attrs["aria-labelledby"]?.split(" ").includes(label.id)) ?? f.after.parts.find((p) => p.focusable);
753
+ if (!control) return [];
754
+ const out = [];
755
+ if (label && control.name !== label.text) out.push(`${control.describe} is named "${control.name}", not by the Field's Label "${label.text}"`);
756
+ const described = (control.attrs["aria-describedby"] ?? "").split(/\s+/).filter((id) => id.startsWith("field-"));
757
+ const expected = [...field.partIds].sort();
758
+ if (JSON.stringify([...described].sort()) !== JSON.stringify(expected)) out.push(`${control.describe} aria-describedby lists [${described}], the rendered Field parts are [${expected}]`);
759
+ const invalid = field.attrs["data-invalid"] !== void 0;
760
+ if (control.role !== "button" && isTrue(control.attrs["aria-invalid"]) !== invalid) out.push(`${control.describe} aria-invalid disagrees with the Field's data-invalid (${invalid})`);
761
+ const has = (name, aria) => control.attrs[name] !== void 0 || isTrue(control.attrs[aria]);
762
+ for (const [data, attr, aria] of [
763
+ [
764
+ "data-disabled",
765
+ "disabled",
766
+ "aria-disabled"
767
+ ],
768
+ [
769
+ "data-readonly",
770
+ "readonly",
771
+ "aria-readonly"
772
+ ],
773
+ [
774
+ "data-required",
775
+ "required",
776
+ "aria-required"
777
+ ]
778
+ ]) if (field.attrs[data] !== void 0 !== has(attr, aria)) out.push(`${control.describe} ${attr} disagrees with the Field's ${data}`);
779
+ return out;
780
+ },
781
+ /** (30) The trigger mirrors open state; content is gone, hidden or until-found when closed. */
782
+ disclosure: (f) => {
783
+ const out = [];
784
+ const triggers = partNamed(f.after, f.semantics["trigger"]);
785
+ if (triggers.length > 1) {
786
+ const contents = partNamed(f.after, f.semantics["content"]);
787
+ for (const t of triggers) {
788
+ const id = t.attrs["aria-controls"];
789
+ const c = id === void 0 ? void 0 : contents.find((x) => x.attrs["id"] === id);
790
+ if (!c) continue;
791
+ const shown = !c.hidden && c.attrs["hidden"] !== "until-found";
792
+ if (t.attrs["aria-expanded"] === "false" && shown) out.push(`${c.describe} is still visible while ${t.describe} is collapsed`);
793
+ if (t.attrs["aria-expanded"] === "true" && !shown) out.push(`${c.describe} is hidden while ${t.describe} is expanded`);
794
+ }
795
+ return out;
796
+ }
797
+ for (const t of triggers) if (t.attrs["aria-expanded"] !== String(isOpen(f))) out.push(`${t.describe} aria-expanded="${t.attrs["aria-expanded"]}" but the state is ${f.state}`);
798
+ if (!isOpen(f)) {
799
+ for (const c of partNamed(f.after, f.semantics["content"])) if (!c.hidden && c.attrs["hidden"] !== "until-found") out.push(`${c.describe} is still visible while ${f.state}`);
800
+ }
801
+ return out;
802
+ },
803
+ /** Focus is never on body while a layer is open. */
804
+ layer: (f) => isOpen(f) && f.after.focus.onBody ? ["focus is on <body> while the layer is open"] : [],
805
+ /** (13) After closing, focus is on the trigger or the declared final-focus part. */
806
+ "restores-focus": (f) => {
807
+ const target = f.semantics["finalFocus"] ?? f.semantics["trigger"];
808
+ return f.from !== null && f.from !== f.state && !isOpen(f) && f.after.focus.part !== target ? [`after closing, focus is on ${f.after.focus.element?.describe ?? "<body>"}, expected the ${target} part`] : [];
809
+ },
810
+ /**
811
+ * While open: everything outside the layer that existed before (and is not kept visible by
812
+ * the keep-visible rule) is inert, focus is inside, the page is scroll-locked, and <body>
813
+ * has no pointer-events style. Closed: unlocked (the rest is document-clean's).
814
+ */
815
+ modal: (f) => {
816
+ const out = [];
817
+ const locked = f.after.html["data-rind-scroll-locked"] !== void 0 || f.after.body["data-rind-scroll-locked"] !== void 0;
818
+ if (/pointer-events/.test(f.after.body["style"] ?? "")) out.push("<body> has a pointer-events style");
819
+ if (!isOpen(f)) {
820
+ if (locked) out.push("the page is still scroll-locked after closing");
821
+ return out;
822
+ }
823
+ for (const [sibling, attrs] of Object.entries(f.after.outside)) {
824
+ if (!(sibling in f.baseline.outside)) continue;
825
+ if (attrs["data-rind-kept"] !== void 0 || attrs["inert"] !== void 0) continue;
826
+ out.push(`${sibling} is outside the open modal layer but not inert`);
827
+ }
828
+ if (!f.after.focus.inInstance) out.push(`focus is on ${f.after.focus.element?.describe ?? "<body>"}, outside the open modal layer`);
829
+ if (!locked) out.push("the page is not scroll-locked while the modal layer is open");
830
+ return out;
831
+ },
832
+ /**
833
+ * Closed content still mounted carries data-state="closed" and has a running exit
834
+ * animation; once none runs it must be gone (the runner waits for that first).
835
+ */
836
+ presence: (f) => {
837
+ const out = [];
838
+ for (const c of closedContents(f)) {
839
+ if (c.hidden && c.attrs["hidden"] !== void 0) continue;
840
+ if (c.attrs["data-state"] !== "closed") out.push(`${c.describe} is mounted while closed without data-state="closed" (running animations: ${c.animations})`);
841
+ if (c.animations === 0) out.push(`${c.describe} is still mounted after its exit animations finished (running animations: 0)`);
842
+ }
843
+ return out;
844
+ },
845
+ /**
846
+ * Anchored popups: focus enters the popup only after its first placement; in a real
847
+ * browser, the placed popup lies inside the visual viewport, on the side `data-side`
848
+ * reports (not over its anchor on that axis), and a centred arrow points at the anchor.
849
+ * Without layout (jsdom) only the focus rule runs.
850
+ */
851
+ anchored: (f) => {
852
+ const pos = f.after.parts.find((p) => p.part === "positioner");
853
+ if (!pos) return [];
854
+ const out = [];
855
+ const placing = pos.attrs["data-placing"] !== void 0;
856
+ const focused = f.after.focus.element;
857
+ if (placing && focused && pos.id && (focused.id === pos.id || focused.within.includes(pos.id))) out.push(`focus entered ${pos.describe} before its first placement`);
858
+ if (placing || !f.after.viewport.layout || pos.hidden) return out;
859
+ const style = (name) => new RegExp(`${name}:\\s*([^;]*)`).exec(pos.attrs["style"] ?? "")?.[1]?.trim() ?? "";
860
+ const [pt = 0, pr = pt, pb = pt, pl = pr] = style("--rind-collision-padding").split(/\s+/).filter(Boolean).map((x) => Number.parseFloat(x));
861
+ const vp = f.after.viewport;
862
+ const v = {
863
+ x: vp.x + pl,
864
+ y: vp.y + pt,
865
+ width: vp.width - pl - pr,
866
+ height: vp.height - pt - pb
867
+ };
868
+ const r = pos.rect;
869
+ const edges = [
870
+ [
871
+ "top",
872
+ v.y - r.y,
873
+ pt
874
+ ],
875
+ [
876
+ "left",
877
+ v.x - r.x,
878
+ pl
879
+ ],
880
+ [
881
+ "bottom",
882
+ r.y + r.height - (v.y + v.height),
883
+ pb
884
+ ],
885
+ [
886
+ "right",
887
+ r.x + r.width - (v.x + v.width),
888
+ pr
889
+ ]
890
+ ];
891
+ const side = pos.attrs["data-side"] ?? "?";
892
+ for (const [edge, over, padding] of edges) {
893
+ if (over <= .5) continue;
894
+ const past = over - padding;
895
+ out.push(past > .5 ? `${pos.describe} (side ${side}) overflows the viewport's ${edge} edge by ${Math.round(past)} px (collision padding ${padding} px)` : `${pos.describe} (side ${side}) is inside the ${edge} collision padding (${padding} px) by ${Math.round(over)} px`);
896
+ }
897
+ const anchorId = style("--rind-anchor-id").replace(/^"|"$/g, "");
898
+ if (anchorId === "") return out;
899
+ const anchor = f.after.parts.find((p) => p.id === anchorId && !p.hidden);
900
+ if (!anchor || pos.attrs["data-anchor-hidden"] !== void 0) return out;
901
+ const a = anchor.rect;
902
+ if (side === "bottom" && r.y < a.y + a.height - .5 || side === "top" && r.y + r.height > a.y + .5 || side === "right" && r.x < a.x + a.width - .5 || side === "left" && r.x + r.width > a.x + .5) out.push(`${pos.describe} is not on the ${side} of ${anchor.describe}`);
903
+ const arrow = f.after.parts.find((p) => p.part === "arrow" && !p.hidden);
904
+ if (arrow && arrow.attrs["data-uncentered"] === void 0) {
905
+ const vertical = side === "top" || side === "bottom";
906
+ const tip = vertical ? arrow.rect.x + arrow.rect.width / 2 : arrow.rect.y + arrow.rect.height / 2;
907
+ const [from, to] = vertical ? [a.x, a.x + a.width] : [a.y, a.y + a.height];
908
+ if (tip < from - .5 || tip > to + .5) out.push(`${arrow.describe} does not point at ${anchor.describe}`);
909
+ }
910
+ return out;
911
+ },
912
+ /** (8) A roving composite is one Tab stop. */
913
+ "composite-roving": (f) => {
914
+ const list = items(f.after, itemPart(f)).filter(exposed);
915
+ const stops = list.filter((el) => el.attrs["tabindex"] === "0").length;
916
+ const container = f.after.parts.some((p) => p.part !== itemPart(f) && p.attrs["tabindex"] === "0");
917
+ const out = list.length > 0 && stops !== 1 && !(stops === 0 && container) ? [`${stops} items have tabindex="0"; expected exactly 1`] : [];
918
+ if (f.before?.focus.inInstance && f.after.focus.onBody) out.push("focus fell to <body> after the step (the focused item was removed?)");
919
+ return [...out, ...highlightChecks(f)];
920
+ },
921
+ /** (8, 9) Only the input or container is tabbable; activedescendant points into the popup. */
922
+ "composite-activedescendant": (f) => {
923
+ const out = [...highlightChecks(f)];
924
+ out.push(...items(f.after, itemPart(f)).filter((el) => el.focusable && el.attrs["tabindex"] !== "-1").map((el) => `${el.describe} is tabbable; only the input or container may be`));
925
+ for (const el of f.after.elements) {
926
+ const id = el.attrs["aria-activedescendant"];
927
+ if (!id) continue;
928
+ const target = f.after.elements.find((e) => e.id === id);
929
+ if (!target) {
930
+ out.push(`${el.describe} aria-activedescendant="${id}" is not a rendered item`);
931
+ continue;
932
+ }
933
+ if (target.attrs["data-highlighted"] === void 0) out.push(`aria-activedescendant points at ${target.describe}, which is not data-highlighted`);
934
+ const popups = ids(el.attrs["aria-controls"]);
935
+ if (popups.length > 0 && !popups.some((p) => target.within.includes(p))) out.push(`aria-activedescendant points at ${target.describe}, outside the controlled popup`);
936
+ }
937
+ return out;
938
+ },
939
+ /** Explicit selection state on every item; it follows the machine's value, not highlight. */
940
+ selectable: (f) => {
941
+ const out = [];
942
+ const list = items(f.after, itemPart(f)).filter(exposed);
943
+ for (const el of list) {
944
+ const v = el.attrs["aria-selected"] ?? el.attrs["aria-checked"];
945
+ if (v !== "true" && v !== "false") out.push(`${el.describe} has no explicit aria-selected/aria-checked`);
946
+ if (isTrue(v) !== selectedFlag(el)) out.push(`${el.describe}: selection state disagrees with data-selected`);
947
+ }
948
+ const multi = f.after.elements.some((el) => isTrue(el.attrs["aria-multiselectable"]));
949
+ const selected = list.filter((el) => isTrue(el.attrs["aria-selected"] ?? el.attrs["aria-checked"]));
950
+ if (!multi && selected.length > 1) out.push(`${selected.length} items are selected in single selection`);
951
+ const wasSelected = new Set(items(f.before ?? f.after, itemPart(f)).filter((el) => isTrue(el.attrs["aria-selected"] ?? el.attrs["aria-checked"])).map((el) => el.attrs["data-key"] ?? el.describe));
952
+ for (const el of selected) if (isTrue(el.attrs["aria-disabled"]) && !wasSelected.has(el.attrs["data-key"] ?? el.describe)) out.push(`${el.describe} is disabled but the step added it to the selection`);
953
+ const itemValue = (el) => el.attrs["data-value"] ?? el.attrs["data-key"];
954
+ const value = f.values["value"];
955
+ if (value !== void 0 && value !== "all" && list.every((el) => itemValue(el) !== void 0)) {
956
+ const rendered = new Set(list.map((el) => itemValue(el)));
957
+ const want = new Set((Array.isArray(value) ? value : [value]).map(String).filter((v) => rendered.has(v)));
958
+ const have = new Set(selected.map((el) => itemValue(el) ?? ""));
959
+ if (want.size !== have.size || [...want].some((v) => !have.has(v))) out.push(`selected items [${[...have].join(", ")}] differ from the machine's value [${[...want].join(", ")}]`);
960
+ }
961
+ return out;
962
+ },
963
+ /** aria-posinset within [1, setsize], unique and increasing in visible order, per set. */
964
+ "set-metadata": (f) => {
965
+ const out = [];
966
+ const groups = /* @__PURE__ */ new Map();
967
+ for (const el of items(f.after, itemPart(f))) {
968
+ if (!exposed(el) || el.attrs["aria-posinset"] === void 0) continue;
969
+ groups.set(el.group, [...groups.get(el.group) ?? [], el]);
970
+ }
971
+ for (const list of groups.values()) {
972
+ let previous = 0;
973
+ const seen = /* @__PURE__ */ new Set();
974
+ for (const el of list) {
975
+ const pos = Number(el.attrs["aria-posinset"]);
976
+ const size = Number(el.attrs["aria-setsize"] ?? list.length);
977
+ if (!(pos >= 1 && (size === -1 || pos <= size))) out.push(`${el.describe} aria-posinset=${pos} outside [1, ${size}]`);
978
+ if (seen.has(pos)) out.push(`${el.describe} repeats aria-posinset=${pos}`);
979
+ else if (pos < previous) out.push(`${el.describe} aria-posinset=${pos} comes after ${previous} in visible order`);
980
+ seen.add(pos);
981
+ previous = Math.max(previous, pos);
982
+ }
983
+ }
984
+ if (f.collectionSize !== void 0) for (const el of items(f.after, itemPart(f)).filter(exposed)) {
985
+ const size = el.attrs["aria-setsize"];
986
+ if (size !== void 0 && el.attrs["aria-level"] === void 0 && Number(size) !== f.collectionSize) out.push(`${el.describe} aria-setsize=${size}, the collection has ${f.collectionSize} items`);
987
+ }
988
+ return out;
989
+ },
990
+ /**
991
+ * aria-valuenow equals the machine's value in the same step; a numeric aria-valuetext
992
+ * equals it too; a `value-text` part shows aria-valuetext (or the value).
993
+ */
994
+ valued: (f) => {
995
+ const value = f.values["value"];
996
+ if (typeof value !== "number") return [];
997
+ const out = [];
998
+ let valuetext;
999
+ for (const el of f.after.elements) {
1000
+ const now = el.attrs["aria-valuenow"];
1001
+ if (now !== void 0 && Number(now) !== value) out.push(`${el.describe} aria-valuenow="${now}", machine value ${value}`);
1002
+ const text = el.attrs["aria-valuetext"];
1003
+ if (text === void 0) continue;
1004
+ valuetext = text;
1005
+ if (text.trim() === "") out.push(`${el.describe} has an empty aria-valuetext`);
1006
+ else if (/^-?\d+(\.\d+)?$/.test(text.trim()) && Number(text) !== value) out.push(`${el.describe} aria-valuetext="${text}", machine value ${value}`);
1007
+ }
1008
+ for (const p of f.after.parts.filter((x) => x.part === "value-text" && exposed(x))) {
1009
+ const want = valuetext ?? String(value);
1010
+ if (!p.text.includes(want)) out.push(`${p.describe} shows "${p.text}", expected "${want}"`);
1011
+ }
1012
+ return out;
1013
+ },
1014
+ /** Live regions exist before their first message and are never hidden from AT. */
1015
+ "live-region": (f) => {
1016
+ const out = f.after.elements.filter((el) => f.after.liveRegions.includes(el.describe) && (el.inAriaHidden || el.inInert)).map((el) => `${el.describe} is a live region inside aria-hidden or inert`);
1017
+ for (const region of f.after.liveRegions) if (!f.baseline.liveRegions.includes(region)) out.push(`${region} did not exist before its first message`);
1018
+ return out;
1019
+ }
1020
+ };
1021
+ /**
1022
+ * (AT 8) The result count is a status message on every platform. An item announcement (the
1023
+ * contract's focus announcement, or any item's accessible name) is made only where VoiceOver
1024
+ * ignores aria-activedescendant (quirk vo-activedescendant: Apple with WebKit): exactly one
1025
+ * per highlight change, for the new item; anywhere else it doubles the screen reader's own
1026
+ * speech. A declared section announcement is expected on entering a section where VoiceOver
1027
+ * is silent on sections (vo-section-entry: every Apple platform) and never elsewhere. Other
1028
+ * messages are not this invariant's business.
1029
+ */
1030
+ const announcementParity = (f) => {
1031
+ const a = f.announcements;
1032
+ if (!a || !f.observed || !f.before || !f.platform) return [];
1033
+ const said = (f.stepAnnouncements ?? []).map((x) => x.message);
1034
+ const highlightedEl = (s) => s.elements.find((e) => e.attrs["data-highlighted"] !== void 0);
1035
+ const highlighted = (s) => highlightedEl(s)?.id ?? null;
1036
+ /** The section holding the highlighted item: the set its item belongs to. */
1037
+ const section = (s) => highlightedEl(s)?.group ?? null;
1038
+ const count = (s) => items(s).filter(exposed).length;
1039
+ const observed = f.observed;
1040
+ const focusMessage = a.focusAnnouncement(observed);
1041
+ const countMessage = a.countAnnouncement(observed);
1042
+ const sectionMessage = a.sectionAnnouncement?.(observed);
1043
+ const highlightChanged = highlighted(f.after) !== null && highlighted(f.after) !== highlighted(f.before);
1044
+ const sectionChanged = highlightChanged && section(f.after) !== null && section(f.after) !== section(f.before);
1045
+ const resultsChanged = count(f.after) > 0 && count(f.after) !== count(f.before);
1046
+ const itemNames = new Set(items(f.after, itemPart(f)).map((e) => e.name).filter((n) => n !== ""));
1047
+ const isItemAnnouncement = (m) => m === focusMessage || itemNames.has(m);
1048
+ const out = [];
1049
+ if (resultsChanged && !said.includes(countMessage)) out.push(`expected the count announcement "${countMessage}", heard ${JSON.stringify(said)}`);
1050
+ if (sectionMessage !== void 0 && sectionChanged) {
1051
+ const heard = said.includes(sectionMessage);
1052
+ if (quirkActive("vo-section-entry", { platform: f.platform })) {
1053
+ if (!heard) out.push(`expected the section announcement "${sectionMessage}", heard ${JSON.stringify(said)}`);
1054
+ } else if (heard) out.push(`announced the section "${sectionMessage}" where the screen reader speaks it`);
1055
+ }
1056
+ if (!highlightChanged) return out;
1057
+ const itemSpeech = said.filter(isItemAnnouncement);
1058
+ if (quirkActive("vo-activedescendant", { platform: f.platform })) {
1059
+ if (itemSpeech.length !== 1 || itemSpeech[0] !== focusMessage) out.push(`expected exactly one item announcement, the focus announcement "${focusMessage}"; heard ${JSON.stringify(itemSpeech)}`);
1060
+ } else if (itemSpeech.length > 0) out.push(`announced ${JSON.stringify(itemSpeech)} for the highlighted item where the screen reader already speaks it (double speech)`);
1061
+ return out;
1062
+ };
1063
+ /** Runs every generic invariant plus those switched on by the contract's traits. */
1064
+ function checkGeneric(facts) {
1065
+ const out = [];
1066
+ const exempt = facts.exempt;
1067
+ const keep = (id, messages) => exempt ? messages.filter((m) => {
1068
+ const part = /\[data-part=([^\]]+)\]/.exec(m)?.[1];
1069
+ return part === void 0 || !exempt(id, part);
1070
+ }) : messages;
1071
+ for (const [id, check] of Object.entries(genericInvariants)) out.push(...keep(id, check?.(facts) ?? []));
1072
+ const traits = new Set(facts.traits);
1073
+ if (traits.has("modal")) {
1074
+ traits.add("layer");
1075
+ traits.add("restores-focus");
1076
+ }
1077
+ for (const trait of traits) out.push(...keep(trait, traitInvariants[trait]?.(facts) ?? []));
1078
+ if (facts.traits.includes("composite-activedescendant")) out.push(...keep("announcement-parity", announcementParity(facts)).map((m) => `announcement-parity: ${m}`));
1079
+ return out;
1080
+ }
1081
+ /** The anchored layout checks (trait `anchored`), for a single snapshot outside the runner. */
1082
+ const layoutInvariant = (f) => traitInvariants.anchored?.(f) ?? [];
1083
+ //#endregion
1084
+ //#region src/model.ts
1085
+ /** Contracts whose jsdom limitation was already reported in this run. */
1086
+ const layoutNoted = /* @__PURE__ */ new Set();
1087
+ const simulatedNoted = /* @__PURE__ */ new Set();
1088
+ /** VoiceOver in Chrome on macOS: the Apple preset with the Blink engine. */
1089
+ const appleBlink = withEngine$1(platforms$1.apple, "blink");
1090
+ let run;
1091
+ /** The run `setup` is rendering for (platform, locale, direction, modality). */
1092
+ const currentRun = () => run;
1093
+ function mappingOf(contract, edge) {
1094
+ if (edge.event.startsWith("after:")) return { kind: "delay" };
1095
+ const declared = contract.events[edge.event];
1096
+ const m = typeof declared === "object" && "from" in declared ? declared.from[edge.source] : declared;
1097
+ if (m === void 0) return void 0;
1098
+ if (typeof m === "string") return {
1099
+ kind: "action",
1100
+ action: m
1101
+ };
1102
+ if ("skip" in m) return {
1103
+ kind: "skip",
1104
+ reason: m.skip
1105
+ };
1106
+ if ("props" in m) return {
1107
+ kind: "props",
1108
+ props: m.props
1109
+ };
1110
+ return {
1111
+ kind: "action",
1112
+ action: m.action,
1113
+ ...m.args ? { args: m.args } : {},
1114
+ event: m.event
1115
+ };
1116
+ }
1117
+ const walkable = (contract, canRerender) => (edge) => {
1118
+ const m = mappingOf(contract, edge);
1119
+ return m !== void 0 && m.kind !== "skip" && (m.kind !== "props" || canRerender);
1120
+ };
1121
+ const guardText = (g) => g === null ? "" : typeof g === "string" ? g : "not" in g ? `!${guardText(g.not)}` : "and" in g ? g.and.map(guardText).join(" && ") : g.or.map(guardText).join(" || ");
1122
+ const edgeLabel = (e) => `—${e.event}${e.guard ? `[${guardText(e.guard)}]` : ""}→ ${e.target ?? e.source}`;
1123
+ /** `closed —OPEN→ open —ESCAPE[closeOnEscape]→ closed`. */
1124
+ const label = (edges) => edges.reduce((out, e) => `${out} ${edgeLabel(e)}`, edges[0]?.source ?? "");
1125
+ /** The paths `testMachine` walks, for custom runners and for printing. */
1126
+ function machinePaths(contract, coverage = "transitions", graph = toGraph(contract.machine), canRerender = true) {
1127
+ return paths(graph, {
1128
+ cover: coverage,
1129
+ walkable: walkable(contract, canRerender)
1130
+ }).map((edges) => ({
1131
+ name: label(edges),
1132
+ edges
1133
+ }));
1134
+ }
1135
+ const modalitiesOf = (action) => {
1136
+ const out = [
1137
+ "pointer",
1138
+ "keyboard",
1139
+ "touch"
1140
+ ].filter((m) => m in action);
1141
+ return "pointer" in action ? [...out, "virtual"] : out;
1142
+ };
1143
+ /** The modality a step runs in: the path's, or the action's keyboard twin, then pointer. */
1144
+ /** The item count of a `collection` prop (a rind-ui Collection has a numeric `size`). */
1145
+ const collectionSizeOf = (props) => {
1146
+ const c = props?.collection;
1147
+ return typeof c?.size === "number" ? { collectionSize: c.size } : {};
1148
+ };
1149
+ const stepModality = (action, modality) => {
1150
+ const own = modalitiesOf(action);
1151
+ if (own.includes(modality)) return modality;
1152
+ return [
1153
+ "keyboard",
1154
+ "pointer",
1155
+ "touch"
1156
+ ].find((m) => own.includes(m)) ?? modality;
1157
+ };
1158
+ /**
1159
+ * What the contract expects of each part element in `state`: data-state (one value for every
1160
+ * non-item part, or per part) and ARIA attributes, functions resolved against the oracle's
1161
+ * view and the element's attributes.
1162
+ */
1163
+ function expectations(contract, state, view) {
1164
+ const ds = contract.dataState?.[state];
1165
+ const attrs = contract.attrs?.[state];
1166
+ const resolve = (x, el) => typeof x === "function" ? x(view, el.attrs) : x;
1167
+ return {
1168
+ open: ds === void 0 ? state === "open" : typeof ds === "string" ? ds === "open" : Object.values(ds).includes("open"),
1169
+ expected: (el) => {
1170
+ if (el.part === null) return {};
1171
+ const dataState = ds === void 0 ? void 0 : typeof ds === "string" ? el.part === "item" ? void 0 : ds : resolve(ds[el.part], el);
1172
+ const own = attrs?.[el.part];
1173
+ return {
1174
+ dataState,
1175
+ attrs: own === void 0 ? void 0 : resolve(own, el)
1176
+ };
1177
+ }
1178
+ };
1179
+ }
1180
+ /** The event type the oracle processes for an edge (`$props:x` → the declared event). */
1181
+ function stepEvent(machine, edge) {
1182
+ if (edge.event.startsWith("$sync:")) return "$sync";
1183
+ if (edge.event.startsWith("$props:")) return machine.def.onProps?.[edge.event.slice(7)] ?? edge.event;
1184
+ return edge.event;
1185
+ }
1186
+ /** Whether the oracle's step log shows that this edge was taken. */
1187
+ const taken = (edge, type, log) => log.some((s) => s.event.type === type && s.source === edge.source && s.target === edge.target);
1188
+ /**
1189
+ * An oracle: the contract's pure machine with the given props, never started (no effects,
1190
+ * no timers; delays are sent as `after:<delay>` events). Guards read props through a proxy
1191
+ * that records which ones they read.
1192
+ */
1193
+ /**
1194
+ * The oracle's environment: a real clock (typeahead timeouts agree with the page's), the
1195
+ * default locale, nothing to measure, focus or announce.
1196
+ */
1197
+ const oracleEnv = {
1198
+ clock: { now: () => globalThis.performance?.now() ?? Date.now() },
1199
+ locale: {
1200
+ locale: () => new Intl.Collator().resolvedOptions().locale,
1201
+ dir: () => "ltr"
1202
+ },
1203
+ platform: {
1204
+ engine: "blink",
1205
+ apple: false,
1206
+ mac: false,
1207
+ ios: false,
1208
+ android: false,
1209
+ windows: false,
1210
+ webkit: false,
1211
+ chromium: true,
1212
+ firefox: false
1213
+ },
1214
+ layout: { pageTarget: () => null },
1215
+ dom: {
1216
+ getById: () => null,
1217
+ activeElement: () => null,
1218
+ getRootNode: () => void 0
1219
+ },
1220
+ announcer: {
1221
+ announce: () => {},
1222
+ prepare: () => () => {},
1223
+ cancel: () => {}
1224
+ },
1225
+ modality: {
1226
+ modality: () => "keyboard",
1227
+ subscribe: () => () => {},
1228
+ focusCause: () => "other",
1229
+ markFocus: () => {},
1230
+ unmarkFocus: () => {},
1231
+ recentFocus: () => []
1232
+ }
1233
+ };
1234
+ function createOracle(contract, initial) {
1235
+ const reads = /* @__PURE__ */ new Set();
1236
+ let inGuard = false;
1237
+ const impl = contract.machine.impl;
1238
+ const guards = Object.fromEntries(Object.entries(impl.guards ?? {}).map(([name, guard]) => [name, (args) => {
1239
+ inGuard = true;
1240
+ try {
1241
+ return guard(args);
1242
+ } finally {
1243
+ inGuard = false;
1244
+ }
1245
+ }]));
1246
+ const track = (p) => new Proxy(p, { get(target, key) {
1247
+ if (inGuard && typeof key === "string") reads.add(key);
1248
+ return Reflect.get(target, key);
1249
+ } });
1250
+ const machine = {
1251
+ ...contract.machine,
1252
+ impl: {
1253
+ ...impl,
1254
+ guards
1255
+ }
1256
+ };
1257
+ const service = createService(machine, track(initial), oracleEnv);
1258
+ const log = [];
1259
+ service.inspect((s) => log.push(s));
1260
+ let props = initial;
1261
+ return {
1262
+ service,
1263
+ log,
1264
+ reads,
1265
+ get props() {
1266
+ return props;
1267
+ },
1268
+ setProps(next) {
1269
+ props = next;
1270
+ service.setProps(track(next));
1271
+ },
1272
+ send(type, extra = {}) {
1273
+ service.send({
1274
+ type,
1275
+ ...extra
1276
+ });
1277
+ }
1278
+ };
1279
+ }
1280
+ /**
1281
+ * Walks a path on an oracle, with each action step in the modality the runner will use (so
1282
+ * guards reading the modality decide as they will at run time): cuts it at the first edge
1283
+ * these props and this modality do not take.
1284
+ */
1285
+ function plan(contract, path, props, reads, modality) {
1286
+ const oracle = createOracle(contract, props);
1287
+ const actions = contract.actions;
1288
+ for (const [i, edge] of path.edges.entries()) {
1289
+ const m = mappingOf(contract, edge);
1290
+ const before = oracle.log.length;
1291
+ const action = m?.kind === "action" ? actions[m.action] : void 0;
1292
+ if (m?.kind === "props") oracle.setProps({
1293
+ ...oracle.props,
1294
+ ...m.props(edge.target ?? edge.source)
1295
+ });
1296
+ else if (action && m?.kind === "action") {
1297
+ const payload = m.event?.(oracle.service.view()) ?? {};
1298
+ oracle.send(edge.event, {
1299
+ ...payload,
1300
+ modality: stepModality(action, modality)
1301
+ });
1302
+ } else oracle.send(edge.event);
1303
+ if (!taken(edge, stepEvent(contract.machine, edge), oracle.log.slice(before))) {
1304
+ for (const r of oracle.reads) reads.add(r);
1305
+ const edges = path.edges.slice(0, i + 1);
1306
+ return {
1307
+ path: {
1308
+ name: `${label(edges)} (not taken)`,
1309
+ edges
1310
+ },
1311
+ notTaken: edge
1312
+ };
1313
+ }
1314
+ }
1315
+ for (const r of oracle.reads) reads.add(r);
1316
+ return {
1317
+ path,
1318
+ notTaken: null
1319
+ };
1320
+ }
1321
+ /**
1322
+ * Registers one test per path × modality (× direction) that walks the machine graph
1323
+ * through the contract, comparing the component against a headless copy of the machine
1324
+ * and checking every applicable invariant after each step, plus one coverage test that
1325
+ * fails while an event or prop edge has no mapping.
1326
+ */
1327
+ function testMachine(contract, options) {
1328
+ const graph = toGraph(contract.machine);
1329
+ const props = options.props ?? {};
1330
+ const canRerender = options.rerender !== void 0;
1331
+ const reads = /* @__PURE__ */ new Set();
1332
+ const actions = contract.actions;
1333
+ const modalities = options.modalities ?? [...new Set(Object.values(actions).flatMap((a) => a ? modalitiesOf(a) : []))];
1334
+ const planFor = (modality) => {
1335
+ const excluded = /* @__PURE__ */ new Set();
1336
+ /** The first path that reached each not-taken edge (it ends with that edge). */
1337
+ const cut = [];
1338
+ let planned = [];
1339
+ for (let round = 0; round <= graph.edges.length; round++) {
1340
+ const isWalkable = walkable(contract, canRerender);
1341
+ planned = paths(graph, {
1342
+ cover: options.coverage ?? "transitions",
1343
+ walkable: (e) => isWalkable(e) && !excluded.has(e)
1344
+ }).map((edges) => plan(contract, {
1345
+ name: label(edges),
1346
+ edges
1347
+ }, props, reads, modality));
1348
+ const before = excluded.size;
1349
+ for (const p of planned) if (p.notTaken && !excluded.has(p.notTaken)) {
1350
+ excluded.add(p.notTaken);
1351
+ cut.push(p);
1352
+ }
1353
+ if (excluded.size === before) break;
1354
+ }
1355
+ return [...planned.filter((p) => !p.notTaken), ...cut];
1356
+ };
1357
+ const plannedBy = new Map(modalities.map((m) => [m, planFor(m)]));
1358
+ const directions = options.directions ?? (contract.traits.includes("directional") ? ["ltr", "rtl"] : ["ltr"]);
1359
+ const runPlatforms = options.platforms ?? (contract.traits.includes("composite-activedescendant") ? [
1360
+ platforms$1.apple,
1361
+ appleBlink,
1362
+ platforms$1.windows
1363
+ ] : [platforms$1.linux]);
1364
+ const platformName = (p) => Object.entries(platforms$1).find(([, preset]) => preset === p)?.[0] ?? `${p.ios ? "ios" : p.apple ? "apple" : p.windows ? "windows" : p.android ? "android" : "other"}-${p.engine}`;
1365
+ const missingProps = [...reads].filter((key) => !(key in props));
1366
+ if (missingProps.length > 0) options.test(`${contract.scope}: props read by guards`, async (..._) => {
1367
+ throw new Error(missingProps.map((key) => `a guard reads prop "${key}": pass it in testMachine({ props })`).join("\n"));
1368
+ });
1369
+ const covered = /* @__PURE__ */ new Set();
1370
+ /** Edges cut as not taken in some modality (reported only if no modality covers them). */
1371
+ const notTaken = /* @__PURE__ */ new Set();
1372
+ modalities.forEach((modality, index) => {
1373
+ const seen = /* @__PURE__ */ new Set();
1374
+ for (const plannedPath of plannedBy.get(modality) ?? []) {
1375
+ const { path, notTaken: skipped } = plannedPath;
1376
+ if (skipped) notTaken.add(skipped);
1377
+ if (path.edges.length === 0 || seen.has(path.name)) continue;
1378
+ seen.add(path.name);
1379
+ const steps = path.edges.map((e) => mappingOf(contract, e));
1380
+ const hasActions = steps.some((m) => m?.kind === "action");
1381
+ if (!steps.some((m) => {
1382
+ const action = m?.kind === "action" ? actions[m.action] : void 0;
1383
+ return action !== void 0 && modalitiesOf(action).includes(modality);
1384
+ }) && (hasActions || index > 0)) continue;
1385
+ for (const e of path.edges) if (e !== skipped) covered.add(e);
1386
+ for (const direction of directions) for (const platform of runPlatforms) {
1387
+ const tags = [
1388
+ modality,
1389
+ ...direction === "rtl" ? ["rtl"] : [],
1390
+ ...runPlatforms.length > 1 ? [platformName(platform)] : []
1391
+ ];
1392
+ const name = `${contract.scope} [${tags.join(", ")}]: ${path.name}`;
1393
+ const ctx = {
1394
+ platform,
1395
+ locale: options.locale ?? "en",
1396
+ direction,
1397
+ modality
1398
+ };
1399
+ options.test(name, (...args) => runPath(contract, graph, plannedPath, ctx, options, args, name));
1400
+ }
1401
+ }
1402
+ });
1403
+ const failing = [];
1404
+ const info = [];
1405
+ for (const edge of graph.edges) {
1406
+ if (covered.has(edge)) continue;
1407
+ const where = `${edge.source} ${edgeLabel(edge)}`;
1408
+ const m = mappingOf(contract, edge);
1409
+ if (edge.event === "$reverted") info.push(`${where} (from the parent)`);
1410
+ else if (m?.kind === "skip") info.push(`${where} (skipped: ${m.reason})`);
1411
+ else if (notTaken.has(edge)) info.push(`${where} (not taken under these props)`);
1412
+ else if (m?.kind === "props" && !canRerender) info.push(`${where} (needs rerender)`);
1413
+ else if (m === void 0) failing.push(`${where} (no mapping)`);
1414
+ else info.push(`${where} (unreachable)`);
1415
+ }
1416
+ if (failing.length > 0 || info.length > 0) {
1417
+ const name = `${contract.scope}: coverage — ${failing.length} uncovered, ${info.length} reported`;
1418
+ options.test(name, async (..._) => {
1419
+ for (const line of info) console.info(`[rind-ui] ${contract.scope} coverage: ${line}`);
1420
+ if (failing.length > 0) throw new Error([
1421
+ `${contract.scope}: edges with no contract mapping (map them, or { skip: "reason" }):`,
1422
+ ...failing.map((f) => `- ${f}`),
1423
+ ...info.length > 0 ? ["reported:", ...info.map((f) => `- ${f}`)] : []
1424
+ ].join("\n"));
1425
+ });
1426
+ }
1427
+ }
1428
+ const TEXT_ENTRY = /* @__PURE__ */ new Set([
1429
+ "textbox",
1430
+ "combobox",
1431
+ "searchbox",
1432
+ "spinbutton"
1433
+ ]);
1434
+ const IME_KEYS = /* @__PURE__ */ new Set([
1435
+ "Enter",
1436
+ "Escape",
1437
+ "Space",
1438
+ "ArrowUp",
1439
+ "ArrowDown",
1440
+ "ArrowLeft",
1441
+ "ArrowRight"
1442
+ ]);
1443
+ /** Keys an IME may swallow: navigation/commit keys and every printable character. */
1444
+ const imeKey = (key) => IME_KEYS.has(key) || [...key].length === 1;
1445
+ /**
1446
+ * An env that replays an action differently: hover as touch, or keys as composing on
1447
+ * text-entry parts; every other input is dropped. `used` tells whether anything was replayed.
1448
+ */
1449
+ function replayEnv(base, snapshot, mode) {
1450
+ const state = {
1451
+ used: false,
1452
+ keys: [],
1453
+ finish: []
1454
+ };
1455
+ const isText = (name) => TEXT_ENTRY.has(snapshot.parts.find((p) => p.part === name)?.role ?? "");
1456
+ const wrap = (part, name) => ({
1457
+ ...part,
1458
+ click: async () => {},
1459
+ tap: async () => {},
1460
+ focus: async () => {},
1461
+ type: async (text) => {
1462
+ if (mode !== "composing" || !isText(name) || text === "") return;
1463
+ state.used = true;
1464
+ state.keys.push(JSON.stringify(text));
1465
+ const updates = [...text].map((_, i) => text.slice(0, i + 1));
1466
+ await part.compose(updates);
1467
+ state.finish.push(() => part.compose([], ""));
1468
+ },
1469
+ compose: async () => {},
1470
+ pressAtPosition: async () => {},
1471
+ hover: async () => {
1472
+ if (mode !== "touch-hover") return;
1473
+ state.used = true;
1474
+ await part.hover({ pointerType: "touch" });
1475
+ },
1476
+ press: async (key, o) => {
1477
+ if (mode !== "composing" || !imeKey(key) || !isText(name)) return;
1478
+ state.used = true;
1479
+ state.keys.push(key);
1480
+ await part.press(key, {
1481
+ ...o,
1482
+ composing: true
1483
+ });
1484
+ },
1485
+ nth: (i) => wrap(part.nth(i), name),
1486
+ all: async () => (await part.all()).map((p) => wrap(p, name)),
1487
+ scoped: (scope, inner) => wrap(part.scoped(scope, inner), null),
1488
+ withAttr: (name, value) => wrap(part.withAttr(name, value), null)
1489
+ });
1490
+ return {
1491
+ env: {
1492
+ ...base,
1493
+ part: (name, by) => wrap(base.part(name, by), name),
1494
+ find: (by) => wrap(base.find(by), null),
1495
+ focused: () => wrap(base.focused(), snapshot.focus.part),
1496
+ keyboard: async (key, o) => {
1497
+ if (mode !== "composing" || !imeKey(key) || !TEXT_ENTRY.has(snapshot.focus.element?.role ?? "")) return;
1498
+ state.used = true;
1499
+ state.keys.push(key);
1500
+ await base.keyboard(key, {
1501
+ ...o,
1502
+ composing: true
1503
+ });
1504
+ },
1505
+ pointerOutside: async () => {}
1506
+ },
1507
+ state
1508
+ };
1509
+ }
1510
+ async function runPath(contract, graph, { path, notTaken }, ctx, options, args, testName) {
1511
+ const { modality, direction, platform } = ctx;
1512
+ installErrorLog().splice(0);
1513
+ for (const arg of args) if (isPage(arg)) watchPageErrors(arg).splice(0);
1514
+ run = ctx;
1515
+ const rendered = await options.setup(...args);
1516
+ const target = options.target(rendered);
1517
+ const factory = toEnvFactory(target);
1518
+ const anchor = contract.locate(...options.anchor);
1519
+ const envs = /* @__PURE__ */ new Map();
1520
+ const envFor = (m) => {
1521
+ let env = envs.get(m);
1522
+ if (!env) {
1523
+ env = directed(factory.create({
1524
+ scope: contract.scope,
1525
+ anchor,
1526
+ modality: m,
1527
+ platform
1528
+ }), direction);
1529
+ envs.set(m, env);
1530
+ }
1531
+ return env;
1532
+ };
1533
+ const base = envFor(modality);
1534
+ if (direction === "rtl") await base.setDirection("rtl");
1535
+ const props = options.props ?? {};
1536
+ const oracle = createOracle(contract, props);
1537
+ /** Everything sent to the oracle, to replay "what if" events on a copy. */
1538
+ const inputs = [];
1539
+ const send = (type, extra = {}) => {
1540
+ inputs.push({
1541
+ kind: "send",
1542
+ type,
1543
+ extra
1544
+ });
1545
+ oracle.send(type, extra);
1546
+ };
1547
+ /** The oracle's state after the inputs so far plus `extra` (on a fresh copy). */
1548
+ const whatIf = (type, extra) => {
1549
+ const copy = createOracle(contract, props);
1550
+ for (const input of inputs) if (input.kind === "send") copy.send(input.type, input.extra);
1551
+ else copy.setProps(input.props);
1552
+ copy.send(type, extra);
1553
+ return copy.service.getSnapshot().state;
1554
+ };
1555
+ const impl = contract.machine.impl;
1556
+ const hasFocusEvent = graph.edges.some((e) => e.event === "FOCUS");
1557
+ if (contract.traits.includes("modal") && typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom") && !simulatedNoted.has(contract.scope)) {
1558
+ simulatedNoted.add(contract.scope);
1559
+ console.info(`[rind-ui] ${contract.scope}: modal checks verified the inert attributes and scroll-lock styles only; inert behaviour (focus and pointer blocking) is verified in a real browser`);
1560
+ }
1561
+ if (contract.traits.includes("anchored") && typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom") && !layoutNoted.has(contract.scope)) {
1562
+ layoutNoted.add(contract.scope);
1563
+ console.info(`[rind-ui] ${contract.scope}: anchored layout checks unexercised (no layout in jsdom); placement before focus was checked`);
1564
+ }
1565
+ const reached = /* @__PURE__ */ new Set();
1566
+ const done = [graph.initial];
1567
+ let skippedChromium = false;
1568
+ const exceptions = (contract.exceptions ?? []).filter((e) => quirkActive(e.quirk, { platform }));
1569
+ if (exceptions.length > 0) for (const e of exceptions) console.info(`[rind-ui] ${contract.scope}: exception ${e.invariant} for ${e.part} (quirk ${e.quirk})`);
1570
+ const exempt = (invariant, part) => exceptions.some((e) => e.invariant === invariant && e.part === part);
1571
+ const fail = (step, edge, message) => {
1572
+ const steps = oracle.log.map((s) => `${s.source} —${s.event.type}→ ${s.target ?? s.source}${s.actions.length > 0 ? ` (${s.actions.join(", ")})` : ""}`);
1573
+ throw new Error([
1574
+ `${testName}`,
1575
+ ` failed ${edge ? `at step ${step}/${path.edges.length} (—${edge.event}→)` : "in the initial state"}`,
1576
+ ` modality: ${modality}${direction === "rtl" ? ", rtl" : ""}`,
1577
+ ` path so far: ${done.join(" → ")}`,
1578
+ ` oracle steps: ${steps.length > 0 ? steps.join("; ") : "none"}`,
1579
+ ` ${message.split("\n").join("\n ")}`
1580
+ ].join("\n"));
1581
+ };
1582
+ /** Every query, each caught on its own so one throwing query keeps the report readable. */
1583
+ const observe = async () => {
1584
+ const out = {};
1585
+ for (const [name, query] of Object.entries(contract.queries)) {
1586
+ if (query.length > 1) continue;
1587
+ out[name] = await query(base).catch((e) => `<${e instanceof Error ? e.message : String(e)}>`);
1588
+ }
1589
+ return out;
1590
+ };
1591
+ const expectedFor = (state) => contract.states[state] ?? {};
1592
+ const matchesState = (state) => (seen) => Object.entries(expectedFor(state)).every(([k, v]) => Object.is(seen[k], v));
1593
+ /** The longest delay the machine can schedule under the current props. */
1594
+ const longestDelay = () => Math.max(0, ...Object.values(impl.delays ?? {}).map((d) => {
1595
+ try {
1596
+ return Number(d({ props: oracle.props })) || 0;
1597
+ } catch {
1598
+ return 0;
1599
+ }
1600
+ }));
1601
+ /**
1602
+ * After a replay that must change nothing: every query still reads what it read before,
1603
+ * and the component still shows `state` — also after the machine's longest delay, so a
1604
+ * delayed reaction (a tooltip's open delay) is seen.
1605
+ */
1606
+ const unchanged = async (state, previous, wait = 16) => {
1607
+ await base.advance(wait);
1608
+ const seen = await observe();
1609
+ const changed = Object.keys(seen).filter((k) => JSON.stringify(seen[k]) !== JSON.stringify(previous[k]));
1610
+ return {
1611
+ ok: matchesState(state)(seen) && changed.length === 0,
1612
+ seen,
1613
+ changed
1614
+ };
1615
+ };
1616
+ const hoveredParts = async () => new Set((await base.collect()).parts.filter((p) => p.attrs["data-hover"] !== void 0).map((p) => p.describe));
1617
+ /** The last step's facts: the base of the unmount-while-open check. */
1618
+ /** Steps whose user action changed the value (form-associated: one `change` each). */
1619
+ let userChanges = 0;
1620
+ let lastFacts = null;
1621
+ const verify = async (step, edge, before, from, baseline, stepModality, announcedBefore) => {
1622
+ const state = oracle.service.getSnapshot().state;
1623
+ const expected = expectedFor(state);
1624
+ const matches = matchesState(state);
1625
+ const seen = await base.until(observe, matches).catch(async () => observe());
1626
+ if (!matches(seen)) fail(step, edge, `${stepModality === "virtual" ? "virtual-parity: " : ""}expected ${state}: ${JSON.stringify(expected)}\n observed: ${JSON.stringify(seen)}`);
1627
+ if (contract.traits.includes("presence")) {
1628
+ const content = contract.semantics?.["content"];
1629
+ await base.until(async () => (await base.collect()).parts.filter((p) => p.part === content && p.animations > 0).length, (n) => n === 0).catch(() => {});
1630
+ await base.advance(16);
1631
+ }
1632
+ const after = await base.collect();
1633
+ const facts = {
1634
+ before,
1635
+ after,
1636
+ baseline: baseline ?? after,
1637
+ from,
1638
+ state,
1639
+ ...expectations(contract, state, oracle.service.view()),
1640
+ atInitial: state === graph.initial,
1641
+ anchorCount: await base.anchorCount(),
1642
+ errors: await base.takeErrors(),
1643
+ traits: contract.traits,
1644
+ semantics: { ...contract.semantics },
1645
+ values: oracle.service.view().values,
1646
+ context: oracle.service.getSnapshot().context,
1647
+ ...collectionSizeOf(oracle.props),
1648
+ modality: stepModality,
1649
+ platform,
1650
+ stepAnnouncements: (await base.announcements()).slice(announcedBefore),
1651
+ observed: seen,
1652
+ ...contract.announcements ? { announcements: contract.announcements } : {},
1653
+ ...contract.formInput ? { formInput: {
1654
+ ...contract.formInput.multiple ? { multiple: true } : {},
1655
+ expected: (input) => contract.formInput?.expected(oracle.service.view().values, input) ?? {},
1656
+ userChanges
1657
+ } } : {},
1658
+ exempt
1659
+ };
1660
+ lastFacts = facts;
1661
+ const problems = [...checkGeneric(facts)];
1662
+ const chromium = await base.chromiumChecks?.();
1663
+ if (chromium === "unavailable") {
1664
+ if (!skippedChromium) {
1665
+ skippedChromium = true;
1666
+ console.info(`[rind-ui] ${contract.scope}: Chromium accessibility-tree checks skipped (unavailable here)`);
1667
+ }
1668
+ } else if (chromium) problems.push(...chromium.map((p) => `chromium-tree: ${p}`));
1669
+ const own = [...contract.invariants ?? [], ...options.invariants ?? []];
1670
+ for (const inv of own) {
1671
+ const result = await inv.check({
1672
+ env: base,
1673
+ state,
1674
+ modality,
1675
+ props: oracle.props,
1676
+ values: oracle.service.view().values
1677
+ }).catch((e) => e instanceof Error ? e.message : String(e));
1678
+ if (typeof result === "string" && result !== "") problems.push(`${inv.name}: ${result}`);
1679
+ }
1680
+ if (problems.length > 0) fail(step, edge, `invariants failed in ${state}:\n- ${problems.join("\n- ")}`);
1681
+ if (options.a11y && !reached.has(state)) {
1682
+ reached.add(state);
1683
+ await options.a11y(target).catch((e) => fail(step, edge, `accessibility check failed in ${state}:\n${e instanceof Error ? e.message : String(e)}`));
1684
+ }
1685
+ return after;
1686
+ };
1687
+ /** Replays an action as touch hover / composing keys; it must change nothing. */
1688
+ const replay = async (step, edge, mode, impl, actionArgs, snapshot, state) => {
1689
+ const { env, state: used } = replayEnv(envFor(mode === "composing" ? "keyboard" : "touch"), snapshot, mode);
1690
+ const previous = await observe();
1691
+ const hoveredBefore = await hoveredParts();
1692
+ await impl(env, ...actionArgs).catch(() => {});
1693
+ if (!used.used) return;
1694
+ const transition = `${state} —${edge.event}→ ${edge.target ?? state}`;
1695
+ const wait = 16 + (graph.edges.some((e) => e.source === state && e.event.startsWith("after:")) ? 0 : longestDelay());
1696
+ const { ok, seen, changed } = await unchanged(state, previous, wait);
1697
+ const what = `changed ${changed.length > 0 ? changed.join(", ") : "the state"}: expected ${state} ${JSON.stringify(expectedFor(state))}, observed ${JSON.stringify(seen)}`;
1698
+ for (const finish of used.finish) await finish();
1699
+ if (used.finish.length > 0) await base.advance(16);
1700
+ if (mode === "touch-hover") {
1701
+ const gained = [...await hoveredParts()].filter((d) => !hoveredBefore.has(d));
1702
+ if (!ok || gained.length > 0) fail(step, edge, `no-touch-hover: a touch "hover" in the action of ${transition} ${gained.length > 0 ? `set data-hover on ${gained.join(", ")}` : what}`);
1703
+ }
1704
+ if (mode === "composing" && !ok) fail(step, edge, `ime-never-commits: composing ${used.keys.join(", ")} in the action of ${transition} ${what}`);
1705
+ };
1706
+ /**
1707
+ * Presence, after a closing action: sampled mid-exit (a running exit animation), then
1708
+ * reopened — the exiting element must come back, not a new one — and closed again by the
1709
+ * same action, so the path goes on from the state it reached.
1710
+ */
1711
+ const reopenDuringExit = async (step, edge, close) => {
1712
+ const content = contract.semantics?.["content"];
1713
+ const exiting = (await base.collect()).parts.find((p) => p.part === content && p.animations > 0);
1714
+ if (!exiting) return;
1715
+ if (exiting.attrs["data-state"] !== "closed") fail(step, edge, `presence: ${exiting.describe} is exiting (running animations: ${exiting.animations}) without data-state="closed"`);
1716
+ const state = oracle.service.getSnapshot().state;
1717
+ const reopen = graph.edges.find((e) => e.source === state && e.target !== null && expectations(contract, e.target, null).open && mappingOf(contract, e)?.kind === "action");
1718
+ const m = reopen ? mappingOf(contract, reopen) : void 0;
1719
+ if (!reopen || m?.kind !== "action") return;
1720
+ const action = contract.actions[m.action] ?? {};
1721
+ const mod = stepModality(action, "keyboard");
1722
+ const act = async (name, args, m) => {
1723
+ try {
1724
+ await runAction(contract, envFor(m), name, args, false);
1725
+ } catch (e) {
1726
+ fail(step, edge, `presence (reopen during the exit): ${e instanceof Error ? e.message : String(e)}`);
1727
+ }
1728
+ };
1729
+ send(reopen.event, { modality: mod });
1730
+ await act(m.action, m.args?.(oracle.service.view()) ?? [], mod);
1731
+ const back = (await base.collect()).parts.find((p) => p.part === content);
1732
+ if (back?.node !== exiting.node) fail(step, edge, `presence: reopening during the exit (running animations: ${exiting.animations}) ${back ? `mounted a new ${back.describe}` : "left no content"}; the exiting element must be kept`);
1733
+ send(edge.event, { modality: close.mod });
1734
+ await act(close.action, close.args, close.mod);
1735
+ };
1736
+ await (base.scope ? base.scope.bind(base) : (fn) => fn())(async () => {
1737
+ try {
1738
+ const baseline = await verify(0, null, null, null, null, null, 0);
1739
+ let before = baseline;
1740
+ for (const [i, edge] of path.edges.entries()) {
1741
+ const from = oracle.service.getSnapshot().state;
1742
+ const mapping = mappingOf(contract, edge);
1743
+ const announcedBefore = (await base.announcements()).length;
1744
+ let stepMod = null;
1745
+ if (mapping?.kind === "delay") {
1746
+ const ms = impl.delays?.[edge.event.slice(6)]?.({ props: oracle.props }) ?? 0;
1747
+ send(edge.event);
1748
+ await base.advance(ms);
1749
+ } else if (mapping?.kind === "props") {
1750
+ const next = {
1751
+ ...oracle.props,
1752
+ ...mapping.props(edge.target ?? edge.source)
1753
+ };
1754
+ inputs.push({
1755
+ kind: "props",
1756
+ props: next
1757
+ });
1758
+ oracle.setProps(next);
1759
+ await options.rerender?.(next, rendered);
1760
+ } else if (mapping?.kind === "action") {
1761
+ const logBefore = oracle.log.length;
1762
+ const countBefore = options.activations?.count() ?? 0;
1763
+ const action = contract.actions[mapping.action] ?? {};
1764
+ const actionArgs = mapping.args?.(oracle.service.view()) ?? [];
1765
+ stepMod = stepModality(action, modality);
1766
+ const keyboardImpl = action["keyboard"];
1767
+ if (stepMod === "keyboard" && typeof keyboardImpl === "function") await replay(i + 1, edge, "composing", keyboardImpl, actionArgs, before, from);
1768
+ const ownImpl = action[stepMod === "virtual" ? "pointer" : stepMod];
1769
+ if (typeof ownImpl === "function") await replay(i + 1, edge, "touch-hover", ownImpl, actionArgs, before, from);
1770
+ const valuesBefore = JSON.stringify(oracle.service.view().values);
1771
+ send(edge.event, {
1772
+ ...mapping.event?.(oracle.service.view()),
1773
+ modality: stepMod
1774
+ });
1775
+ if (JSON.stringify(oracle.service.view().values) !== valuesBefore && !contract.formInput?.silentEvents?.includes(edge.event)) userChanges += 1;
1776
+ try {
1777
+ await runAction(contract, envFor(stepMod), mapping.action, actionArgs, edge !== notTaken);
1778
+ } catch (e) {
1779
+ fail(i + 1, edge, e instanceof Error ? e.message : String(e));
1780
+ }
1781
+ const closes = edge !== notTaken && edge.target !== null && expectations(contract, from, null).open && !expectations(contract, edge.target, null).open;
1782
+ if (options.activations) {
1783
+ const { action: name, count } = options.activations;
1784
+ const expected = oracle.log.slice(logBefore).filter((s) => s.actions.includes(name)).length;
1785
+ const actual = count() - countBefore;
1786
+ if (actual !== expected) {
1787
+ const prefix = stepMod === "virtual" ? "virtual-parity: " : "activation-parity: ";
1788
+ fail(i + 1, edge, `${prefix}"${name}" ran ${actual} times, expected ${expected}`);
1789
+ }
1790
+ }
1791
+ if (contract.traits.includes("presence") && closes) await reopenDuringExit(i + 1, edge, {
1792
+ action: mapping.action,
1793
+ args: actionArgs,
1794
+ mod: stepMod
1795
+ });
1796
+ } else fail(i + 1, edge, `no contract mapping for ${edge.event}`);
1797
+ done.push(`${edge.event}→${oracle.service.getSnapshot().state}`);
1798
+ before = await verify(i + 1, edge, before, from, baseline, stepMod, announcedBefore);
1799
+ }
1800
+ const state = oracle.service.getSnapshot().state;
1801
+ const virtualEnv = envFor("virtual");
1802
+ const counts = /* @__PURE__ */ new Map();
1803
+ for (const p of before.parts) {
1804
+ if (p.part === null) continue;
1805
+ const index = counts.get(p.part) ?? 0;
1806
+ counts.set(p.part, index + 1);
1807
+ if (!p.focusable || p.hidden) continue;
1808
+ if (contract.traits.includes("form-associated") && (contract.commitsOnFocus?.length ?? 0) > 0 && p.part === "hidden-input") continue;
1809
+ if (contract.commitsOnFocus?.some((c) => c.part === p.part && c.state === state)) continue;
1810
+ const previous = await observe();
1811
+ await virtualEnv.part(p.part).nth(index).focus();
1812
+ const { ok, seen, changed } = await unchanged(state, previous);
1813
+ const oracleState = hasFocusEvent ? whatIf("FOCUS", {
1814
+ modality: "virtual",
1815
+ cause: "other"
1816
+ }) : state;
1817
+ if (!ok || oracleState !== state) fail(path.edges.length, path.edges.at(-1) ?? null, `focus-does-not-commit: programmatic focus on ${p.describe} in ${state} changed ${oracleState !== state ? `the machine: ${state} → ${oracleState}` : `${changed.length > 0 ? changed.join(", ") : "the state"}: observed ${JSON.stringify(seen)}`}; list it in the contract's commitsOnFocus if that is intended`);
1818
+ }
1819
+ const layered = contract.traits.some((t) => t === "layer" || t === "modal");
1820
+ const unmount = rendered?.unmount;
1821
+ if (layered && typeof unmount === "function" && expectations(contract, state, null).open) {
1822
+ unmount();
1823
+ await base.advance(16);
1824
+ const page = await base.collectDocument();
1825
+ const last = lastFacts;
1826
+ const problems = last ? genericInvariants["document-clean"]?.({
1827
+ ...last,
1828
+ after: page,
1829
+ atInitial: true
1830
+ }) ?? [] : [];
1831
+ if (problems.length > 0) fail(path.edges.length, path.edges.at(-1) ?? null, `unmounted while open:\n${problems.map((p) => ` - ${p}`).join("\n")}`);
1832
+ }
1833
+ } finally {
1834
+ run = void 0;
1835
+ if (direction === "rtl") await base.setDirection(null);
1836
+ }
1837
+ });
1838
+ }
1839
+ //#endregion
1840
+ //#region src/positioning.ts
1841
+ function fakePositioning() {
1842
+ const live = /* @__PURE__ */ new Set();
1843
+ let repositions = 0;
1844
+ return {
1845
+ get requests() {
1846
+ return [...live];
1847
+ },
1848
+ get repositions() {
1849
+ return repositions;
1850
+ },
1851
+ track(request) {
1852
+ live.add(request);
1853
+ return {
1854
+ reposition: () => {
1855
+ if (live.has(request)) repositions++;
1856
+ },
1857
+ stop: () => {
1858
+ live.delete(request);
1859
+ }
1860
+ };
1861
+ },
1862
+ reposition(positioner) {
1863
+ for (const r of live) if (r.positioner === positioner) repositions++;
1864
+ },
1865
+ emit(placement, options = {}) {
1866
+ for (const r of [...live]) {
1867
+ if (options.positioner && r.positioner !== options.positioner) continue;
1868
+ r.onPlacement(placement, options.first ?? true);
1869
+ }
1870
+ }
1871
+ };
1872
+ }
1873
+ //#endregion
1874
+ //#region src/pseudo-locale.ts
1875
+ const ACCENTS = {
1876
+ a: "á",
1877
+ e: "é",
1878
+ i: "í",
1879
+ o: "ó",
1880
+ u: "ú",
1881
+ c: "ç",
1882
+ n: "ñ",
1883
+ s: "š",
1884
+ y: "ý",
1885
+ z: "ž",
1886
+ A: "Á",
1887
+ E: "É",
1888
+ I: "Í",
1889
+ O: "Ó",
1890
+ U: "Ú",
1891
+ C: "Ç",
1892
+ N: "Ñ",
1893
+ S: "Š",
1894
+ Y: "Ý",
1895
+ Z: "Ž"
1896
+ };
1897
+ /** "Close" → "⟦Çłóšé⟧": still readable, never equal to (or containing) the English. */
1898
+ const pseudo = (text) => `⟦${[...text].map((c) => ACCENTS[c] ?? c).join("")}⟧`;
1899
+ /** Every message replaced: strings pseudo-localised, functions' results too. */
1900
+ function pseudoMessages(messages) {
1901
+ const out = {};
1902
+ for (const [key, value] of Object.entries(messages)) out[key] = typeof value === "function" ? (...args) => pseudo(value(...args)) : pseudo(value);
1903
+ return out;
1904
+ }
1905
+ /**
1906
+ * The English defaults (string messages) that appear in `texts` — accessible names,
1907
+ * descriptions, aria-roledescription, aria-valuetext, announcements. Empty when every AT
1908
+ * string comes from the messages.
1909
+ */
1910
+ function englishLeaks(defaults, texts) {
1911
+ return Object.values(defaults).filter((v) => typeof v === "string").filter((e) => texts.some((t) => t.includes(e)));
1912
+ }
1913
+ //#endregion
1914
+ //#region src/state-stories.ts
1915
+ /** States of `contract` with no state story (empty when covered). */
1916
+ function missingStateStories(contract, stories, storyExports) {
1917
+ const own = stories[contract.scope] ?? {};
1918
+ return Object.keys(contract.states).flatMap((state) => {
1919
+ const name = own[state];
1920
+ if (!name) return [`${contract.scope}: no state story for "${state}"`];
1921
+ if (!(name in storyExports)) return [`${contract.scope}: state story "${name}" for "${state}" is not exported`];
1922
+ return [];
1923
+ });
1924
+ }
1925
+ //#endregion
1926
+ //#region src/switch-invariants.ts
1927
+ /** `switch-name-stable`: the Control's accessible name is the same in every state. */
1928
+ function switchStepInvariants() {
1929
+ let first = null;
1930
+ return {
1931
+ invariants: [{
1932
+ name: "switch-name-stable",
1933
+ check: async ({ env }) => {
1934
+ const control = env.part("control");
1935
+ if (await control.count() === 0) return void 0;
1936
+ const name = await control.accessibleName();
1937
+ if (first === null) first = name;
1938
+ return name === first ? void 0 : `the name changed with the state: "${first}" → "${name}"`;
1939
+ }
1940
+ }],
1941
+ reset() {
1942
+ first = null;
1943
+ }
1944
+ };
1945
+ }
1946
+ //#endregion
1947
+ //#region src/text-field-invariants.ts
1948
+ /**
1949
+ * - `text-field-silent-while-composing`: no announcement is made during a composition;
1950
+ * - `text-field-value-only-from-composition` (when `composedText` is given): during a
1951
+ * composition the value only ever holds the story's own text and what the composition
1952
+ * adds, so a variant writing the value while composing (kobalte#737) fails.
1953
+ */
1954
+ function textFieldStepInvariants(options = {}) {
1955
+ let seen = 0;
1956
+ return {
1957
+ invariants: [...options.composedText ? [{
1958
+ name: "text-field-value-only-from-composition",
1959
+ check: async ({ env, state }) => {
1960
+ if (state !== "composing") return void 0;
1961
+ const input = env.part("input");
1962
+ const value = await (await input.exists() ? input : env.part("textarea")).value();
1963
+ return options.composedText?.test(value) ? void 0 : `the value is "${value}" during a composition`;
1964
+ }
1965
+ }] : [], {
1966
+ name: "text-field-silent-while-composing",
1967
+ check: async ({ state }) => {
1968
+ const log = installAnnouncementLog();
1969
+ const added = log.slice(seen);
1970
+ seen = log.length;
1971
+ return state === "composing" && added.length > 0 ? `announced "${added[0]?.message}" while composing` : void 0;
1972
+ }
1973
+ }],
1974
+ reset() {
1975
+ seen = 0;
1976
+ installAnnouncementLog().length = 0;
1977
+ }
1978
+ };
1979
+ }
1980
+ //#endregion
1981
+ //#region src/virtual-sr.ts
1982
+ /**
1983
+ * Starts the virtual screen reader on `container`, runs `run(virtual)` (move with
1984
+ * `virtual.next()`, act, or let the component announce), and returns every phrase spoken.
1985
+ */
1986
+ async function spokenLog(container, run) {
1987
+ const { virtual } = await import("@guidepup/virtual-screen-reader");
1988
+ await virtual.start({ container });
1989
+ try {
1990
+ await run(virtual);
1991
+ return await virtual.spokenPhraseLog();
1992
+ } finally {
1993
+ await virtual.stop();
1994
+ }
1995
+ }
1996
+ /** The live-region phrases of a spoken log ("polite: Copied" → { polite, "Copied" }). */
1997
+ function liveAnnouncements(log) {
1998
+ return log.flatMap((phrase) => {
1999
+ const match = /^(polite|assertive): (.*)$/.exec(phrase);
2000
+ return match ? [{
2001
+ priority: match[1],
2002
+ message: match[2] ?? ""
2003
+ }] : [];
2004
+ });
2005
+ }
2006
+ //#endregion
2007
+ export { accordionStepInvariants, checkGeneric, checkboxStepInvariants, createDriver, createDriverWith, currentRun, domEnv, englishLeaks, fakePositioning, fakeRouter, formStepInvariants, genericInvariants, getAccordion, getButton, getCheckbox, getCheckboxGroup, getCollapsible, getField, getFieldset, getForm, getHeading, getLabel, getLink, getRadioGroup, getSegmentedControl, getSeparator, getSwitch, getTabs, getTextField, getToggle, getToggleGroup, getToolbar, installAnnouncementLog, interceptNativeNavigation, layoutInvariant, liveAnnouncements, machinePaths, missingAriaLines, missingStateStories, navigationLog, paths, platforms, playwrightEnv, pseudo, pseudoMessages, recordingAnnouncer, runAction, spokenLog, switchStepInvariants, testMachine, textFieldStepInvariants, toGraph, traitInvariants, uncovered, withEngine };