@reticular/speakable 1.3.0 → 1.4.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.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/model/types.ts
2
8
  var SUPPORTED_ROLES = [
3
9
  // Original roles (22)
@@ -2658,6 +2664,2520 @@ function createGenericContainer(rootElement, warnings) {
2658
2664
  children
2659
2665
  };
2660
2666
  }
2667
+
2668
+ // src/runtime/index.ts
2669
+ var runtime_exports = {};
2670
+ __export(runtime_exports, {
2671
+ classifyDiff: () => classifyDiff,
2672
+ createBaselineStorage: () => createBaselineStorage,
2673
+ createEngine: () => createEngine,
2674
+ createHeuristicAnalyzer: () => createHeuristicAnalyzer,
2675
+ createTimelineGenerator: () => createTimelineGenerator,
2676
+ deserializeEvent: () => deserializeEvent,
2677
+ deserializeInteractionSequence: () => deserializeInteractionSequence,
2678
+ deserializeTimeline: () => deserializeTimeline,
2679
+ diffTimelines: () => diffTimelines,
2680
+ executeAction: () => executeAction,
2681
+ executeSequence: () => executeSequence,
2682
+ generateSelector: () => generateSelector,
2683
+ getBuiltinPattern: () => getBuiltinPattern,
2684
+ serializeEvent: () => serializeEvent,
2685
+ serializeInteractionSequence: () => serializeInteractionSequence,
2686
+ serializeTimeline: () => serializeTimeline,
2687
+ timelinesEqual: () => timelinesEqual
2688
+ });
2689
+
2690
+ // src/runtime/selector.ts
2691
+ function generateSelector(element) {
2692
+ if (element.id) {
2693
+ return `#${escapeCSSIdentifier(element.id)}`;
2694
+ }
2695
+ const document = element.ownerDocument;
2696
+ if (!document) {
2697
+ return getTagName(element);
2698
+ }
2699
+ const segments = [];
2700
+ let current = element;
2701
+ while (current && current !== document.documentElement) {
2702
+ const segment = buildSegment(current, document);
2703
+ segments.unshift(segment);
2704
+ const partialSelector = segments.join(" > ");
2705
+ try {
2706
+ const matches = document.querySelectorAll(partialSelector);
2707
+ if (matches.length === 1 && matches[0] === element) {
2708
+ return partialSelector;
2709
+ }
2710
+ } catch {
2711
+ }
2712
+ current = current.parentElement;
2713
+ }
2714
+ if (segments.length === 0) {
2715
+ return getTagName(element);
2716
+ }
2717
+ const fullSelector = segments.join(" > ");
2718
+ return fullSelector;
2719
+ }
2720
+ function buildSegment(element, _document) {
2721
+ const tag = getTagName(element);
2722
+ const parent = element.parentElement;
2723
+ if (parent) {
2724
+ const siblingsWithSameTag = Array.from(parent.children).filter(
2725
+ (child) => getTagName(child) === tag
2726
+ );
2727
+ if (siblingsWithSameTag.length === 1) {
2728
+ return tag;
2729
+ }
2730
+ } else {
2731
+ return tag;
2732
+ }
2733
+ const classes = getStableClasses(element);
2734
+ if (classes.length > 0) {
2735
+ const tagWithClasses = `${tag}.${classes.join(".")}`;
2736
+ if (parent) {
2737
+ const siblingsMatchingClasses = Array.from(parent.children).filter(
2738
+ (child) => {
2739
+ if (getTagName(child) !== tag) return false;
2740
+ return classes.every((cls) => child.classList.contains(cls));
2741
+ }
2742
+ );
2743
+ if (siblingsMatchingClasses.length === 1) {
2744
+ return tagWithClasses;
2745
+ }
2746
+ }
2747
+ }
2748
+ const index = getNthChildIndex(element);
2749
+ return `${tag}:nth-child(${index})`;
2750
+ }
2751
+ function getTagName(element) {
2752
+ return element.tagName.toLowerCase();
2753
+ }
2754
+ function getStableClasses(element) {
2755
+ const classes = Array.from(element.classList);
2756
+ if (classes.length === 0) return [];
2757
+ const stableClasses = classes.filter((cls) => !looksLikeDynamicClass(cls));
2758
+ return stableClasses.sort().map(escapeCSSIdentifier);
2759
+ }
2760
+ function looksLikeDynamicClass(className) {
2761
+ if (/^[a-f0-9]{5,}$/i.test(className)) return true;
2762
+ if (/[_-][a-f0-9]{5,}$/i.test(className)) return true;
2763
+ if (/_{2,}[A-Za-z0-9]{4,}$/.test(className)) return true;
2764
+ return false;
2765
+ }
2766
+ function getNthChildIndex(element) {
2767
+ const parent = element.parentElement;
2768
+ if (!parent) return 1;
2769
+ const children = Array.from(parent.children);
2770
+ const index = children.indexOf(element);
2771
+ return index + 1;
2772
+ }
2773
+ function escapeCSSIdentifier(value) {
2774
+ if (!value) return value;
2775
+ let result = "";
2776
+ for (let i = 0; i < value.length; i++) {
2777
+ const char = value[i];
2778
+ const code = char.charCodeAt(0);
2779
+ if (i === 0 && code >= 48 && code <= 57) {
2780
+ result += `\\3${char} `;
2781
+ continue;
2782
+ }
2783
+ if (char === "!" || char === '"' || char === "#" || char === "$" || char === "%" || char === "&" || char === "'" || char === "(" || char === ")" || char === "*" || char === "+" || char === "," || char === "." || char === "/" || char === ":" || char === ";" || char === "<" || char === "=" || char === ">" || char === "?" || char === "@" || char === "[" || char === "\\" || char === "]" || char === "^" || char === "`" || char === "{" || char === "|" || char === "}" || char === "~" || char === " ") {
2784
+ result += `\\${char}`;
2785
+ continue;
2786
+ }
2787
+ result += char;
2788
+ }
2789
+ return result;
2790
+ }
2791
+
2792
+ // src/runtime/observers/focus-observer.ts
2793
+ function computeAccessibleName2(element, document) {
2794
+ const ariaLabel = element.getAttribute("aria-label");
2795
+ if (ariaLabel && ariaLabel.trim()) {
2796
+ return ariaLabel.trim();
2797
+ }
2798
+ const labelledBy = element.getAttribute("aria-labelledby");
2799
+ if (labelledBy && labelledBy.trim()) {
2800
+ const ids = labelledBy.trim().split(/\s+/);
2801
+ const parts = [];
2802
+ for (const id of ids) {
2803
+ const referenced = document.getElementById(id);
2804
+ if (referenced && referenced.textContent) {
2805
+ parts.push(referenced.textContent.trim());
2806
+ }
2807
+ }
2808
+ const combined = parts.join(" ");
2809
+ if (combined) {
2810
+ return combined;
2811
+ }
2812
+ }
2813
+ const textContent = element.textContent;
2814
+ if (textContent && textContent.trim()) {
2815
+ return textContent.trim();
2816
+ }
2817
+ return "";
2818
+ }
2819
+ function getElementRole(element) {
2820
+ const explicitRole = element.getAttribute("role");
2821
+ if (explicitRole && explicitRole.trim()) {
2822
+ return explicitRole.trim();
2823
+ }
2824
+ const tagName = element.tagName.toLowerCase();
2825
+ switch (tagName) {
2826
+ case "button":
2827
+ return "button";
2828
+ case "a":
2829
+ return element.hasAttribute("href") ? "link" : "generic";
2830
+ case "input": {
2831
+ const type = (element.getAttribute("type") || "text").toLowerCase();
2832
+ switch (type) {
2833
+ case "button":
2834
+ case "submit":
2835
+ case "reset":
2836
+ case "image":
2837
+ return "button";
2838
+ case "checkbox":
2839
+ return "checkbox";
2840
+ case "radio":
2841
+ return "radio";
2842
+ case "range":
2843
+ return "slider";
2844
+ case "search":
2845
+ return "searchbox";
2846
+ default:
2847
+ return "textbox";
2848
+ }
2849
+ }
2850
+ case "textarea":
2851
+ return "textbox";
2852
+ case "select":
2853
+ return element.hasAttribute("multiple") ? "listbox" : "combobox";
2854
+ case "nav":
2855
+ return "navigation";
2856
+ case "main":
2857
+ return "main";
2858
+ case "header":
2859
+ return "banner";
2860
+ case "footer":
2861
+ return "contentinfo";
2862
+ case "aside":
2863
+ return "complementary";
2864
+ case "form":
2865
+ return "form";
2866
+ case "section":
2867
+ return element.hasAttribute("aria-label") || element.hasAttribute("aria-labelledby") ? "region" : "generic";
2868
+ case "article":
2869
+ return "article";
2870
+ case "dialog":
2871
+ return "dialog";
2872
+ case "table":
2873
+ return "table";
2874
+ case "ul":
2875
+ case "ol":
2876
+ return "list";
2877
+ case "li":
2878
+ return "listitem";
2879
+ case "img":
2880
+ return element.getAttribute("alt") === "" ? "presentation" : "img";
2881
+ case "h1":
2882
+ case "h2":
2883
+ case "h3":
2884
+ case "h4":
2885
+ case "h5":
2886
+ case "h6":
2887
+ return "heading";
2888
+ case "option":
2889
+ return "option";
2890
+ case "progress":
2891
+ return "progressbar";
2892
+ case "output":
2893
+ return "status";
2894
+ case "menu":
2895
+ return "menu";
2896
+ default:
2897
+ return "generic";
2898
+ }
2899
+ }
2900
+ function createFocusObserver(options) {
2901
+ const { document: doc, onEvent, getTimestamp } = options;
2902
+ let active = false;
2903
+ let previousTarget = null;
2904
+ function buildEventTarget2(element) {
2905
+ return {
2906
+ role: getElementRole(element),
2907
+ accessibleName: computeAccessibleName2(element, doc),
2908
+ selector: generateSelector(element)
2909
+ };
2910
+ }
2911
+ function handleFocusIn(event) {
2912
+ if (!active) return;
2913
+ const target = event.target;
2914
+ if (!target || !(target instanceof doc.defaultView.Element)) {
2915
+ return;
2916
+ }
2917
+ const currentTarget = buildEventTarget2(target);
2918
+ const a11yEvent = {
2919
+ type: "FOCUS_CHANGED",
2920
+ timestamp: getTimestamp(),
2921
+ target: currentTarget,
2922
+ payload: {
2923
+ kind: "focus_changed",
2924
+ previousTarget
2925
+ }
2926
+ };
2927
+ onEvent(a11yEvent);
2928
+ previousTarget = currentTarget;
2929
+ }
2930
+ return {
2931
+ start() {
2932
+ if (active) return;
2933
+ active = true;
2934
+ previousTarget = null;
2935
+ doc.addEventListener("focusin", handleFocusIn);
2936
+ },
2937
+ stop() {
2938
+ if (!active) return;
2939
+ active = false;
2940
+ doc.removeEventListener("focusin", handleFocusIn);
2941
+ },
2942
+ get isActive() {
2943
+ return active;
2944
+ }
2945
+ };
2946
+ }
2947
+
2948
+ // src/runtime/observers/mutation-observer.ts
2949
+ var ROLE_ATTRIBUTE = "role";
2950
+ var NAME_ATTRIBUTES = /* @__PURE__ */ new Set(["aria-label", "aria-labelledby"]);
2951
+ var STATE_ATTRIBUTES = /* @__PURE__ */ new Set([
2952
+ "aria-expanded",
2953
+ "aria-selected",
2954
+ "aria-checked",
2955
+ "aria-disabled",
2956
+ "aria-hidden"
2957
+ ]);
2958
+ var OBSERVED_ATTRIBUTES = [
2959
+ ROLE_ATTRIBUTE,
2960
+ "aria-label",
2961
+ "aria-labelledby",
2962
+ "aria-expanded",
2963
+ "aria-selected",
2964
+ "aria-checked",
2965
+ "aria-disabled",
2966
+ "aria-hidden"
2967
+ ];
2968
+ function computeAccessibleName3(element, document) {
2969
+ const ariaLabel = element.getAttribute("aria-label");
2970
+ if (ariaLabel && ariaLabel.trim()) {
2971
+ return ariaLabel.trim();
2972
+ }
2973
+ const labelledBy = element.getAttribute("aria-labelledby");
2974
+ if (labelledBy && labelledBy.trim()) {
2975
+ const ids = labelledBy.trim().split(/\s+/);
2976
+ const parts = [];
2977
+ for (const id of ids) {
2978
+ const referenced = document.getElementById(id);
2979
+ if (referenced && referenced.textContent) {
2980
+ parts.push(referenced.textContent.trim());
2981
+ }
2982
+ }
2983
+ const combined = parts.join(" ");
2984
+ if (combined) {
2985
+ return combined;
2986
+ }
2987
+ }
2988
+ const textContent = element.textContent;
2989
+ if (textContent && textContent.trim()) {
2990
+ return textContent.trim();
2991
+ }
2992
+ return "";
2993
+ }
2994
+ function getElementRole2(element) {
2995
+ const explicitRole = element.getAttribute("role");
2996
+ if (explicitRole && explicitRole.trim()) {
2997
+ return explicitRole.trim();
2998
+ }
2999
+ const tagName = element.tagName.toLowerCase();
3000
+ switch (tagName) {
3001
+ case "button":
3002
+ return "button";
3003
+ case "a":
3004
+ return element.hasAttribute("href") ? "link" : "generic";
3005
+ case "input": {
3006
+ const type = (element.getAttribute("type") || "text").toLowerCase();
3007
+ switch (type) {
3008
+ case "button":
3009
+ case "submit":
3010
+ case "reset":
3011
+ case "image":
3012
+ return "button";
3013
+ case "checkbox":
3014
+ return "checkbox";
3015
+ case "radio":
3016
+ return "radio";
3017
+ case "range":
3018
+ return "slider";
3019
+ case "search":
3020
+ return "searchbox";
3021
+ default:
3022
+ return "textbox";
3023
+ }
3024
+ }
3025
+ case "textarea":
3026
+ return "textbox";
3027
+ case "select":
3028
+ return element.hasAttribute("multiple") ? "listbox" : "combobox";
3029
+ case "nav":
3030
+ return "navigation";
3031
+ case "main":
3032
+ return "main";
3033
+ case "header":
3034
+ return "banner";
3035
+ case "footer":
3036
+ return "contentinfo";
3037
+ case "aside":
3038
+ return "complementary";
3039
+ case "form":
3040
+ return "form";
3041
+ case "section":
3042
+ return element.hasAttribute("aria-label") || element.hasAttribute("aria-labelledby") ? "region" : "generic";
3043
+ case "article":
3044
+ return "article";
3045
+ case "dialog":
3046
+ return "dialog";
3047
+ case "table":
3048
+ return "table";
3049
+ case "ul":
3050
+ case "ol":
3051
+ return "list";
3052
+ case "li":
3053
+ return "listitem";
3054
+ case "img":
3055
+ return element.getAttribute("alt") === "" ? "presentation" : "img";
3056
+ case "h1":
3057
+ case "h2":
3058
+ case "h3":
3059
+ case "h4":
3060
+ case "h5":
3061
+ case "h6":
3062
+ return "heading";
3063
+ case "option":
3064
+ return "option";
3065
+ case "progress":
3066
+ return "progressbar";
3067
+ case "output":
3068
+ return "status";
3069
+ case "menu":
3070
+ return "menu";
3071
+ default:
3072
+ return "generic";
3073
+ }
3074
+ }
3075
+ function createMutationObserver(options) {
3076
+ const { document: doc, onEvent, getTimestamp } = options;
3077
+ let observer = null;
3078
+ let active = false;
3079
+ function handleMutations(mutations) {
3080
+ if (!active) return;
3081
+ for (const mutation of mutations) {
3082
+ if (mutation.type !== "attributes") {
3083
+ continue;
3084
+ }
3085
+ const attributeName = mutation.attributeName;
3086
+ if (!attributeName) {
3087
+ continue;
3088
+ }
3089
+ const target = mutation.target;
3090
+ if (!(target instanceof Element)) {
3091
+ continue;
3092
+ }
3093
+ if (attributeName === ROLE_ATTRIBUTE) {
3094
+ handleRoleChange(target, mutation.oldValue);
3095
+ } else if (NAME_ATTRIBUTES.has(attributeName)) {
3096
+ handleNameChange(target, attributeName, mutation.oldValue);
3097
+ } else if (STATE_ATTRIBUTES.has(attributeName)) {
3098
+ handleStateChange(target, attributeName, mutation.oldValue);
3099
+ }
3100
+ }
3101
+ }
3102
+ function handleRoleChange(element, oldValue) {
3103
+ const previousRole = oldValue?.trim() || getImplicitRole(element);
3104
+ const newRole = element.getAttribute("role")?.trim() || getImplicitRole(element);
3105
+ if (previousRole === newRole) {
3106
+ return;
3107
+ }
3108
+ const eventTarget = buildEventTarget2(element);
3109
+ const payload = {
3110
+ kind: "role_changed",
3111
+ previousRole,
3112
+ newRole
3113
+ };
3114
+ onEvent({
3115
+ type: "ROLE_CHANGED",
3116
+ timestamp: getTimestamp(),
3117
+ target: eventTarget,
3118
+ payload
3119
+ });
3120
+ }
3121
+ function handleNameChange(element, attributeName, oldValue) {
3122
+ let previousName;
3123
+ let newName;
3124
+ if (attributeName === "aria-label") {
3125
+ previousName = oldValue?.trim() || "";
3126
+ newName = computeAccessibleName3(element, doc);
3127
+ if (!previousName && oldValue === null) {
3128
+ const labelledBy = element.getAttribute("aria-labelledby");
3129
+ if (labelledBy) {
3130
+ previousName = resolveAriaLabelledBy(element, labelledBy);
3131
+ } else {
3132
+ previousName = element.textContent?.trim() || "";
3133
+ }
3134
+ }
3135
+ } else {
3136
+ previousName = oldValue ? resolveAriaLabelledBy(element, oldValue) : "";
3137
+ if (!previousName && oldValue === null) {
3138
+ const ariaLabel = element.getAttribute("aria-label");
3139
+ if (ariaLabel) {
3140
+ previousName = ariaLabel.trim();
3141
+ } else {
3142
+ previousName = element.textContent?.trim() || "";
3143
+ }
3144
+ }
3145
+ newName = computeAccessibleName3(element, doc);
3146
+ }
3147
+ if (previousName === newName) {
3148
+ return;
3149
+ }
3150
+ const eventTarget = buildEventTarget2(element);
3151
+ const payload = {
3152
+ kind: "accessible_name_changed",
3153
+ previousName,
3154
+ newName
3155
+ };
3156
+ onEvent({
3157
+ type: "ACCESSIBLE_NAME_CHANGED",
3158
+ timestamp: getTimestamp(),
3159
+ target: eventTarget,
3160
+ payload
3161
+ });
3162
+ }
3163
+ function handleStateChange(element, attributeName, oldValue) {
3164
+ const currentValue = element.getAttribute(attributeName);
3165
+ const normalizedOld = normalizeStateValue(oldValue);
3166
+ const normalizedNew = normalizeStateValue(currentValue);
3167
+ if (normalizedOld === normalizedNew) {
3168
+ return;
3169
+ }
3170
+ const eventTarget = buildEventTarget2(element);
3171
+ const payload = {
3172
+ kind: "state_changed",
3173
+ attribute: attributeName,
3174
+ previousValue: normalizedOld,
3175
+ newValue: normalizedNew
3176
+ };
3177
+ onEvent({
3178
+ type: "STATE_CHANGED",
3179
+ timestamp: getTimestamp(),
3180
+ target: eventTarget,
3181
+ payload
3182
+ });
3183
+ }
3184
+ function buildEventTarget2(element) {
3185
+ return {
3186
+ role: getElementRole2(element),
3187
+ accessibleName: computeAccessibleName3(element, doc),
3188
+ selector: generateSelector(element)
3189
+ };
3190
+ }
3191
+ function getImplicitRole(element) {
3192
+ const tagName = element.tagName.toLowerCase();
3193
+ switch (tagName) {
3194
+ case "button":
3195
+ return "button";
3196
+ case "a":
3197
+ return element.hasAttribute("href") ? "link" : "generic";
3198
+ case "input": {
3199
+ const type = (element.getAttribute("type") || "text").toLowerCase();
3200
+ switch (type) {
3201
+ case "button":
3202
+ case "submit":
3203
+ case "reset":
3204
+ case "image":
3205
+ return "button";
3206
+ case "checkbox":
3207
+ return "checkbox";
3208
+ case "radio":
3209
+ return "radio";
3210
+ default:
3211
+ return "textbox";
3212
+ }
3213
+ }
3214
+ default:
3215
+ return "generic";
3216
+ }
3217
+ }
3218
+ function resolveAriaLabelledBy(element, idRefs) {
3219
+ const ownerDoc = element.ownerDocument;
3220
+ if (!ownerDoc) {
3221
+ return "";
3222
+ }
3223
+ const ids = idRefs.trim().split(/\s+/).filter(Boolean);
3224
+ const parts = [];
3225
+ for (const id of ids) {
3226
+ const referenced = ownerDoc.getElementById(id);
3227
+ if (referenced && referenced.textContent) {
3228
+ parts.push(referenced.textContent.trim());
3229
+ }
3230
+ }
3231
+ return parts.join(" ");
3232
+ }
3233
+ function normalizeStateValue(value) {
3234
+ if (value === null) {
3235
+ return null;
3236
+ }
3237
+ if (value === "true") {
3238
+ return true;
3239
+ }
3240
+ if (value === "false") {
3241
+ return false;
3242
+ }
3243
+ return value;
3244
+ }
3245
+ return {
3246
+ start() {
3247
+ if (active) return;
3248
+ active = true;
3249
+ observer = new MutationObserver(handleMutations);
3250
+ observer.observe(doc.body ?? doc.documentElement, {
3251
+ attributes: true,
3252
+ attributeOldValue: true,
3253
+ attributeFilter: OBSERVED_ATTRIBUTES,
3254
+ subtree: true
3255
+ });
3256
+ },
3257
+ stop() {
3258
+ if (!active) return;
3259
+ active = false;
3260
+ if (observer) {
3261
+ observer.disconnect();
3262
+ observer = null;
3263
+ }
3264
+ },
3265
+ get isActive() {
3266
+ return active;
3267
+ }
3268
+ };
3269
+ }
3270
+
3271
+ // src/runtime/observers/live-region-observer.ts
3272
+ var IMPLICIT_LIVE_ROLES = /* @__PURE__ */ new Set(["alert", "status", "log", "marquee", "timer"]);
3273
+ var ROLE_POLITENESS_MAP = {
3274
+ alert: "assertive",
3275
+ status: "polite",
3276
+ log: "polite",
3277
+ marquee: "polite",
3278
+ timer: "polite"
3279
+ };
3280
+ function createLiveRegionObserver(document, callback) {
3281
+ let contentObserver = null;
3282
+ let documentObserver = null;
3283
+ const trackedRegions = /* @__PURE__ */ new Set();
3284
+ function getLiveRegionPoliteness(element) {
3285
+ const ariaLive = element.getAttribute("aria-live");
3286
+ if (ariaLive === "assertive") return "assertive";
3287
+ if (ariaLive === "polite") return "polite";
3288
+ if (ariaLive === "off") return null;
3289
+ const role = element.getAttribute("role");
3290
+ if (role && IMPLICIT_LIVE_ROLES.has(role)) {
3291
+ return ROLE_POLITENESS_MAP[role] || "polite";
3292
+ }
3293
+ if (ariaLive && ariaLive !== "off") return "polite";
3294
+ return null;
3295
+ }
3296
+ function isAtomic(element) {
3297
+ return element.getAttribute("aria-atomic") === "true";
3298
+ }
3299
+ function buildEventTarget2(element) {
3300
+ const role = element.getAttribute("role") || "region";
3301
+ const accessibleName = element.getAttribute("aria-label") || element.getAttribute("aria-labelledby") || "";
3302
+ const selector = generateSelector(element);
3303
+ return { role, accessibleName, selector };
3304
+ }
3305
+ function getTextFromNodes(nodes) {
3306
+ const parts = [];
3307
+ nodes.forEach((node) => {
3308
+ if (node.nodeType === Node.TEXT_NODE) {
3309
+ const text = node.textContent?.trim();
3310
+ if (text) parts.push(text);
3311
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
3312
+ const text = node.textContent?.trim();
3313
+ if (text) parts.push(text);
3314
+ }
3315
+ });
3316
+ return parts.join(" ").trim();
3317
+ }
3318
+ function emitAnnouncement(liveRegion, text, politeness) {
3319
+ if (!text) return;
3320
+ const target = buildEventTarget2(liveRegion);
3321
+ callback({
3322
+ type: "ANNOUNCEMENT",
3323
+ target,
3324
+ payload: {
3325
+ kind: "announcement",
3326
+ politeness,
3327
+ text
3328
+ }
3329
+ });
3330
+ }
3331
+ function findLiveRegionAncestor(node) {
3332
+ let current = node;
3333
+ while (current) {
3334
+ if (current.nodeType === Node.ELEMENT_NODE && trackedRegions.has(current)) {
3335
+ return current;
3336
+ }
3337
+ current = current.parentNode;
3338
+ }
3339
+ return null;
3340
+ }
3341
+ function handleContentMutations(mutations) {
3342
+ const regionChanges = /* @__PURE__ */ new Map();
3343
+ for (const mutation of mutations) {
3344
+ const liveRegion = findLiveRegionAncestor(mutation.target);
3345
+ if (!liveRegion) continue;
3346
+ if (!regionChanges.has(liveRegion)) {
3347
+ regionChanges.set(liveRegion, { addedText: [], charDataChanged: false });
3348
+ }
3349
+ const changes = regionChanges.get(liveRegion);
3350
+ if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
3351
+ const text = getTextFromNodes(mutation.addedNodes);
3352
+ if (text) {
3353
+ changes.addedText.push(text);
3354
+ }
3355
+ } else if (mutation.type === "characterData") {
3356
+ changes.charDataChanged = true;
3357
+ }
3358
+ }
3359
+ for (const [region, changes] of regionChanges) {
3360
+ const politeness = getLiveRegionPoliteness(region);
3361
+ if (!politeness) continue;
3362
+ let text;
3363
+ if (isAtomic(region)) {
3364
+ text = region.textContent?.trim() || "";
3365
+ } else {
3366
+ if (changes.addedText.length > 0) {
3367
+ text = changes.addedText.join(" ").trim();
3368
+ } else if (changes.charDataChanged) {
3369
+ text = region.textContent?.trim() || "";
3370
+ } else {
3371
+ text = "";
3372
+ }
3373
+ }
3374
+ emitAnnouncement(region, text, politeness);
3375
+ }
3376
+ }
3377
+ function handleDocumentMutations(mutations) {
3378
+ for (const mutation of mutations) {
3379
+ if (mutation.type !== "childList") continue;
3380
+ mutation.addedNodes.forEach((node) => {
3381
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
3382
+ const element = node;
3383
+ if (getLiveRegionPoliteness(element) !== null && !trackedRegions.has(element)) {
3384
+ trackRegion(element);
3385
+ }
3386
+ const descendants = element.querySelectorAll("[aria-live], [role]");
3387
+ descendants.forEach((desc) => {
3388
+ if (getLiveRegionPoliteness(desc) !== null && !trackedRegions.has(desc)) {
3389
+ trackRegion(desc);
3390
+ }
3391
+ });
3392
+ });
3393
+ mutation.removedNodes.forEach((node) => {
3394
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
3395
+ const element = node;
3396
+ if (trackedRegions.has(element)) {
3397
+ trackedRegions.delete(element);
3398
+ }
3399
+ const descendants = element.querySelectorAll("[aria-live], [role]");
3400
+ descendants.forEach((desc) => {
3401
+ trackedRegions.delete(desc);
3402
+ });
3403
+ });
3404
+ }
3405
+ }
3406
+ function trackRegion(element) {
3407
+ trackedRegions.add(element);
3408
+ }
3409
+ function discoverExistingRegions() {
3410
+ const ariaLiveElements = document.querySelectorAll("[aria-live]");
3411
+ ariaLiveElements.forEach((el) => {
3412
+ if (getLiveRegionPoliteness(el) !== null) {
3413
+ trackRegion(el);
3414
+ }
3415
+ });
3416
+ IMPLICIT_LIVE_ROLES.forEach((role) => {
3417
+ const roleElements = document.querySelectorAll(`[role="${role}"]`);
3418
+ roleElements.forEach((el) => {
3419
+ if (!trackedRegions.has(el)) {
3420
+ trackRegion(el);
3421
+ }
3422
+ });
3423
+ });
3424
+ }
3425
+ function start() {
3426
+ discoverExistingRegions();
3427
+ contentObserver = new MutationObserver(handleContentMutations);
3428
+ const body = document.body;
3429
+ if (body) {
3430
+ contentObserver.observe(body, {
3431
+ childList: true,
3432
+ characterData: true,
3433
+ subtree: true,
3434
+ characterDataOldValue: true
3435
+ });
3436
+ }
3437
+ documentObserver = new MutationObserver(handleDocumentMutations);
3438
+ if (body) {
3439
+ documentObserver.observe(body, {
3440
+ childList: true,
3441
+ subtree: true
3442
+ });
3443
+ }
3444
+ }
3445
+ function stop() {
3446
+ if (contentObserver) {
3447
+ contentObserver.disconnect();
3448
+ contentObserver = null;
3449
+ }
3450
+ if (documentObserver) {
3451
+ documentObserver.disconnect();
3452
+ documentObserver = null;
3453
+ }
3454
+ trackedRegions.clear();
3455
+ }
3456
+ return { start, stop };
3457
+ }
3458
+
3459
+ // src/runtime/observers/dialog-observer.ts
3460
+ function computeDialogAccessibleName(element, document) {
3461
+ const ariaLabel = element.getAttribute("aria-label");
3462
+ if (ariaLabel && ariaLabel.trim()) {
3463
+ return ariaLabel.trim();
3464
+ }
3465
+ const labelledBy = element.getAttribute("aria-labelledby");
3466
+ if (labelledBy && labelledBy.trim()) {
3467
+ const ids = labelledBy.trim().split(/\s+/);
3468
+ const parts = [];
3469
+ for (const id of ids) {
3470
+ const referenced = document.getElementById(id);
3471
+ if (referenced && referenced.textContent) {
3472
+ parts.push(referenced.textContent.trim());
3473
+ }
3474
+ }
3475
+ const combined = parts.join(" ");
3476
+ if (combined) {
3477
+ return combined;
3478
+ }
3479
+ }
3480
+ const title = element.getAttribute("title");
3481
+ if (title && title.trim()) {
3482
+ return title.trim();
3483
+ }
3484
+ const heading = element.querySelector("h1, h2, h3, h4, h5, h6");
3485
+ if (heading && heading.textContent && heading.textContent.trim()) {
3486
+ return heading.textContent.trim();
3487
+ }
3488
+ return "";
3489
+ }
3490
+ function getDialogRole(element) {
3491
+ const explicitRole = element.getAttribute("role");
3492
+ if (explicitRole && explicitRole.trim()) {
3493
+ return explicitRole.trim();
3494
+ }
3495
+ if (element.tagName.toLowerCase() === "dialog") {
3496
+ return "dialog";
3497
+ }
3498
+ return "generic";
3499
+ }
3500
+ function isDialogElement(element) {
3501
+ if (element.tagName.toLowerCase() === "dialog") {
3502
+ return true;
3503
+ }
3504
+ const role = element.getAttribute("role");
3505
+ return role === "dialog" || role === "alertdialog";
3506
+ }
3507
+ function isDialogModal(element) {
3508
+ const ariaModal = element.getAttribute("aria-modal");
3509
+ if (ariaModal === "true") {
3510
+ return true;
3511
+ }
3512
+ return false;
3513
+ }
3514
+ function createDialogObserver(options) {
3515
+ const { document: doc, onEvent, getTimestamp } = options;
3516
+ let active = false;
3517
+ let mutationObserver = null;
3518
+ const openDialogStack = [];
3519
+ function buildEventTarget2(element) {
3520
+ return {
3521
+ role: getDialogRole(element),
3522
+ accessibleName: computeDialogAccessibleName(element, doc),
3523
+ selector: generateSelector(element)
3524
+ };
3525
+ }
3526
+ function emitDialogOpened(element) {
3527
+ const name = computeDialogAccessibleName(element, doc);
3528
+ const isModal = isDialogModal(element);
3529
+ const target = buildEventTarget2(element);
3530
+ openDialogStack.push({
3531
+ element,
3532
+ name,
3533
+ selector: target.selector
3534
+ });
3535
+ const a11yEvent = {
3536
+ type: "DIALOG_OPENED",
3537
+ timestamp: getTimestamp(),
3538
+ target,
3539
+ payload: {
3540
+ kind: "dialog_opened",
3541
+ dialogName: name,
3542
+ isModal
3543
+ }
3544
+ };
3545
+ onEvent(a11yEvent);
3546
+ }
3547
+ function emitDialogClosed(element) {
3548
+ const name = computeDialogAccessibleName(element, doc);
3549
+ const target = buildEventTarget2(element);
3550
+ const index = openDialogStack.findIndex((d) => d.element === element);
3551
+ if (index !== -1) {
3552
+ openDialogStack.splice(index, 1);
3553
+ }
3554
+ const a11yEvent = {
3555
+ type: "DIALOG_CLOSED",
3556
+ timestamp: getTimestamp(),
3557
+ target,
3558
+ payload: {
3559
+ kind: "dialog_closed",
3560
+ dialogName: name
3561
+ }
3562
+ };
3563
+ onEvent(a11yEvent);
3564
+ }
3565
+ function isTrackedAsOpen(element) {
3566
+ return openDialogStack.some((d) => d.element === element);
3567
+ }
3568
+ function handleMutations(mutations) {
3569
+ if (!active) return;
3570
+ for (const mutation of mutations) {
3571
+ if (mutation.type === "attributes") {
3572
+ const target = mutation.target;
3573
+ if (!(target instanceof doc.defaultView.Element)) continue;
3574
+ if (mutation.attributeName === "open" && target.tagName.toLowerCase() === "dialog") {
3575
+ if (target.hasAttribute("open")) {
3576
+ if (!isTrackedAsOpen(target)) {
3577
+ emitDialogOpened(target);
3578
+ }
3579
+ } else {
3580
+ if (isTrackedAsOpen(target)) {
3581
+ emitDialogClosed(target);
3582
+ }
3583
+ }
3584
+ }
3585
+ if (mutation.attributeName === "aria-modal" && isDialogElement(target)) {
3586
+ if (!isTrackedAsOpen(target) && isVisibleDialog(target)) {
3587
+ emitDialogOpened(target);
3588
+ }
3589
+ }
3590
+ if (mutation.attributeName === "role") {
3591
+ const oldRole = mutation.oldValue;
3592
+ const newRole = target.getAttribute("role");
3593
+ const wasDialog = oldRole === "dialog" || oldRole === "alertdialog";
3594
+ const isNowDialog = newRole === "dialog" || newRole === "alertdialog";
3595
+ if (!wasDialog && isNowDialog && isVisibleDialog(target)) {
3596
+ emitDialogOpened(target);
3597
+ } else if (wasDialog && !isNowDialog && isTrackedAsOpen(target)) {
3598
+ emitDialogClosed(target);
3599
+ }
3600
+ }
3601
+ }
3602
+ if (mutation.type === "childList") {
3603
+ for (let i = 0; i < mutation.addedNodes.length; i++) {
3604
+ const node = mutation.addedNodes[i];
3605
+ if (!(node instanceof doc.defaultView.Element)) continue;
3606
+ if (isDialogElement(node) && isVisibleDialog(node)) {
3607
+ if (!isTrackedAsOpen(node)) {
3608
+ emitDialogOpened(node);
3609
+ }
3610
+ }
3611
+ const dialogDescendants = node.querySelectorAll(
3612
+ 'dialog[open], [role="dialog"], [role="alertdialog"]'
3613
+ );
3614
+ for (let j = 0; j < dialogDescendants.length; j++) {
3615
+ const dialog = dialogDescendants[j];
3616
+ if (isVisibleDialog(dialog) && !isTrackedAsOpen(dialog)) {
3617
+ emitDialogOpened(dialog);
3618
+ }
3619
+ }
3620
+ }
3621
+ for (let i = 0; i < mutation.removedNodes.length; i++) {
3622
+ const node = mutation.removedNodes[i];
3623
+ if (!(node instanceof doc.defaultView.Element)) continue;
3624
+ if (isTrackedAsOpen(node)) {
3625
+ emitDialogClosed(node);
3626
+ }
3627
+ const trackedInRemoved = openDialogStack.filter(
3628
+ (d) => node.contains(d.element)
3629
+ );
3630
+ for (const tracked of trackedInRemoved) {
3631
+ emitDialogClosed(tracked.element);
3632
+ }
3633
+ }
3634
+ }
3635
+ }
3636
+ }
3637
+ function isVisibleDialog(element) {
3638
+ if (element.tagName.toLowerCase() === "dialog") {
3639
+ return element.hasAttribute("open");
3640
+ }
3641
+ return true;
3642
+ }
3643
+ return {
3644
+ start() {
3645
+ if (active) return;
3646
+ active = true;
3647
+ openDialogStack.length = 0;
3648
+ const existingDialogs = doc.querySelectorAll(
3649
+ 'dialog[open], [role="dialog"], [role="alertdialog"]'
3650
+ );
3651
+ for (let i = 0; i < existingDialogs.length; i++) {
3652
+ const dialog = existingDialogs[i];
3653
+ if (isVisibleDialog(dialog)) {
3654
+ openDialogStack.push({
3655
+ element: dialog,
3656
+ name: computeDialogAccessibleName(dialog, doc),
3657
+ selector: generateSelector(dialog)
3658
+ });
3659
+ }
3660
+ }
3661
+ mutationObserver = new MutationObserver(handleMutations);
3662
+ mutationObserver.observe(doc.body || doc.documentElement, {
3663
+ attributes: true,
3664
+ attributeFilter: ["open", "role", "aria-modal"],
3665
+ attributeOldValue: true,
3666
+ childList: true,
3667
+ subtree: true
3668
+ });
3669
+ },
3670
+ stop() {
3671
+ if (!active) return;
3672
+ active = false;
3673
+ if (mutationObserver) {
3674
+ mutationObserver.disconnect();
3675
+ mutationObserver = null;
3676
+ }
3677
+ openDialogStack.length = 0;
3678
+ },
3679
+ get isActive() {
3680
+ return active;
3681
+ },
3682
+ getOpenDialogs() {
3683
+ return openDialogStack.map((d) => d.name);
3684
+ }
3685
+ };
3686
+ }
3687
+
3688
+ // src/runtime/engine.ts
3689
+ function createEngine(options) {
3690
+ const { document: doc } = options;
3691
+ let attached = false;
3692
+ let sessionStart = 0;
3693
+ let events = [];
3694
+ function getTimestamp() {
3695
+ return Date.now() - sessionStart;
3696
+ }
3697
+ function collectEvent(event) {
3698
+ events.push(event);
3699
+ }
3700
+ function collectLiveRegionEvent(event) {
3701
+ const fullEvent = {
3702
+ ...event,
3703
+ timestamp: getTimestamp()
3704
+ };
3705
+ events.push(fullEvent);
3706
+ }
3707
+ const focusObs = createFocusObserver({
3708
+ document: doc,
3709
+ onEvent: collectEvent,
3710
+ getTimestamp
3711
+ });
3712
+ const mutationObs = createMutationObserver({
3713
+ document: doc,
3714
+ onEvent: collectEvent,
3715
+ getTimestamp
3716
+ });
3717
+ const liveRegionObs = createLiveRegionObserver(
3718
+ doc,
3719
+ collectLiveRegionEvent
3720
+ );
3721
+ const dialogObs = createDialogObserver({
3722
+ document: doc,
3723
+ onEvent: collectEvent,
3724
+ getTimestamp
3725
+ });
3726
+ return {
3727
+ attach() {
3728
+ if (attached) return;
3729
+ attached = true;
3730
+ sessionStart = Date.now();
3731
+ events = [];
3732
+ focusObs.start();
3733
+ mutationObs.start();
3734
+ liveRegionObs.start();
3735
+ dialogObs.start();
3736
+ },
3737
+ detach() {
3738
+ if (!attached) return;
3739
+ attached = false;
3740
+ focusObs.stop();
3741
+ mutationObs.stop();
3742
+ liveRegionObs.stop();
3743
+ dialogObs.stop();
3744
+ },
3745
+ getEvents() {
3746
+ return [...events];
3747
+ },
3748
+ reset() {
3749
+ events = [];
3750
+ },
3751
+ get isAttached() {
3752
+ return attached;
3753
+ },
3754
+ get dialogObserver() {
3755
+ return {
3756
+ getOpenDialogs() {
3757
+ return dialogObs.getOpenDialogs();
3758
+ }
3759
+ };
3760
+ }
3761
+ };
3762
+ }
3763
+
3764
+ // src/runtime/interactions.ts
3765
+ var KEY_MAP = {
3766
+ Tab: { key: "Tab", code: "Tab", keyCode: 9 },
3767
+ Escape: { key: "Escape", code: "Escape", keyCode: 27 },
3768
+ Enter: { key: "Enter", code: "Enter", keyCode: 13 },
3769
+ " ": { key: " ", code: "Space", keyCode: 32 },
3770
+ ArrowUp: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
3771
+ ArrowDown: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
3772
+ ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
3773
+ ArrowRight: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 }
3774
+ };
3775
+ var FOCUSABLE_SELECTOR = [
3776
+ "button:not([disabled])",
3777
+ "a[href]",
3778
+ "input:not([disabled])",
3779
+ "select:not([disabled])",
3780
+ "textarea:not([disabled])",
3781
+ '[tabindex]:not([tabindex="-1"])'
3782
+ ].join(", ");
3783
+ function getFocusableElements(document) {
3784
+ return Array.from(document.querySelectorAll(FOCUSABLE_SELECTOR));
3785
+ }
3786
+ function computeAccessibleName4(element, document) {
3787
+ const ariaLabel = element.getAttribute("aria-label");
3788
+ if (ariaLabel && ariaLabel.trim()) {
3789
+ return ariaLabel.trim();
3790
+ }
3791
+ const labelledBy = element.getAttribute("aria-labelledby");
3792
+ if (labelledBy && labelledBy.trim()) {
3793
+ const ids = labelledBy.trim().split(/\s+/);
3794
+ const parts = [];
3795
+ for (const id of ids) {
3796
+ const referenced = document.getElementById(id);
3797
+ if (referenced && referenced.textContent) {
3798
+ parts.push(referenced.textContent.trim());
3799
+ }
3800
+ }
3801
+ const combined = parts.join(" ");
3802
+ if (combined) return combined;
3803
+ }
3804
+ const textContent = element.textContent;
3805
+ if (textContent && textContent.trim()) {
3806
+ return textContent.trim();
3807
+ }
3808
+ return "";
3809
+ }
3810
+ function getElementRole3(element) {
3811
+ const explicitRole = element.getAttribute("role");
3812
+ if (explicitRole && explicitRole.trim()) {
3813
+ return explicitRole.trim();
3814
+ }
3815
+ const tagName = element.tagName.toLowerCase();
3816
+ switch (tagName) {
3817
+ case "button":
3818
+ return "button";
3819
+ case "a":
3820
+ return element.hasAttribute("href") ? "link" : "generic";
3821
+ case "input": {
3822
+ const type = (element.getAttribute("type") || "text").toLowerCase();
3823
+ switch (type) {
3824
+ case "button":
3825
+ case "submit":
3826
+ case "reset":
3827
+ case "image":
3828
+ return "button";
3829
+ case "checkbox":
3830
+ return "checkbox";
3831
+ case "radio":
3832
+ return "radio";
3833
+ case "range":
3834
+ return "slider";
3835
+ case "search":
3836
+ return "searchbox";
3837
+ default:
3838
+ return "textbox";
3839
+ }
3840
+ }
3841
+ case "textarea":
3842
+ return "textbox";
3843
+ case "select":
3844
+ return element.hasAttribute("multiple") ? "listbox" : "combobox";
3845
+ case "dialog":
3846
+ return "dialog";
3847
+ default:
3848
+ return "generic";
3849
+ }
3850
+ }
3851
+ function buildEventTarget(element, document) {
3852
+ return {
3853
+ role: getElementRole3(element),
3854
+ accessibleName: computeAccessibleName4(element, document),
3855
+ selector: generateSelector(element)
3856
+ };
3857
+ }
3858
+ function dispatchKeyboardEvent(document, options) {
3859
+ const target = document.activeElement || document.body;
3860
+ const commonProps = {
3861
+ key: options.key,
3862
+ code: options.code,
3863
+ keyCode: options.keyCode,
3864
+ which: options.keyCode,
3865
+ shiftKey: options.shiftKey || false,
3866
+ ctrlKey: options.ctrlKey || false,
3867
+ altKey: options.altKey || false,
3868
+ metaKey: options.metaKey || false,
3869
+ bubbles: true,
3870
+ cancelable: true
3871
+ };
3872
+ target.dispatchEvent(new KeyboardEvent("keydown", commonProps));
3873
+ if (options.key.length === 1) {
3874
+ target.dispatchEvent(new KeyboardEvent("keypress", commonProps));
3875
+ }
3876
+ target.dispatchEvent(new KeyboardEvent("keyup", commonProps));
3877
+ }
3878
+ function parseKeyCombo(combo) {
3879
+ const parts = combo.split("+");
3880
+ const modifiers = [];
3881
+ let shiftKey = false;
3882
+ let ctrlKey = false;
3883
+ let altKey = false;
3884
+ let metaKey = false;
3885
+ const key = parts[parts.length - 1];
3886
+ for (let i = 0; i < parts.length - 1; i++) {
3887
+ const mod = parts[i].toLowerCase();
3888
+ switch (mod) {
3889
+ case "shift":
3890
+ shiftKey = true;
3891
+ modifiers.push("Shift");
3892
+ break;
3893
+ case "control":
3894
+ case "ctrl":
3895
+ ctrlKey = true;
3896
+ modifiers.push("Control");
3897
+ break;
3898
+ case "alt":
3899
+ altKey = true;
3900
+ modifiers.push("Alt");
3901
+ break;
3902
+ case "meta":
3903
+ case "cmd":
3904
+ case "command":
3905
+ metaKey = true;
3906
+ modifiers.push("Meta");
3907
+ break;
3908
+ }
3909
+ }
3910
+ return { key, modifiers, shiftKey, ctrlKey, altKey, metaKey };
3911
+ }
3912
+ function getKeyInfo(key) {
3913
+ if (KEY_MAP[key]) {
3914
+ return KEY_MAP[key];
3915
+ }
3916
+ if (key.length === 1) {
3917
+ return {
3918
+ key,
3919
+ code: `Key${key.toUpperCase()}`,
3920
+ keyCode: key.toUpperCase().charCodeAt(0)
3921
+ };
3922
+ }
3923
+ return {
3924
+ key,
3925
+ code: key,
3926
+ keyCode: 0
3927
+ };
3928
+ }
3929
+ function executeClick(selector, document, onEvent, getTimestamp) {
3930
+ const element = document.querySelector(selector);
3931
+ if (!element) {
3932
+ const warningEvent = {
3933
+ type: "WARNING",
3934
+ timestamp: getTimestamp(),
3935
+ target: {
3936
+ role: "generic",
3937
+ accessibleName: "",
3938
+ selector
3939
+ },
3940
+ payload: {
3941
+ kind: "warning",
3942
+ message: `Element not found: ${selector}`
3943
+ }
3944
+ };
3945
+ onEvent(warningEvent);
3946
+ return;
3947
+ }
3948
+ const eventProps = { bubbles: true, cancelable: true };
3949
+ element.dispatchEvent(new MouseEvent("mousedown", eventProps));
3950
+ element.dispatchEvent(new MouseEvent("mouseup", eventProps));
3951
+ element.dispatchEvent(new MouseEvent("click", eventProps));
3952
+ if ("focus" in element && typeof element.focus === "function") {
3953
+ element.focus();
3954
+ }
3955
+ }
3956
+ function executeTab(document, onEvent, getTimestamp) {
3957
+ const focusableElements = getFocusableElements(document);
3958
+ if (focusableElements.length === 0) return;
3959
+ const activeElement = document.activeElement;
3960
+ let currentIndex = -1;
3961
+ if (activeElement) {
3962
+ currentIndex = focusableElements.indexOf(activeElement);
3963
+ }
3964
+ const nextIndex = (currentIndex + 1) % focusableElements.length;
3965
+ const nextElement = focusableElements[nextIndex];
3966
+ dispatchKeyboardEvent(document, {
3967
+ ...KEY_MAP["Tab"],
3968
+ shiftKey: false
3969
+ });
3970
+ if (nextElement && typeof nextElement.focus === "function") {
3971
+ nextElement.focus();
3972
+ }
3973
+ const target = document.activeElement || document.body;
3974
+ const keyboardEvent = {
3975
+ type: "KEYBOARD_ACTION",
3976
+ timestamp: getTimestamp(),
3977
+ target: buildEventTarget(target, document),
3978
+ payload: {
3979
+ kind: "keyboard_action",
3980
+ key: "Tab",
3981
+ modifiers: []
3982
+ }
3983
+ };
3984
+ onEvent(keyboardEvent);
3985
+ }
3986
+ function executeShiftTab(document, onEvent, getTimestamp) {
3987
+ const focusableElements = getFocusableElements(document);
3988
+ if (focusableElements.length === 0) return;
3989
+ const activeElement = document.activeElement;
3990
+ let currentIndex = -1;
3991
+ if (activeElement) {
3992
+ currentIndex = focusableElements.indexOf(activeElement);
3993
+ }
3994
+ const prevIndex = currentIndex <= 0 ? focusableElements.length - 1 : currentIndex - 1;
3995
+ const prevElement = focusableElements[prevIndex];
3996
+ dispatchKeyboardEvent(document, {
3997
+ ...KEY_MAP["Tab"],
3998
+ shiftKey: true
3999
+ });
4000
+ if (prevElement && typeof prevElement.focus === "function") {
4001
+ prevElement.focus();
4002
+ }
4003
+ const target = document.activeElement || document.body;
4004
+ const keyboardEvent = {
4005
+ type: "KEYBOARD_ACTION",
4006
+ timestamp: getTimestamp(),
4007
+ target: buildEventTarget(target, document),
4008
+ payload: {
4009
+ kind: "keyboard_action",
4010
+ key: "Tab",
4011
+ modifiers: ["Shift"]
4012
+ }
4013
+ };
4014
+ onEvent(keyboardEvent);
4015
+ }
4016
+ function executeKeyAction(keyName, document, onEvent, getTimestamp) {
4017
+ const keyInfo = KEY_MAP[keyName];
4018
+ if (!keyInfo) return;
4019
+ dispatchKeyboardEvent(document, {
4020
+ ...keyInfo
4021
+ });
4022
+ const target = document.activeElement || document.body;
4023
+ const keyboardEvent = {
4024
+ type: "KEYBOARD_ACTION",
4025
+ timestamp: getTimestamp(),
4026
+ target: buildEventTarget(target, document),
4027
+ payload: {
4028
+ kind: "keyboard_action",
4029
+ key: keyName,
4030
+ modifiers: []
4031
+ }
4032
+ };
4033
+ onEvent(keyboardEvent);
4034
+ }
4035
+ function executeKeyCombo(combo, document, onEvent, getTimestamp) {
4036
+ const parsed = parseKeyCombo(combo);
4037
+ const keyInfo = getKeyInfo(parsed.key);
4038
+ dispatchKeyboardEvent(document, {
4039
+ ...keyInfo,
4040
+ shiftKey: parsed.shiftKey,
4041
+ ctrlKey: parsed.ctrlKey,
4042
+ altKey: parsed.altKey,
4043
+ metaKey: parsed.metaKey
4044
+ });
4045
+ const target = document.activeElement || document.body;
4046
+ const keyboardEvent = {
4047
+ type: "KEYBOARD_ACTION",
4048
+ timestamp: getTimestamp(),
4049
+ target: buildEventTarget(target, document),
4050
+ payload: {
4051
+ kind: "keyboard_action",
4052
+ key: parsed.key,
4053
+ modifiers: parsed.modifiers
4054
+ }
4055
+ };
4056
+ onEvent(keyboardEvent);
4057
+ }
4058
+ async function executeAction(action, document, onEvent, getTimestamp) {
4059
+ switch (action.type) {
4060
+ case "click":
4061
+ executeClick(action.selector, document, onEvent, getTimestamp);
4062
+ break;
4063
+ case "tab":
4064
+ executeTab(document, onEvent, getTimestamp);
4065
+ break;
4066
+ case "shiftTab":
4067
+ executeShiftTab(document, onEvent, getTimestamp);
4068
+ break;
4069
+ case "escape":
4070
+ executeKeyAction("Escape", document, onEvent, getTimestamp);
4071
+ break;
4072
+ case "enter":
4073
+ executeKeyAction("Enter", document, onEvent, getTimestamp);
4074
+ break;
4075
+ case "space":
4076
+ executeKeyAction(" ", document, onEvent, getTimestamp);
4077
+ break;
4078
+ case "arrowUp":
4079
+ executeKeyAction("ArrowUp", document, onEvent, getTimestamp);
4080
+ break;
4081
+ case "arrowDown":
4082
+ executeKeyAction("ArrowDown", document, onEvent, getTimestamp);
4083
+ break;
4084
+ case "arrowLeft":
4085
+ executeKeyAction("ArrowLeft", document, onEvent, getTimestamp);
4086
+ break;
4087
+ case "arrowRight":
4088
+ executeKeyAction("ArrowRight", document, onEvent, getTimestamp);
4089
+ break;
4090
+ case "key":
4091
+ executeKeyCombo(action.combo, document, onEvent, getTimestamp);
4092
+ break;
4093
+ case "wait":
4094
+ await new Promise((resolve) => setTimeout(resolve, action.ms));
4095
+ break;
4096
+ }
4097
+ }
4098
+ async function executeSequence(sequence, document, onEvent, getTimestamp, settleTime = 100) {
4099
+ for (let i = 0; i < sequence.actions.length; i++) {
4100
+ const action = sequence.actions[i];
4101
+ await executeAction(action, document, onEvent, getTimestamp);
4102
+ if (i < sequence.actions.length - 1) {
4103
+ await new Promise((resolve) => setTimeout(resolve, settleTime));
4104
+ }
4105
+ }
4106
+ }
4107
+
4108
+ // src/runtime/heuristics.ts
4109
+ var DEFAULT_CONFIG = {
4110
+ dialogFocusTimeout: 100,
4111
+ rapidAnnouncementWindow: 500,
4112
+ rapidAnnouncementThreshold: 3,
4113
+ keyboardResponseTimeout: 200
4114
+ };
4115
+ function createHeuristicAnalyzer(config) {
4116
+ const cfg = { ...DEFAULT_CONFIG, ...config };
4117
+ const trackedDialogs = [];
4118
+ const pendingDialogFocusChecks = [];
4119
+ const pendingKeyboardResponses = [];
4120
+ const announcementTimestamps = [];
4121
+ let lastFocusedSelector = null;
4122
+ function createWarning(timestamp, message, target, relatedEvent) {
4123
+ const payload = {
4124
+ kind: "warning",
4125
+ message,
4126
+ relatedEvent
4127
+ };
4128
+ return {
4129
+ type: "WARNING",
4130
+ timestamp,
4131
+ target,
4132
+ payload
4133
+ };
4134
+ }
4135
+ function checkExpiredDialogFocusTimeouts(currentTimestamp) {
4136
+ const warnings = [];
4137
+ for (let i = pendingDialogFocusChecks.length - 1; i >= 0; i--) {
4138
+ const pending = pendingDialogFocusChecks[i];
4139
+ if (pending.resolved) continue;
4140
+ const elapsed = currentTimestamp - pending.openedAt;
4141
+ if (elapsed > cfg.dialogFocusTimeout) {
4142
+ if (pending.isModal) {
4143
+ warnings.push(
4144
+ createWarning(
4145
+ currentTimestamp,
4146
+ "Focus was not moved into modal dialog",
4147
+ {
4148
+ role: "dialog",
4149
+ accessibleName: pending.dialogName,
4150
+ selector: pending.dialogSelector
4151
+ }
4152
+ )
4153
+ );
4154
+ }
4155
+ pending.resolved = true;
4156
+ }
4157
+ }
4158
+ return warnings;
4159
+ }
4160
+ function checkExpiredKeyboardResponses(currentTimestamp) {
4161
+ const warnings = [];
4162
+ for (let i = pendingKeyboardResponses.length - 1; i >= 0; i--) {
4163
+ const pending = pendingKeyboardResponses[i];
4164
+ if (pending.resolved) continue;
4165
+ const elapsed = currentTimestamp - pending.timestamp;
4166
+ if (elapsed > cfg.keyboardResponseTimeout) {
4167
+ warnings.push(
4168
+ createWarning(
4169
+ currentTimestamp,
4170
+ "Keyboard action produced no accessibility response",
4171
+ pending.event.target,
4172
+ pending.event
4173
+ )
4174
+ );
4175
+ pending.resolved = true;
4176
+ }
4177
+ }
4178
+ return warnings;
4179
+ }
4180
+ function checkRapidAnnouncements(currentTimestamp) {
4181
+ const warnings = [];
4182
+ const windowStart = currentTimestamp - cfg.rapidAnnouncementWindow;
4183
+ while (announcementTimestamps.length > 0 && announcementTimestamps[0] < windowStart) {
4184
+ announcementTimestamps.shift();
4185
+ }
4186
+ if (announcementTimestamps.length > cfg.rapidAnnouncementThreshold) {
4187
+ warnings.push(
4188
+ createWarning(
4189
+ currentTimestamp,
4190
+ "Rapid announcements detected: assistive technology users may miss content",
4191
+ {
4192
+ role: "region",
4193
+ accessibleName: "",
4194
+ selector: "body"
4195
+ }
4196
+ )
4197
+ );
4198
+ announcementTimestamps.length = 0;
4199
+ }
4200
+ return warnings;
4201
+ }
4202
+ function checkFocusEscape(event) {
4203
+ const warnings = [];
4204
+ if (event.type !== "FOCUS_CHANGED") return warnings;
4205
+ const modalDialogs = trackedDialogs.filter((d) => d.isModal);
4206
+ if (modalDialogs.length === 0) return warnings;
4207
+ const focusedSelector = event.target.selector;
4208
+ for (const dialog of modalDialogs) {
4209
+ if (!isSelectorInside(focusedSelector, dialog.selector)) {
4210
+ warnings.push(
4211
+ createWarning(
4212
+ event.timestamp,
4213
+ "Focus escaped modal dialog",
4214
+ event.target,
4215
+ event
4216
+ )
4217
+ );
4218
+ break;
4219
+ }
4220
+ }
4221
+ return warnings;
4222
+ }
4223
+ function checkFocusedElementRemoved(event) {
4224
+ const warnings = [];
4225
+ if (event.type === "DOM_MUTATION" && lastFocusedSelector !== null) {
4226
+ if (event.target.selector === lastFocusedSelector) {
4227
+ warnings.push(
4228
+ createWarning(
4229
+ event.timestamp,
4230
+ "Focused element removed without focus management",
4231
+ event.target,
4232
+ event
4233
+ )
4234
+ );
4235
+ }
4236
+ }
4237
+ return warnings;
4238
+ }
4239
+ function isSelectorInside(childSelector, containerSelector) {
4240
+ if (childSelector === containerSelector) return true;
4241
+ if (childSelector.startsWith(containerSelector + " ")) return true;
4242
+ if (childSelector.startsWith(containerSelector + " > ")) return true;
4243
+ if (childSelector.startsWith(containerSelector + ">")) return true;
4244
+ return false;
4245
+ }
4246
+ function processEvent(event) {
4247
+ const warnings = [];
4248
+ warnings.push(...checkExpiredDialogFocusTimeouts(event.timestamp));
4249
+ warnings.push(...checkExpiredKeyboardResponses(event.timestamp));
4250
+ switch (event.type) {
4251
+ case "DIALOG_OPENED": {
4252
+ const payload = event.payload;
4253
+ const dialog = {
4254
+ selector: event.target.selector,
4255
+ name: payload.dialogName,
4256
+ isModal: payload.isModal
4257
+ };
4258
+ trackedDialogs.push(dialog);
4259
+ if (payload.isModal) {
4260
+ pendingDialogFocusChecks.push({
4261
+ dialogSelector: event.target.selector,
4262
+ dialogName: payload.dialogName,
4263
+ openedAt: event.timestamp,
4264
+ isModal: true,
4265
+ resolved: false
4266
+ });
4267
+ }
4268
+ break;
4269
+ }
4270
+ case "DIALOG_CLOSED": {
4271
+ const closedSelector = event.target.selector;
4272
+ const idx = trackedDialogs.findIndex(
4273
+ (d) => d.selector === closedSelector
4274
+ );
4275
+ if (idx !== -1) {
4276
+ trackedDialogs.splice(idx, 1);
4277
+ }
4278
+ for (const pending of pendingDialogFocusChecks) {
4279
+ if (pending.dialogSelector === closedSelector && !pending.resolved) {
4280
+ pending.resolved = true;
4281
+ }
4282
+ }
4283
+ break;
4284
+ }
4285
+ case "FOCUS_CHANGED": {
4286
+ for (const pending of pendingDialogFocusChecks) {
4287
+ if (pending.resolved) continue;
4288
+ if (isSelectorInside(event.target.selector, pending.dialogSelector)) {
4289
+ pending.resolved = true;
4290
+ }
4291
+ }
4292
+ for (const pending of pendingKeyboardResponses) {
4293
+ if (!pending.resolved) {
4294
+ pending.resolved = true;
4295
+ }
4296
+ }
4297
+ warnings.push(...checkFocusEscape(event));
4298
+ lastFocusedSelector = event.target.selector;
4299
+ break;
4300
+ }
4301
+ case "ANNOUNCEMENT": {
4302
+ announcementTimestamps.push(event.timestamp);
4303
+ for (const pending of pendingKeyboardResponses) {
4304
+ if (!pending.resolved) {
4305
+ pending.resolved = true;
4306
+ }
4307
+ }
4308
+ warnings.push(...checkRapidAnnouncements(event.timestamp));
4309
+ break;
4310
+ }
4311
+ case "KEYBOARD_ACTION": {
4312
+ pendingKeyboardResponses.push({
4313
+ event,
4314
+ timestamp: event.timestamp,
4315
+ resolved: false
4316
+ });
4317
+ break;
4318
+ }
4319
+ case "DOM_MUTATION": {
4320
+ warnings.push(...checkFocusedElementRemoved(event));
4321
+ for (const pending of pendingKeyboardResponses) {
4322
+ if (!pending.resolved) {
4323
+ pending.resolved = true;
4324
+ }
4325
+ }
4326
+ break;
4327
+ }
4328
+ case "STATE_CHANGED":
4329
+ case "ROLE_CHANGED":
4330
+ case "ACCESSIBLE_NAME_CHANGED": {
4331
+ for (const pending of pendingKeyboardResponses) {
4332
+ if (!pending.resolved) {
4333
+ pending.resolved = true;
4334
+ }
4335
+ }
4336
+ break;
4337
+ }
4338
+ default:
4339
+ break;
4340
+ }
4341
+ cleanupResolvedChecks();
4342
+ return warnings;
4343
+ }
4344
+ function cleanupResolvedChecks() {
4345
+ for (let i = pendingDialogFocusChecks.length - 1; i >= 0; i--) {
4346
+ if (pendingDialogFocusChecks[i].resolved) {
4347
+ pendingDialogFocusChecks.splice(i, 1);
4348
+ }
4349
+ }
4350
+ for (let i = pendingKeyboardResponses.length - 1; i >= 0; i--) {
4351
+ if (pendingKeyboardResponses[i].resolved) {
4352
+ pendingKeyboardResponses.splice(i, 1);
4353
+ }
4354
+ }
4355
+ }
4356
+ return {
4357
+ process(event) {
4358
+ return processEvent(event);
4359
+ },
4360
+ get openDialogs() {
4361
+ return trackedDialogs.map((d) => d.selector);
4362
+ }
4363
+ };
4364
+ }
4365
+
4366
+ // src/runtime/timeline-generator.ts
4367
+ var SPEAKABLE_VERSION = "1.3.0";
4368
+ var TIMELINE_FORMAT_VERSION = "1.0";
4369
+ var DEFAULT_SETTLE_PERIOD = 500;
4370
+ var DEFAULT_LOAD_TIMEOUT = 1e4;
4371
+ var DOM_STABILITY_WAIT = 100;
4372
+ function createTimelineGenerator(options) {
4373
+ const {
4374
+ document: doc,
4375
+ componentName,
4376
+ storyName,
4377
+ settlePeriod = DEFAULT_SETTLE_PERIOD,
4378
+ loadTimeout = DEFAULT_LOAD_TIMEOUT,
4379
+ heuristics: enableHeuristics = true
4380
+ } = options;
4381
+ let aborted = false;
4382
+ let currentEngine = null;
4383
+ return {
4384
+ async capture(sequence) {
4385
+ aborted = false;
4386
+ await waitForDocumentReady(doc, loadTimeout);
4387
+ if (aborted) {
4388
+ return buildAbortedTimeline(componentName, storyName, sequence);
4389
+ }
4390
+ const engine = createEngine({ document: doc });
4391
+ currentEngine = engine;
4392
+ const heuristicAnalyzer = enableHeuristics ? createHeuristicAnalyzer() : null;
4393
+ const interactionEvents = [];
4394
+ const sessionStart = Date.now();
4395
+ engine.attach();
4396
+ if (aborted) {
4397
+ engine.detach();
4398
+ currentEngine = null;
4399
+ return buildAbortedTimeline(componentName, storyName, sequence);
4400
+ }
4401
+ function getTimestamp() {
4402
+ return Date.now() - sessionStart;
4403
+ }
4404
+ await executeSequence(
4405
+ sequence,
4406
+ doc,
4407
+ (event) => {
4408
+ interactionEvents.push(event);
4409
+ },
4410
+ getTimestamp,
4411
+ DOM_STABILITY_WAIT
4412
+ );
4413
+ if (aborted) {
4414
+ engine.detach();
4415
+ currentEngine = null;
4416
+ return buildAbortedTimeline(componentName, storyName, sequence);
4417
+ }
4418
+ await delay(settlePeriod);
4419
+ engine.detach();
4420
+ currentEngine = null;
4421
+ const duration = Date.now() - sessionStart;
4422
+ const engineEvents = engine.getEvents();
4423
+ const allEvents = mergeEvents(engineEvents, interactionEvents);
4424
+ if (heuristicAnalyzer) {
4425
+ const heuristicWarnings = [];
4426
+ for (const event of allEvents) {
4427
+ const warnings = heuristicAnalyzer.process(event);
4428
+ heuristicWarnings.push(...warnings);
4429
+ }
4430
+ for (const warning of heuristicWarnings) {
4431
+ allEvents.push(warning);
4432
+ }
4433
+ allEvents.sort((a, b) => a.timestamp - b.timestamp);
4434
+ }
4435
+ const allWarnings = allEvents.filter((e) => e.type === "WARNING");
4436
+ const metadata = {
4437
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
4438
+ speakableVersion: SPEAKABLE_VERSION,
4439
+ sourceUrl: getSourceUrl(doc),
4440
+ userAgent: getUserAgent()
4441
+ };
4442
+ const timeline = {
4443
+ version: TIMELINE_FORMAT_VERSION,
4444
+ component: componentName,
4445
+ story: storyName || null,
4446
+ interactionSequence: sequence.description,
4447
+ duration,
4448
+ events: allEvents,
4449
+ warnings: allWarnings,
4450
+ metadata
4451
+ };
4452
+ return timeline;
4453
+ },
4454
+ abort() {
4455
+ aborted = true;
4456
+ if (currentEngine && currentEngine.isAttached) {
4457
+ currentEngine.detach();
4458
+ currentEngine = null;
4459
+ }
4460
+ }
4461
+ };
4462
+ }
4463
+ async function waitForDocumentReady(doc, timeout) {
4464
+ if (doc.body) return;
4465
+ return new Promise((resolve, reject) => {
4466
+ const timeoutId = setTimeout(() => {
4467
+ reject(
4468
+ new Error(
4469
+ `Document load timeout (${timeout}ms): ${getSourceUrl(doc)}`
4470
+ )
4471
+ );
4472
+ }, timeout);
4473
+ const interval = setInterval(() => {
4474
+ if (doc.body) {
4475
+ clearTimeout(timeoutId);
4476
+ clearInterval(interval);
4477
+ resolve();
4478
+ }
4479
+ }, 50);
4480
+ });
4481
+ }
4482
+ function mergeEvents(engineEvents, interactionEvents) {
4483
+ const all = [...engineEvents, ...interactionEvents];
4484
+ all.sort((a, b) => a.timestamp - b.timestamp);
4485
+ return all;
4486
+ }
4487
+ function getSourceUrl(doc) {
4488
+ try {
4489
+ const url = doc.URL;
4490
+ if (url && url !== "about:blank" && url !== "") {
4491
+ return url;
4492
+ }
4493
+ } catch {
4494
+ }
4495
+ return "local";
4496
+ }
4497
+ function getUserAgent() {
4498
+ try {
4499
+ if (typeof navigator !== "undefined" && navigator.userAgent) {
4500
+ return navigator.userAgent;
4501
+ }
4502
+ } catch {
4503
+ }
4504
+ return "jsdom";
4505
+ }
4506
+ function delay(ms) {
4507
+ return new Promise((resolve) => setTimeout(resolve, ms));
4508
+ }
4509
+ function buildAbortedTimeline(componentName, storyName, sequence) {
4510
+ return {
4511
+ version: TIMELINE_FORMAT_VERSION,
4512
+ component: componentName,
4513
+ story: storyName || null,
4514
+ interactionSequence: sequence.description,
4515
+ duration: 0,
4516
+ events: [],
4517
+ warnings: [],
4518
+ metadata: {
4519
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
4520
+ speakableVersion: SPEAKABLE_VERSION,
4521
+ sourceUrl: "local",
4522
+ userAgent: getUserAgent()
4523
+ }
4524
+ };
4525
+ }
4526
+
4527
+ // src/runtime/patterns.ts
4528
+ var MODAL_DIALOG_DEFAULTS = {
4529
+ trigger: "button",
4530
+ container: '[role="dialog"], dialog'
4531
+ };
4532
+ var COMBOBOX_DEFAULTS = {
4533
+ input: '[role="combobox"], input[type="text"]',
4534
+ items: '[role="option"]'
4535
+ };
4536
+ var TABS_DEFAULTS = {
4537
+ container: '[role="tablist"]',
4538
+ items: '[role="tab"]'
4539
+ };
4540
+ var ACCORDION_DEFAULTS = {
4541
+ trigger: "button[aria-expanded]"
4542
+ };
4543
+ function buildModalDialogPattern(selectors) {
4544
+ const trigger = selectors?.trigger ?? MODAL_DIALOG_DEFAULTS.trigger;
4545
+ const actions = [
4546
+ { type: "click", selector: trigger },
4547
+ { type: "tab" },
4548
+ { type: "tab" },
4549
+ { type: "tab" },
4550
+ { type: "escape" }
4551
+ ];
4552
+ return {
4553
+ description: "Modal dialog: click trigger to open, tab through dialog content, press Escape to close, verify focus returns to trigger",
4554
+ actions
4555
+ };
4556
+ }
4557
+ function buildComboboxPattern(selectors) {
4558
+ const input = selectors?.input ?? COMBOBOX_DEFAULTS.input;
4559
+ const actions = [
4560
+ { type: "click", selector: input },
4561
+ { type: "key", combo: "a" },
4562
+ { type: "arrowDown" },
4563
+ { type: "arrowDown" },
4564
+ { type: "enter" }
4565
+ ];
4566
+ return {
4567
+ description: "Combobox: focus input, type to filter, navigate options with arrow keys, select with Enter",
4568
+ actions
4569
+ };
4570
+ }
4571
+ function buildTabsPattern(selectors) {
4572
+ const container = selectors?.container ?? TABS_DEFAULTS.container;
4573
+ const actions = [
4574
+ { type: "click", selector: container },
4575
+ { type: "arrowRight" },
4576
+ { type: "arrowRight" },
4577
+ { type: "enter" },
4578
+ { type: "arrowLeft" },
4579
+ { type: "space" }
4580
+ ];
4581
+ return {
4582
+ description: "Tabs: focus tablist, navigate between tabs with arrow keys, activate with Enter/Space",
4583
+ actions
4584
+ };
4585
+ }
4586
+ function buildAccordionPattern(selectors) {
4587
+ const trigger = selectors?.trigger ?? ACCORDION_DEFAULTS.trigger;
4588
+ const actions = [
4589
+ { type: "click", selector: trigger },
4590
+ { type: "enter" },
4591
+ { type: "arrowDown" },
4592
+ { type: "space" },
4593
+ { type: "arrowDown" },
4594
+ { type: "enter" }
4595
+ ];
4596
+ return {
4597
+ description: "Accordion: focus header, toggle with Enter/Space, navigate between headers with arrow keys",
4598
+ actions
4599
+ };
4600
+ }
4601
+ function getBuiltinPattern(name, selectors) {
4602
+ switch (name) {
4603
+ case "modal-dialog":
4604
+ return buildModalDialogPattern(selectors);
4605
+ case "combobox":
4606
+ return buildComboboxPattern(selectors);
4607
+ case "tabs":
4608
+ return buildTabsPattern(selectors);
4609
+ case "accordion":
4610
+ return buildAccordionPattern(selectors);
4611
+ }
4612
+ }
4613
+
4614
+ // src/runtime/serialization.ts
4615
+ var VALID_EVENT_TYPES = /* @__PURE__ */ new Set([
4616
+ "FOCUS_CHANGED",
4617
+ "ANNOUNCEMENT",
4618
+ "DOM_MUTATION",
4619
+ "ROLE_CHANGED",
4620
+ "ACCESSIBLE_NAME_CHANGED",
4621
+ "STATE_CHANGED",
4622
+ "KEYBOARD_ACTION",
4623
+ "DIALOG_OPENED",
4624
+ "DIALOG_CLOSED",
4625
+ "WARNING",
4626
+ "REGRESSION"
4627
+ ]);
4628
+ var VALID_PAYLOAD_KINDS = /* @__PURE__ */ new Set([
4629
+ "focus_changed",
4630
+ "announcement",
4631
+ "role_changed",
4632
+ "accessible_name_changed",
4633
+ "state_changed",
4634
+ "dialog_opened",
4635
+ "dialog_closed",
4636
+ "keyboard_action",
4637
+ "warning"
4638
+ ]);
4639
+ var VALID_ACTION_TYPES = /* @__PURE__ */ new Set([
4640
+ "click",
4641
+ "tab",
4642
+ "shiftTab",
4643
+ "escape",
4644
+ "enter",
4645
+ "space",
4646
+ "arrowUp",
4647
+ "arrowDown",
4648
+ "arrowLeft",
4649
+ "arrowRight",
4650
+ "key",
4651
+ "wait"
4652
+ ]);
4653
+ function sortKeysDeep(value) {
4654
+ if (value === null || value === void 0) {
4655
+ return value;
4656
+ }
4657
+ if (Array.isArray(value)) {
4658
+ return value.map(sortKeysDeep);
4659
+ }
4660
+ if (typeof value === "object") {
4661
+ const sorted = {};
4662
+ const keys = Object.keys(value).sort();
4663
+ for (const key of keys) {
4664
+ sorted[key] = sortKeysDeep(value[key]);
4665
+ }
4666
+ return sorted;
4667
+ }
4668
+ return value;
4669
+ }
4670
+ function serializeEvent(event) {
4671
+ const sorted = sortKeysDeep(event);
4672
+ return JSON.stringify(sorted, null, 2);
4673
+ }
4674
+ function deserializeEvent(json) {
4675
+ const parsed = JSON.parse(json);
4676
+ validateEvent(parsed);
4677
+ return parsed;
4678
+ }
4679
+ function serializeTimeline(timeline) {
4680
+ const sorted = sortKeysDeep(timeline);
4681
+ return JSON.stringify(sorted, null, 2);
4682
+ }
4683
+ function deserializeTimeline(json) {
4684
+ const parsed = JSON.parse(json);
4685
+ validateTimeline(parsed);
4686
+ return parsed;
4687
+ }
4688
+ function serializeInteractionSequence(seq) {
4689
+ const sorted = sortKeysDeep(seq);
4690
+ return JSON.stringify(sorted, null, 2);
4691
+ }
4692
+ function deserializeInteractionSequence(json) {
4693
+ const parsed = JSON.parse(json);
4694
+ validateInteractionSequence(parsed);
4695
+ return parsed;
4696
+ }
4697
+ function timelinesEqual(a, b) {
4698
+ return serializeTimeline(a) === serializeTimeline(b);
4699
+ }
4700
+ function validateEvent(obj) {
4701
+ if (obj === null || typeof obj !== "object") {
4702
+ throw new Error("Event must be a non-null object");
4703
+ }
4704
+ const event = obj;
4705
+ if (typeof event.type !== "string" || !VALID_EVENT_TYPES.has(event.type)) {
4706
+ throw new Error(
4707
+ `Event "type" must be one of: ${[...VALID_EVENT_TYPES].join(", ")}. Got: ${String(event.type)}`
4708
+ );
4709
+ }
4710
+ if (typeof event.timestamp !== "number" || !Number.isFinite(event.timestamp)) {
4711
+ throw new Error('Event "timestamp" must be a finite number');
4712
+ }
4713
+ validateEventTarget(event.target, 'Event "target"');
4714
+ validatePayload(event.payload);
4715
+ }
4716
+ function validateEventTarget(obj, label) {
4717
+ if (obj === null || typeof obj !== "object") {
4718
+ throw new Error(`${label} must be a non-null object`);
4719
+ }
4720
+ const target = obj;
4721
+ if (typeof target.role !== "string") {
4722
+ throw new Error(`${label}.role must be a string`);
4723
+ }
4724
+ if (typeof target.accessibleName !== "string") {
4725
+ throw new Error(`${label}.accessibleName must be a string`);
4726
+ }
4727
+ if (typeof target.selector !== "string") {
4728
+ throw new Error(`${label}.selector must be a string`);
4729
+ }
4730
+ }
4731
+ function validatePayload(obj) {
4732
+ if (obj === null || typeof obj !== "object") {
4733
+ throw new Error('Event "payload" must be a non-null object');
4734
+ }
4735
+ const payload = obj;
4736
+ if (typeof payload.kind !== "string" || !VALID_PAYLOAD_KINDS.has(payload.kind)) {
4737
+ throw new Error(
4738
+ `Payload "kind" must be one of: ${[...VALID_PAYLOAD_KINDS].join(", ")}. Got: ${String(payload.kind)}`
4739
+ );
4740
+ }
4741
+ switch (payload.kind) {
4742
+ case "focus_changed":
4743
+ if (payload.previousTarget !== null) {
4744
+ validateEventTarget(payload.previousTarget, "FocusChangedPayload.previousTarget");
4745
+ }
4746
+ break;
4747
+ case "announcement":
4748
+ if (payload.politeness !== "polite" && payload.politeness !== "assertive") {
4749
+ throw new Error('AnnouncementPayload.politeness must be "polite" or "assertive"');
4750
+ }
4751
+ if (typeof payload.text !== "string") {
4752
+ throw new Error("AnnouncementPayload.text must be a string");
4753
+ }
4754
+ break;
4755
+ case "role_changed":
4756
+ if (typeof payload.previousRole !== "string") {
4757
+ throw new Error("RoleChangedPayload.previousRole must be a string");
4758
+ }
4759
+ if (typeof payload.newRole !== "string") {
4760
+ throw new Error("RoleChangedPayload.newRole must be a string");
4761
+ }
4762
+ break;
4763
+ case "accessible_name_changed":
4764
+ if (typeof payload.previousName !== "string") {
4765
+ throw new Error("AccessibleNameChangedPayload.previousName must be a string");
4766
+ }
4767
+ if (typeof payload.newName !== "string") {
4768
+ throw new Error("AccessibleNameChangedPayload.newName must be a string");
4769
+ }
4770
+ break;
4771
+ case "state_changed":
4772
+ if (typeof payload.attribute !== "string") {
4773
+ throw new Error("StateChangedPayload.attribute must be a string");
4774
+ }
4775
+ validateStateValue(payload.previousValue, "StateChangedPayload.previousValue");
4776
+ validateStateValue(payload.newValue, "StateChangedPayload.newValue");
4777
+ break;
4778
+ case "dialog_opened":
4779
+ if (typeof payload.dialogName !== "string") {
4780
+ throw new Error("DialogOpenedPayload.dialogName must be a string");
4781
+ }
4782
+ if (typeof payload.isModal !== "boolean") {
4783
+ throw new Error("DialogOpenedPayload.isModal must be a boolean");
4784
+ }
4785
+ break;
4786
+ case "dialog_closed":
4787
+ if (typeof payload.dialogName !== "string") {
4788
+ throw new Error("DialogClosedPayload.dialogName must be a string");
4789
+ }
4790
+ break;
4791
+ case "keyboard_action":
4792
+ if (typeof payload.key !== "string") {
4793
+ throw new Error("KeyboardActionPayload.key must be a string");
4794
+ }
4795
+ if (!Array.isArray(payload.modifiers)) {
4796
+ throw new Error("KeyboardActionPayload.modifiers must be an array");
4797
+ }
4798
+ for (const mod of payload.modifiers) {
4799
+ if (typeof mod !== "string") {
4800
+ throw new Error("KeyboardActionPayload.modifiers must contain only strings");
4801
+ }
4802
+ }
4803
+ break;
4804
+ case "warning":
4805
+ if (typeof payload.message !== "string") {
4806
+ throw new Error("WarningPayload.message must be a string");
4807
+ }
4808
+ if (payload.relatedEvent !== void 0 && payload.relatedEvent !== null) {
4809
+ validateEvent(payload.relatedEvent);
4810
+ }
4811
+ break;
4812
+ }
4813
+ }
4814
+ function validateStateValue(value, label) {
4815
+ if (value !== null && typeof value !== "string" && typeof value !== "boolean") {
4816
+ throw new Error(`${label} must be a string, boolean, or null`);
4817
+ }
4818
+ }
4819
+ function validateTimeline(obj) {
4820
+ if (obj === null || typeof obj !== "object") {
4821
+ throw new Error("Timeline must be a non-null object");
4822
+ }
4823
+ const timeline = obj;
4824
+ if (typeof timeline.version !== "string") {
4825
+ throw new Error('Timeline "version" must be a string');
4826
+ }
4827
+ if (typeof timeline.component !== "string") {
4828
+ throw new Error('Timeline "component" must be a string');
4829
+ }
4830
+ if (timeline.story !== null && typeof timeline.story !== "string") {
4831
+ throw new Error('Timeline "story" must be a string or null');
4832
+ }
4833
+ if (typeof timeline.interactionSequence !== "string") {
4834
+ throw new Error('Timeline "interactionSequence" must be a string');
4835
+ }
4836
+ if (typeof timeline.duration !== "number" || !Number.isFinite(timeline.duration)) {
4837
+ throw new Error('Timeline "duration" must be a finite number');
4838
+ }
4839
+ if (!Array.isArray(timeline.events)) {
4840
+ throw new Error('Timeline "events" must be an array');
4841
+ }
4842
+ for (let i = 0; i < timeline.events.length; i++) {
4843
+ try {
4844
+ validateEvent(timeline.events[i]);
4845
+ } catch (err) {
4846
+ throw new Error(
4847
+ `Timeline events[${i}]: ${err instanceof Error ? err.message : String(err)}`
4848
+ );
4849
+ }
4850
+ }
4851
+ if (!Array.isArray(timeline.warnings)) {
4852
+ throw new Error('Timeline "warnings" must be an array');
4853
+ }
4854
+ for (let i = 0; i < timeline.warnings.length; i++) {
4855
+ try {
4856
+ validateEvent(timeline.warnings[i]);
4857
+ } catch (err) {
4858
+ throw new Error(
4859
+ `Timeline warnings[${i}]: ${err instanceof Error ? err.message : String(err)}`
4860
+ );
4861
+ }
4862
+ }
4863
+ validateTimelineMetadata(timeline.metadata);
4864
+ }
4865
+ function validateTimelineMetadata(obj) {
4866
+ if (obj === null || typeof obj !== "object") {
4867
+ throw new Error('Timeline "metadata" must be a non-null object');
4868
+ }
4869
+ const meta = obj;
4870
+ if (typeof meta.capturedAt !== "string") {
4871
+ throw new Error("Timeline metadata.capturedAt must be a string");
4872
+ }
4873
+ if (typeof meta.speakableVersion !== "string") {
4874
+ throw new Error("Timeline metadata.speakableVersion must be a string");
4875
+ }
4876
+ if (typeof meta.sourceUrl !== "string") {
4877
+ throw new Error("Timeline metadata.sourceUrl must be a string");
4878
+ }
4879
+ if (typeof meta.userAgent !== "string") {
4880
+ throw new Error("Timeline metadata.userAgent must be a string");
4881
+ }
4882
+ }
4883
+ function validateInteractionSequence(obj) {
4884
+ if (obj === null || typeof obj !== "object") {
4885
+ throw new Error("InteractionSequence must be a non-null object");
4886
+ }
4887
+ const seq = obj;
4888
+ if (typeof seq.description !== "string") {
4889
+ throw new Error('InteractionSequence "description" must be a string');
4890
+ }
4891
+ if (!Array.isArray(seq.actions)) {
4892
+ throw new Error('InteractionSequence "actions" must be an array');
4893
+ }
4894
+ for (let i = 0; i < seq.actions.length; i++) {
4895
+ validateAction(seq.actions[i], i);
4896
+ }
4897
+ }
4898
+ function validateAction(obj, index) {
4899
+ if (obj === null || typeof obj !== "object") {
4900
+ throw new Error(`InteractionSequence actions[${index}] must be a non-null object`);
4901
+ }
4902
+ const action = obj;
4903
+ if (typeof action.type !== "string" || !VALID_ACTION_TYPES.has(action.type)) {
4904
+ throw new Error(
4905
+ `InteractionSequence actions[${index}].type must be one of: ${[...VALID_ACTION_TYPES].join(", ")}. Got: ${String(action.type)}`
4906
+ );
4907
+ }
4908
+ switch (action.type) {
4909
+ case "click":
4910
+ if (typeof action.selector !== "string") {
4911
+ throw new Error(
4912
+ `InteractionSequence actions[${index}].selector must be a string for click actions`
4913
+ );
4914
+ }
4915
+ break;
4916
+ case "key":
4917
+ if (typeof action.combo !== "string") {
4918
+ throw new Error(
4919
+ `InteractionSequence actions[${index}].combo must be a string for key actions`
4920
+ );
4921
+ }
4922
+ break;
4923
+ case "wait":
4924
+ if (typeof action.ms !== "number" || !Number.isFinite(action.ms)) {
4925
+ throw new Error(
4926
+ `InteractionSequence actions[${index}].ms must be a finite number for wait actions`
4927
+ );
4928
+ }
4929
+ break;
4930
+ }
4931
+ }
4932
+
4933
+ // src/runtime/diff-engine.ts
4934
+ function matchingKey(event) {
4935
+ return `${event.type}::${event.target.selector}`;
4936
+ }
4937
+ function payloadsEqual(a, b) {
4938
+ if (a.type !== b.type) return false;
4939
+ if (!targetsEqual(a.target, b.target)) return false;
4940
+ return deepEqual(a.payload, b.payload);
4941
+ }
4942
+ function targetsEqual(a, b) {
4943
+ return a.role === b.role && a.accessibleName === b.accessibleName && a.selector === b.selector;
4944
+ }
4945
+ function deepEqual(a, b) {
4946
+ if (a === b) return true;
4947
+ if (a === null || b === null) return a === b;
4948
+ if (typeof a !== typeof b) return false;
4949
+ if (typeof a !== "object") return a === b;
4950
+ const aObj = a;
4951
+ const bObj = b;
4952
+ const aKeys = Object.keys(aObj).sort();
4953
+ const bKeys = Object.keys(bObj).sort();
4954
+ if (aKeys.length !== bKeys.length) return false;
4955
+ for (let i = 0; i < aKeys.length; i++) {
4956
+ if (aKeys[i] !== bKeys[i]) return false;
4957
+ if (!deepEqual(aObj[aKeys[i]], bObj[bKeys[i]])) return false;
4958
+ }
4959
+ return true;
4960
+ }
4961
+ function buildModifiedMessage(baseline, current) {
4962
+ const type = current.type;
4963
+ const selector = current.target.selector;
4964
+ if (baseline.target.accessibleName !== current.target.accessibleName) {
4965
+ return `${type} on "${selector}": accessible name changed from "${baseline.target.accessibleName}" to "${current.target.accessibleName}"`;
4966
+ }
4967
+ if (baseline.target.role !== current.target.role) {
4968
+ return `${type} on "${selector}": role changed from "${baseline.target.role}" to "${current.target.role}"`;
4969
+ }
4970
+ return `${type} on "${selector}": payload values differ`;
4971
+ }
4972
+ function diffTimelines(baseline, current) {
4973
+ const added = [];
4974
+ const removed = [];
4975
+ const modified = [];
4976
+ const currentByKey = /* @__PURE__ */ new Map();
4977
+ for (const event of current.events) {
4978
+ const key = matchingKey(event);
4979
+ const existing = currentByKey.get(key);
4980
+ if (existing) {
4981
+ existing.push(event);
4982
+ } else {
4983
+ currentByKey.set(key, [event]);
4984
+ }
4985
+ }
4986
+ const matchedCurrentIndices = /* @__PURE__ */ new Set();
4987
+ for (const baselineEvent of baseline.events) {
4988
+ const key = matchingKey(baselineEvent);
4989
+ const candidates = currentByKey.get(key);
4990
+ if (!candidates || candidates.length === 0) {
4991
+ removed.push({
4992
+ event: baselineEvent,
4993
+ message: `${baselineEvent.type} on "${baselineEvent.target.selector}" was removed`
4994
+ });
4995
+ continue;
4996
+ }
4997
+ let matched = false;
4998
+ for (let i = 0; i < candidates.length; i++) {
4999
+ const candidateId = `${key}::${i}`;
5000
+ if (matchedCurrentIndices.has(candidateId)) continue;
5001
+ const currentEvent = candidates[i];
5002
+ matchedCurrentIndices.add(candidateId);
5003
+ if (!payloadsEqual(baselineEvent, currentEvent)) {
5004
+ modified.push({
5005
+ event: currentEvent,
5006
+ previousEvent: baselineEvent,
5007
+ message: buildModifiedMessage(baselineEvent, currentEvent)
5008
+ });
5009
+ }
5010
+ matched = true;
5011
+ break;
5012
+ }
5013
+ if (!matched) {
5014
+ removed.push({
5015
+ event: baselineEvent,
5016
+ message: `${baselineEvent.type} on "${baselineEvent.target.selector}" was removed`
5017
+ });
5018
+ }
5019
+ }
5020
+ for (const [key, candidates] of currentByKey.entries()) {
5021
+ for (let i = 0; i < candidates.length; i++) {
5022
+ const candidateId = `${key}::${i}`;
5023
+ if (!matchedCurrentIndices.has(candidateId)) {
5024
+ const event = candidates[i];
5025
+ added.push({
5026
+ event,
5027
+ message: `${event.type} on "${event.target.selector}" was added`
5028
+ });
5029
+ }
5030
+ }
5031
+ }
5032
+ return {
5033
+ baseline: { totalEvents: baseline.events.length },
5034
+ current: { totalEvents: current.events.length },
5035
+ added,
5036
+ removed,
5037
+ modified,
5038
+ summary: {
5039
+ totalBaseline: baseline.events.length,
5040
+ totalCurrent: current.events.length,
5041
+ added: added.length,
5042
+ removed: removed.length,
5043
+ modified: modified.length
5044
+ }
5045
+ };
5046
+ }
5047
+
5048
+ // src/runtime/severity.ts
5049
+ function classifyDiff(report) {
5050
+ const entries = [];
5051
+ for (const entry of report.removed) {
5052
+ const severity = classifyRemoved(entry);
5053
+ entries.push({ ...entry, severity });
5054
+ }
5055
+ for (const entry of report.added) {
5056
+ const severity = classifyAdded(entry);
5057
+ entries.push({ ...entry, severity });
5058
+ }
5059
+ for (const entry of report.modified) {
5060
+ const severity = classifyModified(entry);
5061
+ entries.push({ ...entry, severity });
5062
+ }
5063
+ const criticalCount = entries.filter((e) => e.severity === "critical").length;
5064
+ const highCount = entries.filter((e) => e.severity === "high").length;
5065
+ const mediumCount = entries.filter((e) => e.severity === "medium").length;
5066
+ const lowCount = entries.filter((e) => e.severity === "low").length;
5067
+ let highestSeverity = null;
5068
+ if (criticalCount > 0) highestSeverity = "critical";
5069
+ else if (highCount > 0) highestSeverity = "high";
5070
+ else if (mediumCount > 0) highestSeverity = "medium";
5071
+ else if (lowCount > 0) highestSeverity = "low";
5072
+ return { entries, highestSeverity, criticalCount, highCount, mediumCount, lowCount };
5073
+ }
5074
+ function classifyRemoved(entry) {
5075
+ switch (entry.event.type) {
5076
+ case "FOCUS_CHANGED":
5077
+ return "critical";
5078
+ case "ANNOUNCEMENT":
5079
+ return "critical";
5080
+ case "DIALOG_OPENED":
5081
+ return "high";
5082
+ case "DIALOG_CLOSED":
5083
+ return "high";
5084
+ case "STATE_CHANGED":
5085
+ return "high";
5086
+ case "KEYBOARD_ACTION":
5087
+ return "medium";
5088
+ default:
5089
+ return "medium";
5090
+ }
5091
+ }
5092
+ function classifyAdded(entry) {
5093
+ switch (entry.event.type) {
5094
+ case "WARNING":
5095
+ return "high";
5096
+ case "REGRESSION":
5097
+ return "critical";
5098
+ case "ANNOUNCEMENT":
5099
+ return "medium";
5100
+ case "FOCUS_CHANGED":
5101
+ return "medium";
5102
+ default:
5103
+ return "low";
5104
+ }
5105
+ }
5106
+ function classifyModified(entry) {
5107
+ switch (entry.event.type) {
5108
+ case "FOCUS_CHANGED":
5109
+ return "high";
5110
+ case "STATE_CHANGED":
5111
+ return "high";
5112
+ case "ACCESSIBLE_NAME_CHANGED":
5113
+ return "medium";
5114
+ case "ANNOUNCEMENT":
5115
+ return "medium";
5116
+ default:
5117
+ return "medium";
5118
+ }
5119
+ }
5120
+
5121
+ // src/runtime/baseline-storage.ts
5122
+ import { readFile, writeFile, mkdir, access } from "fs/promises";
5123
+ import { join, dirname } from "path";
5124
+ var SPEAKABLE_VERSION2 = "1.3.0";
5125
+ function createBaselineStorage(baseDir) {
5126
+ function sanitize(name) {
5127
+ return name.toLowerCase().replace(/[/\\]/g, "-").replace(/[^a-z0-9._-]/g, "-");
5128
+ }
5129
+ function getPath(componentName, storyName) {
5130
+ return join(baseDir, sanitize(componentName), `${sanitize(storyName)}.timeline.json`);
5131
+ }
5132
+ return {
5133
+ async save(componentName, storyName, timeline, meta) {
5134
+ const filePath = getPath(componentName, storyName);
5135
+ const dir = dirname(filePath);
5136
+ try {
5137
+ await mkdir(dir, { recursive: true });
5138
+ } catch (err) {
5139
+ throw new Error(`Cannot create baseline directory "${dir}": ${err.message}`);
5140
+ }
5141
+ const baselineFile = {
5142
+ baseline: {
5143
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5144
+ speakableVersion: SPEAKABLE_VERSION2,
5145
+ storybookUrl: meta?.storybookUrl,
5146
+ interactionSequence: timeline.interactionSequence
5147
+ },
5148
+ timeline
5149
+ };
5150
+ const json = JSON.stringify(baselineFile, null, 2);
5151
+ try {
5152
+ await writeFile(filePath, json, "utf-8");
5153
+ } catch (err) {
5154
+ throw new Error(`Cannot write baseline file "${filePath}": ${err.message}`);
5155
+ }
5156
+ },
5157
+ async load(componentName, storyName) {
5158
+ const filePath = getPath(componentName, storyName);
5159
+ try {
5160
+ const content = await readFile(filePath, "utf-8");
5161
+ const parsed = JSON.parse(content);
5162
+ return parsed;
5163
+ } catch {
5164
+ return null;
5165
+ }
5166
+ },
5167
+ async exists(componentName, storyName) {
5168
+ const filePath = getPath(componentName, storyName);
5169
+ try {
5170
+ await access(filePath);
5171
+ return true;
5172
+ } catch {
5173
+ return false;
5174
+ }
5175
+ },
5176
+ getBaselinePath(componentName, storyName) {
5177
+ return getPath(componentName, storyName);
5178
+ }
5179
+ };
5180
+ }
2661
5181
  export {
2662
5182
  CURRENT_MODEL_VERSION,
2663
5183
  ParsingError,
@@ -2691,6 +5211,7 @@ export {
2691
5211
  renderNVDA,
2692
5212
  renderNarrator,
2693
5213
  renderVoiceOver,
5214
+ runtime_exports as runtime,
2694
5215
  serializeModel,
2695
5216
  validateHTMLNotEmpty,
2696
5217
  validateModel,