@generative-a11y/dom 0.2.1 → 0.3.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/README.md +57 -32
- package/dist/index.cjs +64 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -16
- package/dist/index.d.ts +26 -16
- package/dist/index.js +61 -8
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -13,63 +13,63 @@ npm install @generative-a11y/core @generative-a11y/dom
|
|
|
13
13
|
|
|
14
14
|
## Connect a runtime
|
|
15
15
|
|
|
16
|
-
`
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
runtime.
|
|
16
|
+
`bindRuntime(runtime, options?)` creates an `Announcer`, subscribes it to a
|
|
17
|
+
`Runtime`, and returns a `RuntimeBinding`. Disposing the binding unsubscribes
|
|
18
|
+
and disposes the announcer, but never disposes the borrowed runtime.
|
|
20
19
|
|
|
21
20
|
```ts
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
21
|
+
import { createRuntime } from "@generative-a11y/core";
|
|
22
|
+
import { bindRuntime } from "@generative-a11y/dom";
|
|
24
23
|
|
|
25
|
-
const runtime =
|
|
26
|
-
const binding =
|
|
24
|
+
const runtime = createRuntime();
|
|
25
|
+
const binding = bindRuntime(runtime);
|
|
27
26
|
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
// Call when the chat surface is removed.
|
|
28
|
+
export function disposeChat() {
|
|
29
|
+
binding.dispose();
|
|
30
|
+
runtime.dispose();
|
|
31
|
+
}
|
|
31
32
|
```
|
|
32
33
|
|
|
33
|
-
`
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
`RuntimeBinding` exposes the connected `announcer` and an idempotent `dispose()`
|
|
35
|
+
method. Once disposed, the binding cannot mutate its regions even if the runtime
|
|
36
|
+
was already delivering an event. If subscription fails, any regions created for
|
|
37
|
+
the attempted binding are removed before the error is rethrown.
|
|
37
38
|
|
|
38
39
|
## Create an announcer directly
|
|
39
40
|
|
|
40
|
-
`
|
|
41
|
+
`createAnnouncer(options?)` returns an `Announcer`. When a document is
|
|
41
42
|
available, it synchronously mounts one polite and one assertive region before
|
|
42
43
|
returning. Each announcer owns an isolated pair. Without an injected or global
|
|
43
44
|
document it remains inert, so the module and constructor are safe in server
|
|
44
45
|
environments.
|
|
45
46
|
|
|
46
47
|
```ts
|
|
47
|
-
import {
|
|
48
|
+
import { createAnnouncer } from "@generative-a11y/dom";
|
|
48
49
|
|
|
49
|
-
const announcer =
|
|
50
|
+
const announcer = createAnnouncer({ mode: "auto" });
|
|
50
51
|
const result = announcer.announce(intent);
|
|
51
|
-
announcer.dispose()
|
|
52
|
+
// Call announcer.dispose() when its owning surface is removed.
|
|
52
53
|
```
|
|
53
54
|
|
|
54
|
-
`
|
|
55
|
+
`Announcer` provides:
|
|
55
56
|
|
|
56
|
-
- `announce(intent)`, which returns a `
|
|
57
|
-
- `getRegions()`, which returns the `
|
|
58
|
-
|
|
57
|
+
- `announce(intent)`, which returns a `DeliveryResult`.
|
|
58
|
+
- `getRegions()`, which returns the `LiveRegions` pair or `undefined` when the
|
|
59
|
+
DOM is unavailable.
|
|
59
60
|
- An idempotent `dispose()`. It removes regions created by the announcer and
|
|
60
61
|
leaves supplied regions mounted. Later announcements report `disposed`.
|
|
61
62
|
|
|
62
63
|
## Options and modes
|
|
63
64
|
|
|
64
|
-
`
|
|
65
|
+
`AnnouncerOptions` accepts:
|
|
65
66
|
|
|
66
67
|
- `document`: an injected `Document`. If omitted, creation uses a supplied
|
|
67
68
|
region's owner document and then the current global document, when available.
|
|
68
|
-
- `mode`: a `
|
|
69
|
-
`
|
|
70
|
-
`ariaNotify` on the selected region and fall back when it is absent.
|
|
69
|
+
- `mode`: a `DeliveryMode` of `"auto"` or `"live-region"`. `"auto"` tries a
|
|
70
|
+
callable `ariaNotify` on the selected region and falls back when it is absent.
|
|
71
71
|
`"live-region"` always uses text mutation.
|
|
72
|
-
- `regions`: a pre-mounted `
|
|
72
|
+
- `regions`: a pre-mounted `LiveRegions` pair with `polite` and `assertive`
|
|
73
73
|
elements. Supply dedicated, connected, empty elements in the same document;
|
|
74
74
|
neither element may contain the other, and an explicitly supplied `document`
|
|
75
75
|
must be their owner document. The driver normalizes direct hiding attributes
|
|
@@ -77,8 +77,8 @@ announcer.dispose();
|
|
|
77
77
|
required live-region attributes and visually hidden inline styles. The caller
|
|
78
78
|
must ensure ancestors and external CSS keep both regions in the accessibility
|
|
79
79
|
tree. Supplied elements remain owned by the caller.
|
|
80
|
-
- `
|
|
81
|
-
|
|
80
|
+
- `onDelivery`: a callback invoked with the `DeliveryResult` for each attempted
|
|
81
|
+
announcement. Callback errors are isolated from delivery.
|
|
82
82
|
|
|
83
83
|
If `ariaNotify` throws, that notifier is disabled for the announcer. The same
|
|
84
84
|
intent is delivered once through live-region mutation, and later intents remain
|
|
@@ -86,7 +86,7 @@ on that fallback path.
|
|
|
86
86
|
|
|
87
87
|
## Delivery results
|
|
88
88
|
|
|
89
|
-
`
|
|
89
|
+
`DeliveryResult` is serializable and contains:
|
|
90
90
|
|
|
91
91
|
- `status`: `"notified"`, `"mutated"`, `"unavailable"`, or `"disposed"`.
|
|
92
92
|
- `method`: `"aria-notify"`, `"live-region"`, or `"none"`.
|
|
@@ -98,7 +98,7 @@ on that fallback path.
|
|
|
98
98
|
- `error`, when notifier invocation failed, with serializable `name` and
|
|
99
99
|
`message` strings.
|
|
100
100
|
|
|
101
|
-
`
|
|
101
|
+
`LiveRegions` contains the stable outer `polite` and `assertive` elements.
|
|
102
102
|
Live-region delivery sets or clears `lang` from the intent locale and replaces
|
|
103
103
|
the region's text content on every delivery, including repeated identical text.
|
|
104
104
|
Announcement strings are inserted as literal text, never HTML. The result
|
|
@@ -335,3 +335,28 @@ preference returns that preset without granular policy overrides.
|
|
|
335
335
|
prepares paced announcement intents.
|
|
336
336
|
- [`@generative-a11y/react`](https://www.npmjs.com/package/@generative-a11y/react)
|
|
337
337
|
connects core and DOM delivery to React applications.
|
|
338
|
+
|
|
339
|
+
### Attention policy binding
|
|
340
|
+
|
|
341
|
+
`bindAttention({ runtime, attentionStore })` forwards the store's initial mode
|
|
342
|
+
and subsequent mode changes as `attention.changed` events. It is opt-in:
|
|
343
|
+
creating an attention store alone remains observational. Configure the runtime
|
|
344
|
+
with `policy: { attention: { enabled: true } }` to apply those observations to
|
|
345
|
+
announcement policy. Native observations are evidence about visibility and
|
|
346
|
+
focus, not proof of assistive-technology activity.
|
|
347
|
+
|
|
348
|
+
The returned `AttentionBinding` has an idempotent `dispose()` method. It
|
|
349
|
+
unsubscribes and resets the observed mode to `unknown`, preserving explicit user
|
|
350
|
+
overrides. Both inputs are borrowed and remain usable after cleanup. A second
|
|
351
|
+
binding for the same runtime throws, including bindings created by React.
|
|
352
|
+
`AttentionBindingOptions` describes the two required inputs. Construction rolls
|
|
353
|
+
back on store failures; unsubscribe failures cannot prevent the reset.
|
|
354
|
+
|
|
355
|
+
## Localized announcements
|
|
356
|
+
|
|
357
|
+
Core resolves the actual announcement language before delivery. Catalog notices
|
|
358
|
+
may use a different locale from response text. DOM applies that locale before
|
|
359
|
+
either delivery path; its API and ownership remain unchanged.
|
|
360
|
+
|
|
361
|
+
See the
|
|
362
|
+
[localization guide](https://generativea11y.com/docs/localized-announcements).
|
package/dist/index.cjs
CHANGED
|
@@ -20,10 +20,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
+
bindAttention: () => bindAttention,
|
|
24
|
+
bindRuntime: () => bindRuntime,
|
|
23
25
|
captureFocus: () => captureFocus,
|
|
24
|
-
|
|
26
|
+
createAnnouncer: () => createAnnouncer,
|
|
25
27
|
createAttentionStore: () => createAttentionStore,
|
|
26
|
-
createDOMAnnouncer: () => createDOMAnnouncer,
|
|
27
28
|
createPreferenceStore: () => createPreferenceStore,
|
|
28
29
|
defaultPreferences: () => defaultPreferences,
|
|
29
30
|
focusElement: () => focusElement,
|
|
@@ -34,6 +35,56 @@ __export(index_exports, {
|
|
|
34
35
|
});
|
|
35
36
|
module.exports = __toCommonJS(index_exports);
|
|
36
37
|
|
|
38
|
+
// src/attention-binding.ts
|
|
39
|
+
var boundRuntimes = /* @__PURE__ */ new WeakSet();
|
|
40
|
+
function bindAttention({
|
|
41
|
+
runtime,
|
|
42
|
+
attentionStore
|
|
43
|
+
}) {
|
|
44
|
+
if (boundRuntimes.has(runtime)) {
|
|
45
|
+
throw new Error("Runtime already has an attention binding");
|
|
46
|
+
}
|
|
47
|
+
boundRuntimes.add(runtime);
|
|
48
|
+
let active = true;
|
|
49
|
+
let unsubscribe;
|
|
50
|
+
let lastMode;
|
|
51
|
+
let revision = 0;
|
|
52
|
+
const update = () => {
|
|
53
|
+
if (!active) return;
|
|
54
|
+
const readRevision = ++revision;
|
|
55
|
+
const mode = attentionStore.getSnapshot().mode;
|
|
56
|
+
if (!active || revision !== readRevision || mode === lastMode) return;
|
|
57
|
+
lastMode = mode;
|
|
58
|
+
runtime.dispatch({ type: "attention.changed", mode });
|
|
59
|
+
};
|
|
60
|
+
const dispose = () => {
|
|
61
|
+
if (!active) return;
|
|
62
|
+
active = false;
|
|
63
|
+
try {
|
|
64
|
+
try {
|
|
65
|
+
unsubscribe?.();
|
|
66
|
+
} catch {
|
|
67
|
+
}
|
|
68
|
+
if (lastMode !== void 0) {
|
|
69
|
+
runtime.dispatch({ type: "attention.changed", mode: "unknown" });
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
boundRuntimes.delete(runtime);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
try {
|
|
76
|
+
unsubscribe = attentionStore.subscribe(update);
|
|
77
|
+
update();
|
|
78
|
+
} catch (error) {
|
|
79
|
+
try {
|
|
80
|
+
dispose();
|
|
81
|
+
} catch {
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
return { dispose };
|
|
86
|
+
}
|
|
87
|
+
|
|
37
88
|
// src/composed-tree.ts
|
|
38
89
|
function deepActiveElement(document2) {
|
|
39
90
|
let active = document2.activeElement;
|
|
@@ -181,7 +232,7 @@ function createAttentionStore(options = {}) {
|
|
|
181
232
|
update();
|
|
182
233
|
};
|
|
183
234
|
};
|
|
184
|
-
const
|
|
235
|
+
const createChatObserver = (registration, target) => {
|
|
185
236
|
const factory = options.createIntersectionObserver ?? defaultIntersectionObserverFactory(selectedWindow);
|
|
186
237
|
if (!factory) return void 0;
|
|
187
238
|
let created;
|
|
@@ -231,7 +282,7 @@ function createAttentionStore(options = {}) {
|
|
|
231
282
|
stopObserver(newestTarget);
|
|
232
283
|
newestTarget = element;
|
|
233
284
|
newestResult = "unknown";
|
|
234
|
-
observer =
|
|
285
|
+
observer = createChatObserver(registration, element);
|
|
235
286
|
update();
|
|
236
287
|
let registered = true;
|
|
237
288
|
return () => {
|
|
@@ -799,7 +850,9 @@ function serializeError(cause) {
|
|
|
799
850
|
}
|
|
800
851
|
|
|
801
852
|
// src/index.ts
|
|
802
|
-
function
|
|
853
|
+
function createAnnouncer(options = {}) {
|
|
854
|
+
if (options.mode !== void 0 && options.mode !== "auto" && options.mode !== "live-region")
|
|
855
|
+
throw new TypeError('mode must be "auto" or "live-region"');
|
|
803
856
|
validateSuppliedRegions(options);
|
|
804
857
|
const selectedDocument = options.document ?? options.regions?.polite.ownerDocument ?? (typeof document === "undefined" ? void 0 : document);
|
|
805
858
|
const ownsRegions = options.regions === void 0;
|
|
@@ -812,7 +865,7 @@ function createDOMAnnouncer(options = {}) {
|
|
|
812
865
|
let disposed = false;
|
|
813
866
|
const report = (result) => {
|
|
814
867
|
try {
|
|
815
|
-
options.
|
|
868
|
+
options.onDelivery?.(result);
|
|
816
869
|
} catch {
|
|
817
870
|
}
|
|
818
871
|
return result;
|
|
@@ -990,8 +1043,8 @@ function applyLocale(region, locale) {
|
|
|
990
1043
|
if (locale === void 0) region.removeAttribute("lang");
|
|
991
1044
|
else region.setAttribute("lang", locale);
|
|
992
1045
|
}
|
|
993
|
-
function
|
|
994
|
-
const announcer =
|
|
1046
|
+
function bindRuntime(runtime, options = {}) {
|
|
1047
|
+
const announcer = createAnnouncer(options);
|
|
995
1048
|
let disposed = false;
|
|
996
1049
|
let unsubscribe;
|
|
997
1050
|
try {
|
|
@@ -1017,10 +1070,11 @@ function connectRuntimeToDOM(runtime, options = {}) {
|
|
|
1017
1070
|
}
|
|
1018
1071
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1019
1072
|
0 && (module.exports = {
|
|
1073
|
+
bindAttention,
|
|
1074
|
+
bindRuntime,
|
|
1020
1075
|
captureFocus,
|
|
1021
|
-
|
|
1076
|
+
createAnnouncer,
|
|
1022
1077
|
createAttentionStore,
|
|
1023
|
-
createDOMAnnouncer,
|
|
1024
1078
|
createPreferenceStore,
|
|
1025
1079
|
defaultPreferences,
|
|
1026
1080
|
focusElement,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/composed-tree.ts","../src/attention.ts","../src/focus.ts","../src/preferences.ts"],"sourcesContent":["import type {\n AnnouncementIntent,\n GenerativeA11yRuntime,\n} from \"@generative-a11y/core\";\n\nexport {\n createAttentionStore,\n type AttentionIntersectionObserver,\n type AttentionIntersectionObserverFactory,\n type AttentionSnapshot,\n type AttentionStore,\n type AttentionStoreOptions,\n type ExternalStore,\n} from \"./attention.js\";\n\nexport {\n captureFocus,\n focusElement,\n restoreFocus,\n type FocusCapture,\n type FocusElementOptions,\n type FocusResult,\n type FocusSkippedReason,\n type RestoreFocusOptions,\n} from \"./focus.js\";\n\nexport {\n createPreferenceStore,\n defaultPreferences,\n normalizePreferences,\n preferencesToCoreConfiguration,\n type CorePreferenceConfiguration,\n type PreferenceDiagnostic,\n type PreferenceDiagnosticCode,\n type PreferenceDiagnosticSource,\n type PreferencePersistence,\n type PreferenceSchemaV1,\n type PreferenceStorage,\n type PreferenceStorageEvent,\n type PreferenceStorageEventSource,\n type PreferenceStore,\n type PreferenceStoreOptions,\n samePreferences,\n type StreamingVerbosity,\n type ToolVerbosity,\n} from \"./preferences.js\";\n\nexport type DOMAnnouncementMode = \"auto\" | \"aria-notify\" | \"live-region\";\n\nexport interface DOMLiveRegions {\n polite: HTMLElement;\n assertive: HTMLElement;\n}\n\nexport interface DOMDeliveryResult {\n status: \"notified\" | \"mutated\" | \"unavailable\" | \"disposed\";\n method: \"aria-notify\" | \"live-region\" | \"none\";\n channel: AnnouncementIntent[\"channel\"];\n announcementId: string;\n sourceType: AnnouncementIntent[\"sourceType\"];\n at: number;\n sourceEventId?: string;\n responseId?: string;\n toolId?: string;\n interactionId?: string;\n /** Stable logical run identity associated with the delivered intent. */\n runId?: string;\n /** Stable run attempt identity associated with the delivered intent. */\n runInstanceId?: string;\n /** Stable logical step identity associated with the delivered intent. */\n stepId?: string;\n /** Stable step attempt identity associated with the delivered intent. */\n stepInstanceId?: string;\n error?: { name: string; message: string };\n}\n\nexport interface DOMAnnouncerOptions {\n document?: Document;\n mode?: DOMAnnouncementMode;\n regions?: DOMLiveRegions;\n onDiagnostic?: (result: DOMDeliveryResult) => void;\n}\n\nexport interface DOMAnnouncer {\n announce(intent: AnnouncementIntent): DOMDeliveryResult;\n getRegions(): DOMLiveRegions | undefined;\n dispose(): void;\n}\n\nexport interface DOMRuntimeBinding {\n announcer: DOMAnnouncer;\n dispose(): void;\n}\n\nexport function createDOMAnnouncer(\n options: DOMAnnouncerOptions = {},\n): DOMAnnouncer {\n validateSuppliedRegions(options);\n const selectedDocument =\n options.document ??\n options.regions?.polite.ownerDocument ??\n (typeof document === \"undefined\" ? undefined : document);\n const ownsRegions = options.regions === undefined;\n const regions = options.regions ?? createLiveRegions(selectedDocument);\n\n if (regions) {\n configureRegion(regions.polite, \"polite\");\n configureRegion(regions.assertive, \"assertive\");\n }\n let notifierEnabled = true;\n let disposed = false;\n\n const report = (result: DOMDeliveryResult): DOMDeliveryResult => {\n try {\n options.onDiagnostic?.(result);\n } catch {\n // Diagnostics are observational and cannot affect delivery.\n }\n return result;\n };\n\n return {\n announce(intent) {\n if (disposed) {\n return report({\n status: \"disposed\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n if (regions) {\n const region = regions[intent.channel];\n applyLocale(region, intent.locale);\n let error: DOMDeliveryResult[\"error\"];\n if (notifierEnabled && options.mode !== \"live-region\") {\n let notified = false;\n try {\n const ariaNotify = (region as AriaNotifyRegion).ariaNotify;\n if (typeof ariaNotify === \"function\") {\n ariaNotify.call(region, intent.text, {\n priority: intent.channel === \"assertive\" ? \"high\" : \"normal\",\n });\n notified = true;\n }\n } catch (cause) {\n notifierEnabled = false;\n error = serializeError(cause);\n }\n if (notified) {\n return report({\n status: \"notified\",\n method: \"aria-notify\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n }\n region.textContent = intent.text;\n return report({\n status: \"mutated\",\n method: \"live-region\",\n channel: intent.channel,\n ...deliveryContext(intent),\n ...(error === undefined ? {} : { error }),\n });\n }\n return report({\n status: \"unavailable\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n },\n getRegions() {\n return regions;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n if (ownsRegions) {\n regions?.polite.remove();\n regions?.assertive.remove();\n }\n },\n };\n}\n\nfunction deliveryContext(\n intent: AnnouncementIntent,\n): Pick<\n DOMDeliveryResult,\n | \"announcementId\"\n | \"sourceType\"\n | \"at\"\n | \"sourceEventId\"\n | \"responseId\"\n | \"toolId\"\n | \"interactionId\"\n | \"runId\"\n | \"runInstanceId\"\n | \"stepId\"\n | \"stepInstanceId\"\n> {\n return {\n announcementId: intent.id,\n sourceType: intent.sourceType,\n at: intent.at,\n ...(intent.sourceEventId !== undefined\n ? { sourceEventId: intent.sourceEventId }\n : {}),\n ...(intent.responseId !== undefined\n ? { responseId: intent.responseId }\n : {}),\n ...(intent.toolId !== undefined ? { toolId: intent.toolId } : {}),\n ...(intent.interactionId !== undefined\n ? { interactionId: intent.interactionId }\n : {}),\n ...(intent.runId !== undefined ? { runId: intent.runId } : {}),\n ...(intent.runInstanceId !== undefined\n ? { runInstanceId: intent.runInstanceId }\n : {}),\n ...(intent.stepId !== undefined ? { stepId: intent.stepId } : {}),\n ...(intent.stepInstanceId !== undefined\n ? { stepInstanceId: intent.stepInstanceId }\n : {}),\n };\n}\n\nfunction validateSuppliedRegions(options: DOMAnnouncerOptions): void {\n if (options.regions === undefined) return;\n const { polite, assertive } = options.regions;\n if (polite === assertive) {\n throw new TypeError(\n \"Polite and assertive regions must be distinct elements\",\n );\n }\n if (!polite.isConnected || !assertive.isConnected) {\n throw new TypeError(\"Supplied regions must be connected\");\n }\n if (polite.contains(assertive) || assertive.contains(polite)) {\n throw new TypeError(\n \"Polite and assertive regions must not contain one another\",\n );\n }\n if (polite.ownerDocument !== assertive.ownerDocument) {\n throw new TypeError(\n \"Polite and assertive regions must belong to the same document\",\n );\n }\n if (\n options.document !== undefined &&\n (polite.ownerDocument !== options.document ||\n assertive.ownerDocument !== options.document)\n ) {\n throw new TypeError(\n \"Supplied regions must belong to the provided document\",\n );\n }\n}\n\nfunction serializeError(\n error: unknown,\n): NonNullable<DOMDeliveryResult[\"error\"]> {\n try {\n if (error instanceof Error) {\n return {\n name: readErrorString(error, \"name\", \"Error\"),\n message: readErrorString(error, \"message\", \"Unknown error\"),\n };\n }\n } catch {\n // Hostile proxies can throw during instanceof checks.\n }\n return { name: \"Error\", message: safeString(error, \"Unknown error\") };\n}\n\nfunction readErrorString(\n error: Error,\n property: \"name\" | \"message\",\n fallback: string,\n): string {\n try {\n return safeString(error[property], fallback);\n } catch {\n return fallback;\n }\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\ninterface AriaNotifyRegion extends HTMLElement {\n ariaNotify?: (\n text: string,\n options?: { priority: \"normal\" | \"high\" },\n ) => void;\n}\n\nfunction createLiveRegions(\n selectedDocument: Document | undefined,\n): DOMLiveRegions | undefined {\n const parent = selectedDocument?.body ?? selectedDocument?.documentElement;\n if (!selectedDocument || !parent) return undefined;\n\n const regions = {\n polite: selectedDocument.createElement(\"div\"),\n assertive: selectedDocument.createElement(\"div\"),\n };\n parent.append(regions.polite, regions.assertive);\n return regions;\n}\n\nfunction configureRegion(\n region: HTMLElement,\n channel: AnnouncementIntent[\"channel\"],\n): void {\n region.removeAttribute(\"role\");\n region.removeAttribute(\"aria-busy\");\n region.removeAttribute(\"hidden\");\n region.removeAttribute(\"aria-hidden\");\n region.inert = false;\n region.removeAttribute(\"inert\");\n region.style.removeProperty(\"display\");\n region.style.removeProperty(\"visibility\");\n region.style.removeProperty(\"content-visibility\");\n region.setAttribute(\"aria-live\", channel);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(\"aria-relevant\", \"additions text\");\n Object.assign(region.style, {\n position: \"absolute\",\n width: \"1px\",\n height: \"1px\",\n padding: \"0\",\n margin: \"-1px\",\n overflow: \"hidden\",\n clip: \"rect(0, 0, 0, 0)\",\n whiteSpace: \"nowrap\",\n border: \"0\",\n });\n}\n\nfunction applyLocale(region: HTMLElement, locale: string | undefined): void {\n if (locale === undefined) region.removeAttribute(\"lang\");\n else region.setAttribute(\"lang\", locale);\n}\n\nexport function connectRuntimeToDOM(\n runtime: GenerativeA11yRuntime,\n options: DOMAnnouncerOptions = {},\n): DOMRuntimeBinding {\n const announcer = createDOMAnnouncer(options);\n let disposed = false;\n let unsubscribe: () => void;\n try {\n unsubscribe = runtime.subscribeAnnouncements((intent) => {\n if (!disposed) announcer.announce(intent);\n });\n } catch (cause) {\n announcer.dispose();\n throw cause;\n }\n\n return {\n announcer,\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n unsubscribe();\n } finally {\n announcer.dispose();\n }\n },\n };\n}\n","export function deepActiveElement(document: Document): Element | null {\n let active = document.activeElement;\n const visited = new Set<Element>();\n while (active) {\n if (visited.has(active)) throw new Error(\"Cyclic active element\");\n visited.add(active);\n const shadow = (active as Element & { shadowRoot?: ShadowRoot | null })\n .shadowRoot;\n const nested = shadow?.activeElement;\n if (!nested) return active;\n active = nested;\n }\n return null;\n}\n\nexport function composedContains(ancestor: Element, target: Element): boolean {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (current === ancestor) return true;\n if (visited.has(current)) throw new Error(\"Cyclic composed tree\");\n visited.add(current);\n current = composedParent(current);\n }\n return false;\n}\n\nexport function composedParent(element: Element): Element | null {\n const assignedSlot = (\n element as Element & { assignedSlot?: HTMLSlotElement | null }\n ).assignedSlot;\n if (assignedSlot) return assignedSlot;\n if (element.parentElement) return element.parentElement;\n const root = element.getRootNode();\n if (root && \"host\" in root) {\n const host = (root as ShadowRoot).host;\n if (host.ownerDocument === element.ownerDocument) return host;\n }\n return null;\n}\n","import { composedContains, deepActiveElement } from \"./composed-tree.js\";\n\nexport interface ExternalStore<T> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): T;\n getServerSnapshot(): T;\n}\n\nexport interface AttentionSnapshot {\n readonly visibility: \"visible\" | \"hidden\" | \"unknown\";\n readonly windowFocus: \"focused\" | \"blurred\" | \"unknown\";\n readonly focusArea:\n \"composer\" | \"conversation\" | \"elsewhere\" | \"none\" | \"unknown\";\n readonly newestResponse: \"visible\" | \"outside\" | \"unobserved\" | \"unknown\";\n readonly mode:\n \"foreground\" | \"background\" | \"reading-history\" | \"away\" | \"unknown\";\n}\n\nexport interface AttentionStore extends ExternalStore<AttentionSnapshot> {\n registerComposer(element: Element): () => void;\n registerConversation(element: Element): () => void;\n registerNewestResponse(element: Element): () => void;\n dispose(): void;\n}\n\nexport interface AttentionStoreOptions {\n document?: Document;\n createIntersectionObserver?: AttentionIntersectionObserverFactory;\n intersectionObserverInit?: IntersectionObserverInit;\n}\n\nexport interface AttentionIntersectionObserver {\n observe(target: Element): void;\n unobserve(target: Element): void;\n disconnect(): void;\n}\n\nexport type AttentionIntersectionObserverFactory = (\n callback: IntersectionObserverCallback,\n options?: IntersectionObserverInit,\n) => AttentionIntersectionObserver;\n\nconst UNKNOWN_SNAPSHOT: AttentionSnapshot = Object.freeze({\n visibility: \"unknown\",\n windowFocus: \"unknown\",\n focusArea: \"unknown\",\n newestResponse: \"unknown\",\n mode: \"unknown\",\n});\n\nexport function createAttentionStore(\n options: AttentionStoreOptions = {},\n): AttentionStore {\n const selectedDocument =\n options.document ??\n (typeof document === \"undefined\" ? undefined : document);\n if (!selectedDocument) {\n return {\n subscribe: () => () => undefined,\n getSnapshot: () => UNKNOWN_SNAPSHOT,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: () => () => undefined,\n registerConversation: () => () => undefined,\n registerNewestResponse: () => () => undefined,\n dispose: () => undefined,\n };\n }\n\n const listeners = new Set<() => void>();\n const composers = new Map<Element, number>();\n const conversations = new Map<Element, number>();\n const selectedWindow = selectedDocument.defaultView;\n let disposed = false;\n let newestTarget: Element | undefined;\n let newestResult: AttentionSnapshot[\"newestResponse\"] = \"unobserved\";\n let newestRegistration = 0;\n let observer: AttentionIntersectionObserver | undefined;\n let snapshot = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n const update = () => {\n if (disposed) return;\n const next = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n if (sameSnapshot(snapshot, next)) return;\n snapshot = next;\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store observers cannot prevent other observers from running.\n }\n }\n };\n const handleFocusOut = (event: FocusEvent) => {\n if (event.relatedTarget === null) update();\n };\n const listenerCleanups: Array<() => void> = [];\n const installListener = (install: () => void, cleanup: () => void): void => {\n // Register cleanup first because a hostile EventTarget can install and then\n // throw from addEventListener(). Removing a listener that was not installed\n // is harmless, while omitting cleanup would leak the accepted listener.\n listenerCleanups.push(cleanup);\n install();\n };\n const cleanupListeners = (): void => {\n for (const cleanup of listenerCleanups.splice(0).reverse()) {\n try {\n cleanup();\n } catch {\n // One hostile removal cannot strand the remaining listeners.\n }\n }\n };\n try {\n installListener(\n () => selectedDocument.addEventListener(\"visibilitychange\", update),\n () => selectedDocument.removeEventListener(\"visibilitychange\", update),\n );\n if (selectedWindow) {\n installListener(\n () => selectedWindow.addEventListener(\"focus\", update),\n () => selectedWindow.removeEventListener(\"focus\", update),\n );\n installListener(\n () => selectedWindow.addEventListener(\"blur\", update),\n () => selectedWindow.removeEventListener(\"blur\", update),\n );\n }\n installListener(\n () => selectedDocument.addEventListener(\"focusin\", update),\n () => selectedDocument.removeEventListener(\"focusin\", update),\n );\n installListener(\n () => selectedDocument.addEventListener(\"focusout\", handleFocusOut),\n () => selectedDocument.removeEventListener(\"focusout\", handleFocusOut),\n );\n } catch (error) {\n cleanupListeners();\n throw error;\n }\n\n const register = (\n elements: Map<Element, number>,\n element: Element,\n ): (() => void) => {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n elements.set(element, (elements.get(element) ?? 0) + 1);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n const remaining = (elements.get(element) ?? 1) - 1;\n if (remaining === 0) elements.delete(element);\n else elements.set(element, remaining);\n update();\n };\n };\n\n const createObserver = (\n registration: number,\n target: Element,\n ): AttentionIntersectionObserver | undefined => {\n const factory =\n options.createIntersectionObserver ??\n defaultIntersectionObserverFactory(selectedWindow);\n if (!factory) return undefined;\n let created: AttentionIntersectionObserver | undefined;\n try {\n created = factory((entries) => {\n if (\n disposed ||\n registration !== newestRegistration ||\n newestTarget !== target ||\n observer !== created\n ) {\n return;\n }\n let latest: IntersectionObserverEntry | undefined;\n for (const entry of entries) {\n if (entry.target === target) latest = entry;\n }\n if (!latest) return;\n newestResult = latest.isIntersecting ? \"visible\" : \"outside\";\n update();\n }, options.intersectionObserverInit);\n created.observe(target);\n return created;\n } catch {\n cleanupObserver(created, target);\n return undefined;\n }\n };\n\n const stopObserver = (target?: Element): void => {\n const current = observer;\n observer = undefined;\n cleanupObserver(current, target);\n };\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: (element) => register(composers, element),\n registerConversation: (element) => register(conversations, element),\n registerNewestResponse(element) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n const registration = ++newestRegistration;\n stopObserver(newestTarget);\n newestTarget = element;\n newestResult = \"unknown\";\n observer = createObserver(registration, element);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n if (registration !== newestRegistration || newestTarget !== element)\n return;\n stopObserver(element);\n newestTarget = undefined;\n newestResult = \"unobserved\";\n update();\n };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n listeners.clear();\n composers.clear();\n conversations.clear();\n stopObserver(newestTarget);\n newestTarget = undefined;\n cleanupListeners();\n },\n };\n}\n\nfunction makeSnapshot(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot {\n const visibility = readVisibility(document);\n const windowFocus = readWindowFocus(document);\n return Object.freeze({\n visibility,\n windowFocus,\n focusArea: readFocusArea(document, composers, conversations),\n newestResponse,\n mode: deriveMode(visibility, windowFocus, newestResponse),\n });\n}\n\nfunction deriveMode(\n visibility: AttentionSnapshot[\"visibility\"],\n windowFocus: AttentionSnapshot[\"windowFocus\"],\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot[\"mode\"] {\n if (visibility === \"hidden\") return \"background\";\n if (visibility !== \"visible\") return \"unknown\";\n if (windowFocus === \"blurred\") return \"away\";\n if (windowFocus !== \"focused\") return \"unknown\";\n if (newestResponse === \"outside\") return \"reading-history\";\n if (newestResponse === \"visible\") return \"foreground\";\n return \"unknown\";\n}\n\nfunction defaultIntersectionObserverFactory(\n window: (Window & typeof globalThis) | null,\n): AttentionIntersectionObserverFactory | undefined {\n const Constructor = window?.IntersectionObserver;\n if (typeof Constructor !== \"function\") return undefined;\n return (callback, options) => new Constructor(callback, options);\n}\n\nfunction cleanupObserver(\n observer: AttentionIntersectionObserver | undefined,\n target?: Element,\n): void {\n if (!observer) return;\n if (target) {\n try {\n observer.unobserve(target);\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n }\n try {\n observer.disconnect();\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n}\n\nfunction readFocusArea(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n): AttentionSnapshot[\"focusArea\"] {\n let activeElement: Element | null;\n try {\n activeElement = deepActiveElement(document);\n } catch {\n return \"unknown\";\n }\n if (\n activeElement === null ||\n activeElement === document.body ||\n activeElement === document.documentElement\n ) {\n return \"none\";\n }\n if (\n [...composers.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"composer\";\n }\n if (\n [...conversations.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"conversation\";\n }\n return \"elsewhere\";\n}\n\nfunction readVisibility(document: Document): AttentionSnapshot[\"visibility\"] {\n try {\n if (document.visibilityState === \"visible\") return \"visible\";\n if (document.visibilityState === \"hidden\") return \"hidden\";\n } catch {\n // Browser integrations can expose throwing accessors.\n }\n return \"unknown\";\n}\n\nfunction readWindowFocus(document: Document): AttentionSnapshot[\"windowFocus\"] {\n try {\n if (typeof document.hasFocus !== \"function\") return \"unknown\";\n return document.hasFocus() ? \"focused\" : \"blurred\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction sameSnapshot(\n left: AttentionSnapshot,\n right: AttentionSnapshot,\n): boolean {\n return (\n left.visibility === right.visibility &&\n left.windowFocus === right.windowFocus &&\n left.focusArea === right.focusArea &&\n left.newestResponse === right.newestResponse &&\n left.mode === right.mode\n );\n}\n","import {\n composedContains,\n composedParent,\n deepActiveElement,\n} from \"./composed-tree.js\";\n\nexport interface FocusCapture {\n readonly document: Document | null;\n readonly target: Element | null;\n}\n\nexport interface FocusElementOptions {\n preventScroll?: boolean;\n}\n\nexport interface RestoreFocusOptions extends FocusElementOptions {\n onlyIfFocusWithin?: Element;\n}\n\nexport type FocusSkippedReason =\n | \"unavailable\"\n | \"cross-document\"\n | \"disconnected\"\n | \"disabled\"\n | \"hidden\"\n | \"aria-hidden\"\n | \"inert\"\n | \"missing-focus\"\n | \"guard-mismatch\"\n | \"focus-error\"\n | \"focus-not-applied\";\n\nexport type FocusResult =\n | { readonly status: \"focused\"; readonly target: Element }\n | {\n readonly status: \"skipped\";\n readonly reason: FocusSkippedReason;\n readonly target: Element | null;\n };\n\nexport function captureFocus(selectedDocument?: Document): FocusCapture {\n const document =\n selectedDocument ??\n (typeof globalThis.document === \"undefined\"\n ? undefined\n : globalThis.document);\n if (!document) return Object.freeze({ document: null, target: null });\n let target: Element | null = null;\n try {\n const active = deepActiveElement(document);\n if (\n active !== null &&\n active !== document.body &&\n active !== document.documentElement &&\n active.ownerDocument === document\n ) {\n target = active;\n }\n } catch {\n // A hostile document is captured without a restorable target.\n }\n return Object.freeze({ document, target });\n}\n\nexport function focusElement(\n target: Element,\n options: FocusElementOptions = {},\n): FocusResult {\n const eligibility = focusEligibility(target);\n if (eligibility) {\n return { status: \"skipped\", reason: eligibility, target };\n }\n let focus: ((options?: FocusOptions) => void) | undefined;\n let document: Document;\n let previous: Element | null;\n try {\n document = target.ownerDocument;\n previous = deepActiveElement(document);\n focus = (target as Element & { focus?: (options?: FocusOptions) => void })\n .focus;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target };\n }\n if (typeof focus !== \"function\") {\n return { status: \"skipped\", reason: \"missing-focus\", target };\n }\n let focusThrew = false;\n try {\n focus.call(target, { preventScroll: options.preventScroll ?? true });\n } catch {\n focusThrew = true;\n }\n if (focusThrew) {\n restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n const postFocusEligibility = focusEligibility(target);\n let active: Element | null;\n try {\n active = deepActiveElement(document);\n } catch {\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n if (postFocusEligibility) {\n if (active === target) restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: postFocusEligibility, target };\n }\n if (active !== target) {\n return { status: \"skipped\", reason: \"focus-not-applied\", target };\n }\n return { status: \"focused\", target };\n}\n\nexport function restoreFocus(\n capture: FocusCapture,\n options: RestoreFocusOptions = {},\n): FocusResult {\n let document: Document | null;\n let target: Element | null;\n try {\n document = capture.document;\n target = capture.target;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n if (!document || !target) {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n try {\n if (target.ownerDocument !== document) {\n return { status: \"skipped\", reason: \"cross-document\", target };\n }\n const guard = options.onlyIfFocusWithin;\n if (guard !== undefined) {\n const active = deepActiveElement(document);\n if (\n guard.ownerDocument !== document ||\n active === null ||\n !composedContains(guard, active)\n ) {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n }\n } catch {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n return focusElement(target, options);\n}\n\nfunction focusEligibility(target: Element): FocusSkippedReason | undefined {\n let ownerDocument: Document;\n try {\n ownerDocument = target.ownerDocument;\n const ElementConstructor = ownerDocument.defaultView?.Element;\n if (\n !ownerDocument ||\n (ElementConstructor && !(target instanceof ElementConstructor))\n ) {\n return \"unavailable\";\n }\n if (target.isConnected !== true) return \"disconnected\";\n if (\n target.getAttribute(\"disabled\") !== null ||\n (target as Element & { disabled?: unknown }).disabled === true\n ) {\n return \"disabled\";\n }\n } catch {\n return \"unavailable\";\n }\n try {\n const matches = target.matches;\n if (typeof matches === \"function\" && matches.call(target, \":disabled\")) {\n return \"disabled\";\n }\n } catch {\n // Fall back to the direct disabled checks above.\n }\n\n try {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (visited.has(current)) return \"unavailable\";\n visited.add(current);\n if (current.hasAttribute(\"hidden\")) return \"hidden\";\n if (current.getAttribute(\"aria-hidden\")?.trim().toLowerCase() === \"true\")\n return \"aria-hidden\";\n if (\n current.hasAttribute(\"inert\") ||\n (current as Element & { inert?: unknown }).inert === true\n ) {\n return \"inert\";\n }\n current = composedParent(current);\n }\n } catch {\n return \"unavailable\";\n }\n\n try {\n const focus = (\n target as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus !== \"function\") return \"missing-focus\";\n } catch {\n return \"unavailable\";\n }\n return undefined;\n}\n\nfunction restorePreviousFocus(\n previous: Element | null,\n attempted: Element,\n document: Document,\n): void {\n try {\n if (\n !previous ||\n deepActiveElement(document) !== attempted ||\n focusEligibility(previous) !== undefined\n ) {\n return;\n }\n const focus = (\n previous as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus === \"function\")\n focus.call(previous, { preventScroll: true });\n } catch {\n // Focus rollback is best-effort at hostile DOM boundaries.\n }\n}\n","import type { PolicyOverrides, PresetName } from \"@generative-a11y/core\";\n\nimport type { ExternalStore } from \"./attention.js\";\n\nexport type StreamingVerbosity =\n \"preset\" | \"off\" | \"completion\" | \"paragraph\" | \"sentence\";\n\nexport type ToolVerbosity =\n \"preset\" | \"off\" | \"failures\" | \"status\" | \"progress\";\n\nexport type PreferenceSchemaV1 =\n | Readonly<{ version: 1; preset: \"completion-only\" }>\n | Readonly<{\n version: 1;\n preset: \"minimal\" | \"balanced\" | \"verbose\";\n streaming: StreamingVerbosity;\n tools: ToolVerbosity;\n }>;\n\nexport interface PreferenceStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nexport interface PreferenceStorageEvent {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly storageArea?: PreferenceStorage | null;\n}\n\nexport interface PreferenceStorageEventSource {\n subscribe(listener: (event: PreferenceStorageEvent) => void): () => void;\n}\n\nexport type PreferenceDiagnosticSource =\n | \"storage-read\"\n | \"storage-write\"\n | \"storage-event\"\n | \"event-subscribe\"\n | \"event-unsubscribe\";\n\nexport type PreferenceDiagnosticCode =\n | \"operation-failed\"\n | \"invalid-json\"\n | \"invalid-preference\"\n | \"unsupported-version\";\n\nexport interface PreferenceDiagnostic {\n readonly source: PreferenceDiagnosticSource;\n readonly code: PreferenceDiagnosticCode;\n readonly error?: Readonly<{ name: string; message: string }>;\n}\n\nexport interface PreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nexport interface PreferenceStoreOptions {\n readonly defaultValue?: PreferenceSchemaV1;\n readonly persistence?: PreferencePersistence;\n readonly onDiagnostic?: (diagnostic: PreferenceDiagnostic) => void;\n}\n\nexport interface PreferenceStore extends ExternalStore<PreferenceSchemaV1> {\n setPreferences(value: PreferenceSchemaV1): void;\n dispose(): void;\n}\n\nexport interface CorePreferenceConfiguration {\n readonly preset: PresetName;\n readonly policy?: PolicyOverrides;\n}\n\nexport const defaultPreferences: PreferenceSchemaV1 = Object.freeze({\n version: 1,\n preset: \"balanced\",\n streaming: \"preset\",\n tools: \"preset\",\n});\n\nexport function preferencesToCoreConfiguration(\n value: PreferenceSchemaV1,\n): CorePreferenceConfiguration {\n const preferences = normalizePreferences(value);\n if (preferences.preset === \"completion-only\") {\n return { preset: \"completion-only\" };\n }\n const policy: PolicyOverrides = {};\n const text = mapStreaming(preferences.streaming);\n const tools = mapTools(preferences.tools);\n if (text) policy.text = text;\n if (tools) policy.tools = tools;\n return Object.keys(policy).length === 0\n ? { preset: preferences.preset }\n : { preset: preferences.preset, policy };\n}\n\nexport function createPreferenceStore(\n options: PreferenceStoreOptions = {},\n): PreferenceStore {\n const configuredDefault = options.defaultValue\n ? normalizePreferences(options.defaultValue)\n : defaultPreferences;\n const persistence = resolvePersistence(options.persistence);\n const report = (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ): void => {\n const diagnostic: PreferenceDiagnostic = {\n source,\n code,\n ...(cause === undefined ? {} : { error: serializeError(cause) }),\n };\n try {\n options.onDiagnostic?.(diagnostic);\n } catch {\n // Diagnostics are observational.\n }\n };\n let current = configuredDefault;\n if (persistence?.storage) {\n try {\n const stored = persistence.storage.getItem(persistence.key);\n if (stored !== null) {\n current = parsePreferences(stored, \"storage-read\", report) ?? current;\n }\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n }\n let disposed = false;\n let eventEpoch = 0;\n const listeners = new Set<() => void>();\n let unsubscribeEvents: (() => void) | undefined;\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store listeners cannot prevent other listeners.\n }\n }\n };\n const replace = (next: PreferenceSchemaV1): boolean => {\n if (samePreferences(current, next)) return false;\n current = next;\n notify();\n return true;\n };\n const handleStorageEvent = (event: PreferenceStorageEvent): void => {\n if (disposed || !persistence) return;\n const epoch = ++eventEpoch;\n let key: string | null;\n let newValue: string | null;\n let storageArea: PreferenceStorage | null | undefined;\n try {\n key = event.key;\n newValue = event.newValue;\n storageArea = event.storageArea;\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n return;\n }\n if (disposed || epoch !== eventEpoch) return;\n try {\n if (storageArea != null && storageArea !== persistence.storage) {\n return;\n }\n if (key !== null && key !== persistence.key) return;\n if (key === null || newValue === null) {\n replace(configuredDefault);\n return;\n }\n const next = parsePreferences(newValue, \"storage-event\", report);\n if (!disposed && epoch === eventEpoch && next) replace(next);\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n }\n };\n\n if (persistence?.events) {\n try {\n unsubscribeEvents = persistence.events.subscribe(handleStorageEvent);\n } catch (cause) {\n report(\"event-subscribe\", \"operation-failed\", cause);\n }\n }\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => current,\n getServerSnapshot: () => configuredDefault,\n setPreferences(value) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n const next = normalizePreferences(value);\n const changed = replace(next);\n if (!disposed && persistence?.storage && samePreferences(current, next)) {\n const serialized = JSON.stringify(next);\n if (!changed) {\n const epoch = eventEpoch;\n let matchesStoredValue = false;\n try {\n matchesStoredValue =\n persistence.storage.getItem(persistence.key) === serialized;\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n if (\n matchesStoredValue ||\n disposed ||\n epoch !== eventEpoch ||\n !samePreferences(current, next)\n ) {\n return;\n }\n }\n if (disposed || !samePreferences(current, next)) return;\n try {\n persistence.storage.setItem(persistence.key, serialized);\n } catch (cause) {\n report(\"storage-write\", \"operation-failed\", cause);\n }\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n eventEpoch += 1;\n listeners.clear();\n const unsubscribe = unsubscribeEvents;\n unsubscribeEvents = undefined;\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (cause) {\n report(\"event-unsubscribe\", \"operation-failed\", cause);\n }\n }\n },\n };\n}\n\ninterface ResolvedPreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nfunction resolvePersistence(\n persistence: PreferencePersistence | undefined,\n): ResolvedPreferencePersistence | undefined {\n if (!persistence) return undefined;\n if (persistence.storage) return persistence;\n const browser = getBrowserPersistence();\n return {\n key: persistence.key,\n ...(browser?.storage ? { storage: browser.storage } : {}),\n ...(persistence.events\n ? { events: persistence.events }\n : browser?.events\n ? { events: browser.events }\n : {}),\n };\n}\n\nfunction getBrowserPersistence():\n | { storage: PreferenceStorage; events: PreferenceStorageEventSource }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n const browserWindow = window;\n const storage = browserWindow.localStorage;\n if (!storage) return undefined;\n return {\n storage,\n events: {\n subscribe(listener) {\n const handle = (event: StorageEvent): void => listener(event);\n browserWindow.addEventListener(\"storage\", handle);\n return () => browserWindow.removeEventListener(\"storage\", handle);\n },\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction parsePreferences(\n raw: string,\n source: \"storage-read\" | \"storage-event\",\n report: (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ) => void,\n): PreferenceSchemaV1 | undefined {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (cause) {\n report(source, \"invalid-json\", cause);\n return undefined;\n }\n try {\n return normalizePreferences(value as PreferenceSchemaV1);\n } catch (cause) {\n report(\n source,\n cause instanceof UnsupportedPreferenceVersionError\n ? \"unsupported-version\"\n : \"invalid-preference\",\n cause,\n );\n return undefined;\n }\n}\n\nclass UnsupportedPreferenceVersionError extends TypeError {}\n\nexport function normalizePreferences(\n value: PreferenceSchemaV1,\n): PreferenceSchemaV1 {\n const fields = snapshotPreferenceFields(value);\n if (fields.version !== 1)\n throw new UnsupportedPreferenceVersionError(\n \"Unsupported preference version\",\n );\n if (fields.preset === \"completion-only\") {\n if (!hasExactKeys(fields, [\"version\", \"preset\"]))\n throw new TypeError(\"Invalid completion-only preferences\");\n return Object.freeze({ version: 1, preset: \"completion-only\" });\n }\n if (\n !([\"minimal\", \"balanced\", \"verbose\"] as unknown[]).includes(fields.preset)\n )\n throw new TypeError(\"Invalid preference preset\");\n if (!hasExactKeys(fields, [\"version\", \"preset\", \"streaming\", \"tools\"]))\n throw new TypeError(\"Invalid preference fields\");\n if (!STREAMING_VALUES.includes(fields.streaming as StreamingVerbosity))\n throw new TypeError(\"Invalid streaming preference\");\n if (!TOOL_VALUES.includes(fields.tools as ToolVerbosity))\n throw new TypeError(\"Invalid tool preference\");\n return Object.freeze({\n version: 1,\n preset: fields.preset as \"minimal\" | \"balanced\" | \"verbose\",\n streaming: fields.streaming as StreamingVerbosity,\n tools: fields.tools as ToolVerbosity,\n });\n}\n\nconst STREAMING_VALUES: readonly StreamingVerbosity[] = [\n \"preset\",\n \"off\",\n \"completion\",\n \"paragraph\",\n \"sentence\",\n];\nconst TOOL_VALUES: readonly ToolVerbosity[] = [\n \"preset\",\n \"off\",\n \"failures\",\n \"status\",\n \"progress\",\n];\n\nfunction snapshotPreferenceFields(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(\"Invalid preferences\");\n }\n try {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const fields = Object.create(null) as Record<string, unknown>;\n for (const key of Reflect.ownKeys(descriptors)) {\n if (typeof key !== \"string\")\n throw new TypeError(\"Invalid preference fields\");\n const descriptor = descriptors[key];\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\n \"Preference fields must be enumerable data properties\",\n );\n }\n fields[key] = descriptor.value;\n }\n return fields;\n } catch {\n throw new TypeError(\"Invalid preferences\");\n }\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value);\n return (\n keys.length === expected.length &&\n expected.every((key) => keys.includes(key))\n );\n}\n\nexport function samePreferences(\n left: PreferenceSchemaV1,\n right: PreferenceSchemaV1,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction mapStreaming(\n value: StreamingVerbosity,\n): PolicyOverrides[\"text\"] | undefined {\n if (value === \"preset\") return undefined;\n if (value === \"off\") return { strategy: \"silent\" };\n if (value === \"completion\")\n return { strategy: \"completion\", minimumCharacters: 0, maximumDelayMs: 0 };\n return { strategy: value };\n}\n\nfunction mapTools(value: ToolVerbosity): PolicyOverrides[\"tools\"] | undefined {\n if (value === \"preset\") return undefined;\n return {\n announceStart: value === \"status\" || value === \"progress\",\n announceProgress: value === \"progress\",\n announceCompletion: value === \"status\" || value === \"progress\",\n announceFailure: value !== \"off\",\n };\n}\n\nfunction serializeError(cause: unknown): Readonly<{\n name: string;\n message: string;\n}> {\n const fallback = { name: \"Error\", message: \"Unknown error\" } as const;\n try {\n if (cause instanceof Error) {\n const name = cause.name;\n const message = cause.message;\n if (typeof name !== \"string\" || typeof message !== \"string\") {\n return fallback;\n }\n return { name: name || \"Error\", message };\n }\n if (\n typeof cause === \"string\" ||\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\" ||\n typeof cause === \"symbol\"\n ) {\n return { name: \"Error\", message: String(cause) };\n }\n } catch {\n return fallback;\n }\n return fallback;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,SAAS,kBAAkBA,WAAoC;AACpE,MAAI,SAASA,UAAS;AACtB,QAAM,UAAU,oBAAI,IAAa;AACjC,SAAO,QAAQ;AACb,QAAI,QAAQ,IAAI,MAAM,EAAG,OAAM,IAAI,MAAM,uBAAuB;AAChE,YAAQ,IAAI,MAAM;AAClB,UAAM,SAAU,OACb;AACH,UAAM,SAAS,QAAQ;AACvB,QAAI,CAAC,OAAQ,QAAO;AACpB,aAAS;AAAA,EACX;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,UAAmB,QAA0B;AAC5E,MAAI,UAA0B;AAC9B,QAAM,UAAU,oBAAI,IAAa;AACjC,SAAO,SAAS;AACd,QAAI,YAAY,SAAU,QAAO;AACjC,QAAI,QAAQ,IAAI,OAAO,EAAG,OAAM,IAAI,MAAM,sBAAsB;AAChE,YAAQ,IAAI,OAAO;AACnB,cAAU,eAAe,OAAO;AAAA,EAClC;AACA,SAAO;AACT;AAEO,SAAS,eAAe,SAAkC;AAC/D,QAAM,eACJ,QACA;AACF,MAAI,aAAc,QAAO;AACzB,MAAI,QAAQ,cAAe,QAAO,QAAQ;AAC1C,QAAM,OAAO,QAAQ,YAAY;AACjC,MAAI,QA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,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AACR,UAAI,SAAU;AACd,iBAAW;AACX,UAAI;AACF,oBAAY;AAAA,MACd,UAAE;AACA,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;","names":["document","document","window","document","serializeError"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/attention-binding.ts","../src/composed-tree.ts","../src/attention.ts","../src/focus.ts","../src/preferences.ts"],"sourcesContent":["export {\n bindAttention,\n type AttentionBinding,\n type AttentionBindingOptions,\n} from \"./attention-binding.js\";\n\nimport type { AnnouncementIntent, Runtime } from \"@generative-a11y/core\";\n\nexport {\n createAttentionStore,\n type AttentionIntersectionObserver,\n type AttentionIntersectionObserverFactory,\n type AttentionSnapshot,\n type AttentionStore,\n type AttentionStoreOptions,\n type ExternalStore,\n} from \"./attention.js\";\n\nexport {\n captureFocus,\n focusElement,\n restoreFocus,\n type FocusCapture,\n type FocusElementOptions,\n type FocusResult,\n type FocusSkippedReason,\n type RestoreFocusOptions,\n} from \"./focus.js\";\n\nexport {\n createPreferenceStore,\n defaultPreferences,\n normalizePreferences,\n preferencesToCoreConfiguration,\n type CorePreferenceConfiguration,\n type PreferenceDiagnostic,\n type PreferenceDiagnosticCode,\n type PreferenceDiagnosticSource,\n type PreferencePersistence,\n type PreferenceSchemaV1,\n type PreferenceStorage,\n type PreferenceStorageEvent,\n type PreferenceStorageEventSource,\n type PreferenceStore,\n type PreferenceStoreOptions,\n samePreferences,\n type StreamingVerbosity,\n type ToolVerbosity,\n} from \"./preferences.js\";\n\nexport type DeliveryMode = \"auto\" | \"live-region\";\n\nexport interface LiveRegions {\n polite: HTMLElement;\n assertive: HTMLElement;\n}\n\nexport interface DeliveryResult {\n status: \"notified\" | \"mutated\" | \"unavailable\" | \"disposed\";\n method: \"aria-notify\" | \"live-region\" | \"none\";\n channel: AnnouncementIntent[\"channel\"];\n announcementId: string;\n sourceType: AnnouncementIntent[\"sourceType\"];\n at: number;\n sourceEventId?: string;\n responseId?: string;\n toolId?: string;\n interactionId?: string;\n /** Stable logical run identity associated with the delivered intent. */\n runId?: string;\n /** Stable run attempt identity associated with the delivered intent. */\n runInstanceId?: string;\n /** Stable logical step identity associated with the delivered intent. */\n stepId?: string;\n /** Stable step attempt identity associated with the delivered intent. */\n stepInstanceId?: string;\n error?: { name: string; message: string };\n}\n\nexport interface AnnouncerOptions {\n document?: Document;\n mode?: DeliveryMode;\n regions?: LiveRegions;\n onDelivery?: (result: DeliveryResult) => void;\n}\n\nexport interface Announcer {\n announce(intent: AnnouncementIntent): DeliveryResult;\n getRegions(): LiveRegions | undefined;\n dispose(): void;\n}\n\nexport interface RuntimeBinding {\n announcer: Announcer;\n dispose(): void;\n}\n\nexport function createAnnouncer(options: AnnouncerOptions = {}): Announcer {\n if (\n options.mode !== undefined &&\n options.mode !== \"auto\" &&\n options.mode !== \"live-region\"\n )\n throw new TypeError('mode must be \"auto\" or \"live-region\"');\n validateSuppliedRegions(options);\n const selectedDocument =\n options.document ??\n options.regions?.polite.ownerDocument ??\n (typeof document === \"undefined\" ? undefined : document);\n const ownsRegions = options.regions === undefined;\n const regions = options.regions ?? createLiveRegions(selectedDocument);\n\n if (regions) {\n configureRegion(regions.polite, \"polite\");\n configureRegion(regions.assertive, \"assertive\");\n }\n let notifierEnabled = true;\n let disposed = false;\n\n const report = (result: DeliveryResult): DeliveryResult => {\n try {\n options.onDelivery?.(result);\n } catch {\n // Diagnostics are observational and cannot affect delivery.\n }\n return result;\n };\n\n return {\n announce(intent) {\n if (disposed) {\n return report({\n status: \"disposed\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n if (regions) {\n const region = regions[intent.channel];\n applyLocale(region, intent.locale);\n let error: DeliveryResult[\"error\"];\n if (notifierEnabled && options.mode !== \"live-region\") {\n let notified = false;\n try {\n const ariaNotify = (region as AriaNotifyRegion).ariaNotify;\n if (typeof ariaNotify === \"function\") {\n ariaNotify.call(region, intent.text, {\n priority: intent.channel === \"assertive\" ? \"high\" : \"normal\",\n });\n notified = true;\n }\n } catch (cause) {\n notifierEnabled = false;\n error = serializeError(cause);\n }\n if (notified) {\n return report({\n status: \"notified\",\n method: \"aria-notify\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n }\n region.textContent = intent.text;\n return report({\n status: \"mutated\",\n method: \"live-region\",\n channel: intent.channel,\n ...deliveryContext(intent),\n ...(error === undefined ? {} : { error }),\n });\n }\n return report({\n status: \"unavailable\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n },\n getRegions() {\n return regions;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n if (ownsRegions) {\n regions?.polite.remove();\n regions?.assertive.remove();\n }\n },\n };\n}\n\nfunction deliveryContext(\n intent: AnnouncementIntent,\n): Pick<\n DeliveryResult,\n | \"announcementId\"\n | \"sourceType\"\n | \"at\"\n | \"sourceEventId\"\n | \"responseId\"\n | \"toolId\"\n | \"interactionId\"\n | \"runId\"\n | \"runInstanceId\"\n | \"stepId\"\n | \"stepInstanceId\"\n> {\n return {\n announcementId: intent.id,\n sourceType: intent.sourceType,\n at: intent.at,\n ...(intent.sourceEventId !== undefined\n ? { sourceEventId: intent.sourceEventId }\n : {}),\n ...(intent.responseId !== undefined\n ? { responseId: intent.responseId }\n : {}),\n ...(intent.toolId !== undefined ? { toolId: intent.toolId } : {}),\n ...(intent.interactionId !== undefined\n ? { interactionId: intent.interactionId }\n : {}),\n ...(intent.runId !== undefined ? { runId: intent.runId } : {}),\n ...(intent.runInstanceId !== undefined\n ? { runInstanceId: intent.runInstanceId }\n : {}),\n ...(intent.stepId !== undefined ? { stepId: intent.stepId } : {}),\n ...(intent.stepInstanceId !== undefined\n ? { stepInstanceId: intent.stepInstanceId }\n : {}),\n };\n}\n\nfunction validateSuppliedRegions(options: AnnouncerOptions): void {\n if (options.regions === undefined) return;\n const { polite, assertive } = options.regions;\n if (polite === assertive) {\n throw new TypeError(\n \"Polite and assertive regions must be distinct elements\",\n );\n }\n if (!polite.isConnected || !assertive.isConnected) {\n throw new TypeError(\"Supplied regions must be connected\");\n }\n if (polite.contains(assertive) || assertive.contains(polite)) {\n throw new TypeError(\n \"Polite and assertive regions must not contain one another\",\n );\n }\n if (polite.ownerDocument !== assertive.ownerDocument) {\n throw new TypeError(\n \"Polite and assertive regions must belong to the same document\",\n );\n }\n if (\n options.document !== undefined &&\n (polite.ownerDocument !== options.document ||\n assertive.ownerDocument !== options.document)\n ) {\n throw new TypeError(\n \"Supplied regions must belong to the provided document\",\n );\n }\n}\n\nfunction serializeError(error: unknown): NonNullable<DeliveryResult[\"error\"]> {\n try {\n if (error instanceof Error) {\n return {\n name: readErrorString(error, \"name\", \"Error\"),\n message: readErrorString(error, \"message\", \"Unknown error\"),\n };\n }\n } catch {\n // Hostile proxies can throw during instanceof checks.\n }\n return { name: \"Error\", message: safeString(error, \"Unknown error\") };\n}\n\nfunction readErrorString(\n error: Error,\n property: \"name\" | \"message\",\n fallback: string,\n): string {\n try {\n return safeString(error[property], fallback);\n } catch {\n return fallback;\n }\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\ninterface AriaNotifyRegion extends HTMLElement {\n ariaNotify?: (\n text: string,\n options?: { priority: \"normal\" | \"high\" },\n ) => void;\n}\n\nfunction createLiveRegions(\n selectedDocument: Document | undefined,\n): LiveRegions | undefined {\n const parent = selectedDocument?.body ?? selectedDocument?.documentElement;\n if (!selectedDocument || !parent) return undefined;\n\n const regions = {\n polite: selectedDocument.createElement(\"div\"),\n assertive: selectedDocument.createElement(\"div\"),\n };\n parent.append(regions.polite, regions.assertive);\n return regions;\n}\n\nfunction configureRegion(\n region: HTMLElement,\n channel: AnnouncementIntent[\"channel\"],\n): void {\n region.removeAttribute(\"role\");\n region.removeAttribute(\"aria-busy\");\n region.removeAttribute(\"hidden\");\n region.removeAttribute(\"aria-hidden\");\n region.inert = false;\n region.removeAttribute(\"inert\");\n region.style.removeProperty(\"display\");\n region.style.removeProperty(\"visibility\");\n region.style.removeProperty(\"content-visibility\");\n region.setAttribute(\"aria-live\", channel);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(\"aria-relevant\", \"additions text\");\n Object.assign(region.style, {\n position: \"absolute\",\n width: \"1px\",\n height: \"1px\",\n padding: \"0\",\n margin: \"-1px\",\n overflow: \"hidden\",\n clip: \"rect(0, 0, 0, 0)\",\n whiteSpace: \"nowrap\",\n border: \"0\",\n });\n}\n\nfunction applyLocale(region: HTMLElement, locale: string | undefined): void {\n if (locale === undefined) region.removeAttribute(\"lang\");\n else region.setAttribute(\"lang\", locale);\n}\n\nexport function bindRuntime(\n runtime: Runtime,\n options: AnnouncerOptions = {},\n): RuntimeBinding {\n const announcer = createAnnouncer(options);\n let disposed = false;\n let unsubscribe: () => void;\n try {\n unsubscribe = runtime.subscribeAnnouncements((intent) => {\n if (!disposed) announcer.announce(intent);\n });\n } catch (cause) {\n announcer.dispose();\n throw cause;\n }\n\n return {\n announcer,\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n unsubscribe();\n } finally {\n announcer.dispose();\n }\n },\n };\n}\n","import type { Runtime } from \"@generative-a11y/core\";\nimport type { AttentionSnapshot, AttentionStore } from \"./attention.js\";\n\nexport interface AttentionBindingOptions {\n readonly runtime: Runtime;\n readonly attentionStore: AttentionStore;\n}\n\nexport interface AttentionBinding {\n dispose(): void;\n}\n\nconst boundRuntimes = new WeakSet<Runtime>();\n\n/** Borrow a store and runtime, forwarding observations without changing overrides. */\nexport function bindAttention({\n runtime,\n attentionStore,\n}: AttentionBindingOptions): AttentionBinding {\n if (boundRuntimes.has(runtime)) {\n throw new Error(\"Runtime already has an attention binding\");\n }\n // Claim before invoking any external code, including store accessors.\n boundRuntimes.add(runtime);\n let active = true;\n let unsubscribe: (() => void) | undefined;\n let lastMode: AttentionSnapshot[\"mode\"] | undefined;\n let revision = 0;\n const update = () => {\n if (!active) return;\n const readRevision = ++revision;\n const mode = attentionStore.getSnapshot().mode;\n if (!active || revision !== readRevision || mode === lastMode) return;\n lastMode = mode;\n runtime.dispatch({ type: \"attention.changed\", mode });\n };\n const dispose = () => {\n if (!active) return;\n active = false;\n try {\n try {\n unsubscribe?.();\n } catch {\n // A throwing borrowed store cannot prevent observation reset.\n }\n if (lastMode !== undefined) {\n runtime.dispatch({ type: \"attention.changed\", mode: \"unknown\" });\n }\n } finally {\n boundRuntimes.delete(runtime);\n }\n };\n try {\n unsubscribe = attentionStore.subscribe(update);\n update();\n } catch (error) {\n try {\n dispose();\n } catch {\n // Preserve the original construction error.\n }\n throw error;\n }\n return { dispose };\n}\n","export function deepActiveElement(document: Document): Element | null {\n let active = document.activeElement;\n const visited = new Set<Element>();\n while (active) {\n if (visited.has(active)) throw new Error(\"Cyclic active element\");\n visited.add(active);\n const shadow = (active as Element & { shadowRoot?: ShadowRoot | null })\n .shadowRoot;\n const nested = shadow?.activeElement;\n if (!nested) return active;\n active = nested;\n }\n return null;\n}\n\nexport function composedContains(ancestor: Element, target: Element): boolean {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (current === ancestor) return true;\n if (visited.has(current)) throw new Error(\"Cyclic composed tree\");\n visited.add(current);\n current = composedParent(current);\n }\n return false;\n}\n\nexport function composedParent(element: Element): Element | null {\n const assignedSlot = (\n element as Element & { assignedSlot?: HTMLSlotElement | null }\n ).assignedSlot;\n if (assignedSlot) return assignedSlot;\n if (element.parentElement) return element.parentElement;\n const root = element.getRootNode();\n if (root && \"host\" in root) {\n const host = (root as ShadowRoot).host;\n if (host.ownerDocument === element.ownerDocument) return host;\n }\n return null;\n}\n","import { composedContains, deepActiveElement } from \"./composed-tree.js\";\n\nexport interface ExternalStore<T> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): T;\n getServerSnapshot(): T;\n}\n\nexport interface AttentionSnapshot {\n readonly visibility: \"visible\" | \"hidden\" | \"unknown\";\n readonly windowFocus: \"focused\" | \"blurred\" | \"unknown\";\n readonly focusArea:\n \"composer\" | \"conversation\" | \"elsewhere\" | \"none\" | \"unknown\";\n readonly newestResponse: \"visible\" | \"outside\" | \"unobserved\" | \"unknown\";\n readonly mode:\n \"foreground\" | \"background\" | \"reading-history\" | \"away\" | \"unknown\";\n}\n\nexport interface AttentionStore extends ExternalStore<AttentionSnapshot> {\n registerComposer(element: Element): () => void;\n registerConversation(element: Element): () => void;\n registerNewestResponse(element: Element): () => void;\n dispose(): void;\n}\n\nexport interface AttentionStoreOptions {\n document?: Document;\n createIntersectionObserver?: AttentionIntersectionObserverFactory;\n intersectionObserverInit?: IntersectionObserverInit;\n}\n\nexport interface AttentionIntersectionObserver {\n observe(target: Element): void;\n unobserve(target: Element): void;\n disconnect(): void;\n}\n\nexport type AttentionIntersectionObserverFactory = (\n callback: IntersectionObserverCallback,\n options?: IntersectionObserverInit,\n) => AttentionIntersectionObserver;\n\nconst UNKNOWN_SNAPSHOT: AttentionSnapshot = Object.freeze({\n visibility: \"unknown\",\n windowFocus: \"unknown\",\n focusArea: \"unknown\",\n newestResponse: \"unknown\",\n mode: \"unknown\",\n});\n\nexport function createAttentionStore(\n options: AttentionStoreOptions = {},\n): AttentionStore {\n const selectedDocument =\n options.document ??\n (typeof document === \"undefined\" ? undefined : document);\n if (!selectedDocument) {\n return {\n subscribe: () => () => undefined,\n getSnapshot: () => UNKNOWN_SNAPSHOT,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: () => () => undefined,\n registerConversation: () => () => undefined,\n registerNewestResponse: () => () => undefined,\n dispose: () => undefined,\n };\n }\n\n const listeners = new Set<() => void>();\n const composers = new Map<Element, number>();\n const conversations = new Map<Element, number>();\n const selectedWindow = selectedDocument.defaultView;\n let disposed = false;\n let newestTarget: Element | undefined;\n let newestResult: AttentionSnapshot[\"newestResponse\"] = \"unobserved\";\n let newestRegistration = 0;\n let observer: AttentionIntersectionObserver | undefined;\n let snapshot = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n const update = () => {\n if (disposed) return;\n const next = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n if (sameSnapshot(snapshot, next)) return;\n snapshot = next;\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store observers cannot prevent other observers from running.\n }\n }\n };\n const handleFocusOut = (event: FocusEvent) => {\n if (event.relatedTarget === null) update();\n };\n const listenerCleanups: Array<() => void> = [];\n const installListener = (install: () => void, cleanup: () => void): void => {\n // Register cleanup first because a hostile EventTarget can install and then\n // throw from addEventListener(). Removing a listener that was not installed\n // is harmless, while omitting cleanup would leak the accepted listener.\n listenerCleanups.push(cleanup);\n install();\n };\n const cleanupListeners = (): void => {\n for (const cleanup of listenerCleanups.splice(0).reverse()) {\n try {\n cleanup();\n } catch {\n // One hostile removal cannot strand the remaining listeners.\n }\n }\n };\n try {\n installListener(\n () => selectedDocument.addEventListener(\"visibilitychange\", update),\n () => selectedDocument.removeEventListener(\"visibilitychange\", update),\n );\n if (selectedWindow) {\n installListener(\n () => selectedWindow.addEventListener(\"focus\", update),\n () => selectedWindow.removeEventListener(\"focus\", update),\n );\n installListener(\n () => selectedWindow.addEventListener(\"blur\", update),\n () => selectedWindow.removeEventListener(\"blur\", update),\n );\n }\n installListener(\n () => selectedDocument.addEventListener(\"focusin\", update),\n () => selectedDocument.removeEventListener(\"focusin\", update),\n );\n installListener(\n () => selectedDocument.addEventListener(\"focusout\", handleFocusOut),\n () => selectedDocument.removeEventListener(\"focusout\", handleFocusOut),\n );\n } catch (error) {\n cleanupListeners();\n throw error;\n }\n\n const register = (\n elements: Map<Element, number>,\n element: Element,\n ): (() => void) => {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n elements.set(element, (elements.get(element) ?? 0) + 1);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n const remaining = (elements.get(element) ?? 1) - 1;\n if (remaining === 0) elements.delete(element);\n else elements.set(element, remaining);\n update();\n };\n };\n\n const createChatObserver = (\n registration: number,\n target: Element,\n ): AttentionIntersectionObserver | undefined => {\n const factory =\n options.createIntersectionObserver ??\n defaultIntersectionObserverFactory(selectedWindow);\n if (!factory) return undefined;\n let created: AttentionIntersectionObserver | undefined;\n try {\n created = factory((entries) => {\n if (\n disposed ||\n registration !== newestRegistration ||\n newestTarget !== target ||\n observer !== created\n ) {\n return;\n }\n let latest: IntersectionObserverEntry | undefined;\n for (const entry of entries) {\n if (entry.target === target) latest = entry;\n }\n if (!latest) return;\n newestResult = latest.isIntersecting ? \"visible\" : \"outside\";\n update();\n }, options.intersectionObserverInit);\n created.observe(target);\n return created;\n } catch {\n cleanupObserver(created, target);\n return undefined;\n }\n };\n\n const stopObserver = (target?: Element): void => {\n const current = observer;\n observer = undefined;\n cleanupObserver(current, target);\n };\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: (element) => register(composers, element),\n registerConversation: (element) => register(conversations, element),\n registerNewestResponse(element) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n const registration = ++newestRegistration;\n stopObserver(newestTarget);\n newestTarget = element;\n newestResult = \"unknown\";\n observer = createChatObserver(registration, element);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n if (registration !== newestRegistration || newestTarget !== element)\n return;\n stopObserver(element);\n newestTarget = undefined;\n newestResult = \"unobserved\";\n update();\n };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n listeners.clear();\n composers.clear();\n conversations.clear();\n stopObserver(newestTarget);\n newestTarget = undefined;\n cleanupListeners();\n },\n };\n}\n\nfunction makeSnapshot(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot {\n const visibility = readVisibility(document);\n const windowFocus = readWindowFocus(document);\n return Object.freeze({\n visibility,\n windowFocus,\n focusArea: readFocusArea(document, composers, conversations),\n newestResponse,\n mode: deriveMode(visibility, windowFocus, newestResponse),\n });\n}\n\nfunction deriveMode(\n visibility: AttentionSnapshot[\"visibility\"],\n windowFocus: AttentionSnapshot[\"windowFocus\"],\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot[\"mode\"] {\n if (visibility === \"hidden\") return \"background\";\n if (visibility !== \"visible\") return \"unknown\";\n if (windowFocus === \"blurred\") return \"away\";\n if (windowFocus !== \"focused\") return \"unknown\";\n if (newestResponse === \"outside\") return \"reading-history\";\n if (newestResponse === \"visible\") return \"foreground\";\n return \"unknown\";\n}\n\nfunction defaultIntersectionObserverFactory(\n window: (Window & typeof globalThis) | null,\n): AttentionIntersectionObserverFactory | undefined {\n const Constructor = window?.IntersectionObserver;\n if (typeof Constructor !== \"function\") return undefined;\n return (callback, options) => new Constructor(callback, options);\n}\n\nfunction cleanupObserver(\n observer: AttentionIntersectionObserver | undefined,\n target?: Element,\n): void {\n if (!observer) return;\n if (target) {\n try {\n observer.unobserve(target);\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n }\n try {\n observer.disconnect();\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n}\n\nfunction readFocusArea(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n): AttentionSnapshot[\"focusArea\"] {\n let activeElement: Element | null;\n try {\n activeElement = deepActiveElement(document);\n } catch {\n return \"unknown\";\n }\n if (\n activeElement === null ||\n activeElement === document.body ||\n activeElement === document.documentElement\n ) {\n return \"none\";\n }\n if (\n [...composers.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"composer\";\n }\n if (\n [...conversations.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"conversation\";\n }\n return \"elsewhere\";\n}\n\nfunction readVisibility(document: Document): AttentionSnapshot[\"visibility\"] {\n try {\n if (document.visibilityState === \"visible\") return \"visible\";\n if (document.visibilityState === \"hidden\") return \"hidden\";\n } catch {\n // Browser integrations can expose throwing accessors.\n }\n return \"unknown\";\n}\n\nfunction readWindowFocus(document: Document): AttentionSnapshot[\"windowFocus\"] {\n try {\n if (typeof document.hasFocus !== \"function\") return \"unknown\";\n return document.hasFocus() ? \"focused\" : \"blurred\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction sameSnapshot(\n left: AttentionSnapshot,\n right: AttentionSnapshot,\n): boolean {\n return (\n left.visibility === right.visibility &&\n left.windowFocus === right.windowFocus &&\n left.focusArea === right.focusArea &&\n left.newestResponse === right.newestResponse &&\n left.mode === right.mode\n );\n}\n","import {\n composedContains,\n composedParent,\n deepActiveElement,\n} from \"./composed-tree.js\";\n\nexport interface FocusCapture {\n readonly document: Document | null;\n readonly target: Element | null;\n}\n\nexport interface FocusElementOptions {\n preventScroll?: boolean;\n}\n\nexport interface RestoreFocusOptions extends FocusElementOptions {\n onlyIfFocusWithin?: Element;\n}\n\nexport type FocusSkippedReason =\n | \"unavailable\"\n | \"cross-document\"\n | \"disconnected\"\n | \"disabled\"\n | \"hidden\"\n | \"aria-hidden\"\n | \"inert\"\n | \"missing-focus\"\n | \"guard-mismatch\"\n | \"focus-error\"\n | \"focus-not-applied\";\n\nexport type FocusResult =\n | { readonly status: \"focused\"; readonly target: Element }\n | {\n readonly status: \"skipped\";\n readonly reason: FocusSkippedReason;\n readonly target: Element | null;\n };\n\nexport function captureFocus(selectedDocument?: Document): FocusCapture {\n const document =\n selectedDocument ??\n (typeof globalThis.document === \"undefined\"\n ? undefined\n : globalThis.document);\n if (!document) return Object.freeze({ document: null, target: null });\n let target: Element | null = null;\n try {\n const active = deepActiveElement(document);\n if (\n active !== null &&\n active !== document.body &&\n active !== document.documentElement &&\n active.ownerDocument === document\n ) {\n target = active;\n }\n } catch {\n // A hostile document is captured without a restorable target.\n }\n return Object.freeze({ document, target });\n}\n\nexport function focusElement(\n target: Element,\n options: FocusElementOptions = {},\n): FocusResult {\n const eligibility = focusEligibility(target);\n if (eligibility) {\n return { status: \"skipped\", reason: eligibility, target };\n }\n let focus: ((options?: FocusOptions) => void) | undefined;\n let document: Document;\n let previous: Element | null;\n try {\n document = target.ownerDocument;\n previous = deepActiveElement(document);\n focus = (target as Element & { focus?: (options?: FocusOptions) => void })\n .focus;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target };\n }\n if (typeof focus !== \"function\") {\n return { status: \"skipped\", reason: \"missing-focus\", target };\n }\n let focusThrew = false;\n try {\n focus.call(target, { preventScroll: options.preventScroll ?? true });\n } catch {\n focusThrew = true;\n }\n if (focusThrew) {\n restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n const postFocusEligibility = focusEligibility(target);\n let active: Element | null;\n try {\n active = deepActiveElement(document);\n } catch {\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n if (postFocusEligibility) {\n if (active === target) restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: postFocusEligibility, target };\n }\n if (active !== target) {\n return { status: \"skipped\", reason: \"focus-not-applied\", target };\n }\n return { status: \"focused\", target };\n}\n\nexport function restoreFocus(\n capture: FocusCapture,\n options: RestoreFocusOptions = {},\n): FocusResult {\n let document: Document | null;\n let target: Element | null;\n try {\n document = capture.document;\n target = capture.target;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n if (!document || !target) {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n try {\n if (target.ownerDocument !== document) {\n return { status: \"skipped\", reason: \"cross-document\", target };\n }\n const guard = options.onlyIfFocusWithin;\n if (guard !== undefined) {\n const active = deepActiveElement(document);\n if (\n guard.ownerDocument !== document ||\n active === null ||\n !composedContains(guard, active)\n ) {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n }\n } catch {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n return focusElement(target, options);\n}\n\nfunction focusEligibility(target: Element): FocusSkippedReason | undefined {\n let ownerDocument: Document;\n try {\n ownerDocument = target.ownerDocument;\n const ElementConstructor = ownerDocument.defaultView?.Element;\n if (\n !ownerDocument ||\n (ElementConstructor && !(target instanceof ElementConstructor))\n ) {\n return \"unavailable\";\n }\n if (target.isConnected !== true) return \"disconnected\";\n if (\n target.getAttribute(\"disabled\") !== null ||\n (target as Element & { disabled?: unknown }).disabled === true\n ) {\n return \"disabled\";\n }\n } catch {\n return \"unavailable\";\n }\n try {\n const matches = target.matches;\n if (typeof matches === \"function\" && matches.call(target, \":disabled\")) {\n return \"disabled\";\n }\n } catch {\n // Fall back to the direct disabled checks above.\n }\n\n try {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (visited.has(current)) return \"unavailable\";\n visited.add(current);\n if (current.hasAttribute(\"hidden\")) return \"hidden\";\n if (current.getAttribute(\"aria-hidden\")?.trim().toLowerCase() === \"true\")\n return \"aria-hidden\";\n if (\n current.hasAttribute(\"inert\") ||\n (current as Element & { inert?: unknown }).inert === true\n ) {\n return \"inert\";\n }\n current = composedParent(current);\n }\n } catch {\n return \"unavailable\";\n }\n\n try {\n const focus = (\n target as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus !== \"function\") return \"missing-focus\";\n } catch {\n return \"unavailable\";\n }\n return undefined;\n}\n\nfunction restorePreviousFocus(\n previous: Element | null,\n attempted: Element,\n document: Document,\n): void {\n try {\n if (\n !previous ||\n deepActiveElement(document) !== attempted ||\n focusEligibility(previous) !== undefined\n ) {\n return;\n }\n const focus = (\n previous as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus === \"function\")\n focus.call(previous, { preventScroll: true });\n } catch {\n // Focus rollback is best-effort at hostile DOM boundaries.\n }\n}\n","import type { PolicyOverrides, PresetName } from \"@generative-a11y/core\";\n\nimport type { ExternalStore } from \"./attention.js\";\n\nexport type StreamingVerbosity =\n \"preset\" | \"off\" | \"completion\" | \"paragraph\" | \"sentence\";\n\nexport type ToolVerbosity =\n \"preset\" | \"off\" | \"failures\" | \"status\" | \"progress\";\n\nexport type PreferenceSchemaV1 =\n | Readonly<{ version: 1; preset: \"completion-only\" }>\n | Readonly<{\n version: 1;\n preset: \"minimal\" | \"balanced\" | \"verbose\";\n streaming: StreamingVerbosity;\n tools: ToolVerbosity;\n }>;\n\nexport interface PreferenceStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nexport interface PreferenceStorageEvent {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly storageArea?: PreferenceStorage | null;\n}\n\nexport interface PreferenceStorageEventSource {\n subscribe(listener: (event: PreferenceStorageEvent) => void): () => void;\n}\n\nexport type PreferenceDiagnosticSource =\n | \"storage-read\"\n | \"storage-write\"\n | \"storage-event\"\n | \"event-subscribe\"\n | \"event-unsubscribe\";\n\nexport type PreferenceDiagnosticCode =\n | \"operation-failed\"\n | \"invalid-json\"\n | \"invalid-preference\"\n | \"unsupported-version\";\n\nexport interface PreferenceDiagnostic {\n readonly source: PreferenceDiagnosticSource;\n readonly code: PreferenceDiagnosticCode;\n readonly error?: Readonly<{ name: string; message: string }>;\n}\n\nexport interface PreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nexport interface PreferenceStoreOptions {\n readonly defaultValue?: PreferenceSchemaV1;\n readonly persistence?: PreferencePersistence;\n readonly onDiagnostic?: (diagnostic: PreferenceDiagnostic) => void;\n}\n\nexport interface PreferenceStore extends ExternalStore<PreferenceSchemaV1> {\n setPreferences(value: PreferenceSchemaV1): void;\n dispose(): void;\n}\n\nexport interface CorePreferenceConfiguration {\n readonly preset: PresetName;\n readonly policy?: PolicyOverrides;\n}\n\nexport const defaultPreferences: PreferenceSchemaV1 = Object.freeze({\n version: 1,\n preset: \"balanced\",\n streaming: \"preset\",\n tools: \"preset\",\n});\n\nexport function preferencesToCoreConfiguration(\n value: PreferenceSchemaV1,\n): CorePreferenceConfiguration {\n const preferences = normalizePreferences(value);\n if (preferences.preset === \"completion-only\") {\n return { preset: \"completion-only\" };\n }\n const policy: PolicyOverrides = {};\n const text = mapStreaming(preferences.streaming);\n const tools = mapTools(preferences.tools);\n if (text) policy.text = text;\n if (tools) policy.tools = tools;\n return Object.keys(policy).length === 0\n ? { preset: preferences.preset }\n : { preset: preferences.preset, policy };\n}\n\nexport function createPreferenceStore(\n options: PreferenceStoreOptions = {},\n): PreferenceStore {\n const configuredDefault = options.defaultValue\n ? normalizePreferences(options.defaultValue)\n : defaultPreferences;\n const persistence = resolvePersistence(options.persistence);\n const report = (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ): void => {\n const diagnostic: PreferenceDiagnostic = {\n source,\n code,\n ...(cause === undefined ? {} : { error: serializeError(cause) }),\n };\n try {\n options.onDiagnostic?.(diagnostic);\n } catch {\n // Diagnostics are observational.\n }\n };\n let current = configuredDefault;\n if (persistence?.storage) {\n try {\n const stored = persistence.storage.getItem(persistence.key);\n if (stored !== null) {\n current = parsePreferences(stored, \"storage-read\", report) ?? current;\n }\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n }\n let disposed = false;\n let eventEpoch = 0;\n const listeners = new Set<() => void>();\n let unsubscribeEvents: (() => void) | undefined;\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store listeners cannot prevent other listeners.\n }\n }\n };\n const replace = (next: PreferenceSchemaV1): boolean => {\n if (samePreferences(current, next)) return false;\n current = next;\n notify();\n return true;\n };\n const handleStorageEvent = (event: PreferenceStorageEvent): void => {\n if (disposed || !persistence) return;\n const epoch = ++eventEpoch;\n let key: string | null;\n let newValue: string | null;\n let storageArea: PreferenceStorage | null | undefined;\n try {\n key = event.key;\n newValue = event.newValue;\n storageArea = event.storageArea;\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n return;\n }\n if (disposed || epoch !== eventEpoch) return;\n try {\n if (storageArea != null && storageArea !== persistence.storage) {\n return;\n }\n if (key !== null && key !== persistence.key) return;\n if (key === null || newValue === null) {\n replace(configuredDefault);\n return;\n }\n const next = parsePreferences(newValue, \"storage-event\", report);\n if (!disposed && epoch === eventEpoch && next) replace(next);\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n }\n };\n\n if (persistence?.events) {\n try {\n unsubscribeEvents = persistence.events.subscribe(handleStorageEvent);\n } catch (cause) {\n report(\"event-subscribe\", \"operation-failed\", cause);\n }\n }\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => current,\n getServerSnapshot: () => configuredDefault,\n setPreferences(value) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n const next = normalizePreferences(value);\n const changed = replace(next);\n if (!disposed && persistence?.storage && samePreferences(current, next)) {\n const serialized = JSON.stringify(next);\n if (!changed) {\n const epoch = eventEpoch;\n let matchesStoredValue = false;\n try {\n matchesStoredValue =\n persistence.storage.getItem(persistence.key) === serialized;\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n if (\n matchesStoredValue ||\n disposed ||\n epoch !== eventEpoch ||\n !samePreferences(current, next)\n ) {\n return;\n }\n }\n if (disposed || !samePreferences(current, next)) return;\n try {\n persistence.storage.setItem(persistence.key, serialized);\n } catch (cause) {\n report(\"storage-write\", \"operation-failed\", cause);\n }\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n eventEpoch += 1;\n listeners.clear();\n const unsubscribe = unsubscribeEvents;\n unsubscribeEvents = undefined;\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (cause) {\n report(\"event-unsubscribe\", \"operation-failed\", cause);\n }\n }\n },\n };\n}\n\ninterface ResolvedPreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nfunction resolvePersistence(\n persistence: PreferencePersistence | undefined,\n): ResolvedPreferencePersistence | undefined {\n if (!persistence) return undefined;\n if (persistence.storage) return persistence;\n const browser = getBrowserPersistence();\n return {\n key: persistence.key,\n ...(browser?.storage ? { storage: browser.storage } : {}),\n ...(persistence.events\n ? { events: persistence.events }\n : browser?.events\n ? { events: browser.events }\n : {}),\n };\n}\n\nfunction getBrowserPersistence():\n | { storage: PreferenceStorage; events: PreferenceStorageEventSource }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n const browserWindow = window;\n const storage = browserWindow.localStorage;\n if (!storage) return undefined;\n return {\n storage,\n events: {\n subscribe(listener) {\n const handle = (event: StorageEvent): void => listener(event);\n browserWindow.addEventListener(\"storage\", handle);\n return () => browserWindow.removeEventListener(\"storage\", handle);\n },\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction parsePreferences(\n raw: string,\n source: \"storage-read\" | \"storage-event\",\n report: (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ) => void,\n): PreferenceSchemaV1 | undefined {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (cause) {\n report(source, \"invalid-json\", cause);\n return undefined;\n }\n try {\n return normalizePreferences(value as PreferenceSchemaV1);\n } catch (cause) {\n report(\n source,\n cause instanceof UnsupportedPreferenceVersionError\n ? \"unsupported-version\"\n : \"invalid-preference\",\n cause,\n );\n return undefined;\n }\n}\n\nclass UnsupportedPreferenceVersionError extends TypeError {}\n\nexport function normalizePreferences(\n value: PreferenceSchemaV1,\n): PreferenceSchemaV1 {\n const fields = snapshotPreferenceFields(value);\n if (fields.version !== 1)\n throw new UnsupportedPreferenceVersionError(\n \"Unsupported preference version\",\n );\n if (fields.preset === \"completion-only\") {\n if (!hasExactKeys(fields, [\"version\", \"preset\"]))\n throw new TypeError(\"Invalid completion-only preferences\");\n return Object.freeze({ version: 1, preset: \"completion-only\" });\n }\n if (\n !([\"minimal\", \"balanced\", \"verbose\"] as unknown[]).includes(fields.preset)\n )\n throw new TypeError(\"Invalid preference preset\");\n if (!hasExactKeys(fields, [\"version\", \"preset\", \"streaming\", \"tools\"]))\n throw new TypeError(\"Invalid preference fields\");\n if (!STREAMING_VALUES.includes(fields.streaming as StreamingVerbosity))\n throw new TypeError(\"Invalid streaming preference\");\n if (!TOOL_VALUES.includes(fields.tools as ToolVerbosity))\n throw new TypeError(\"Invalid tool preference\");\n return Object.freeze({\n version: 1,\n preset: fields.preset as \"minimal\" | \"balanced\" | \"verbose\",\n streaming: fields.streaming as StreamingVerbosity,\n tools: fields.tools as ToolVerbosity,\n });\n}\n\nconst STREAMING_VALUES: readonly StreamingVerbosity[] = [\n \"preset\",\n \"off\",\n \"completion\",\n \"paragraph\",\n \"sentence\",\n];\nconst TOOL_VALUES: readonly ToolVerbosity[] = [\n \"preset\",\n \"off\",\n \"failures\",\n \"status\",\n \"progress\",\n];\n\nfunction snapshotPreferenceFields(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(\"Invalid preferences\");\n }\n try {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const fields = Object.create(null) as Record<string, unknown>;\n for (const key of Reflect.ownKeys(descriptors)) {\n if (typeof key !== \"string\")\n throw new TypeError(\"Invalid preference fields\");\n const descriptor = descriptors[key];\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\n \"Preference fields must be enumerable data properties\",\n );\n }\n fields[key] = descriptor.value;\n }\n return fields;\n } catch {\n throw new TypeError(\"Invalid preferences\");\n }\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value);\n return (\n keys.length === expected.length &&\n expected.every((key) => keys.includes(key))\n );\n}\n\nexport function samePreferences(\n left: PreferenceSchemaV1,\n right: PreferenceSchemaV1,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction mapStreaming(\n value: StreamingVerbosity,\n): PolicyOverrides[\"text\"] | undefined {\n if (value === \"preset\") return undefined;\n if (value === \"off\") return { strategy: \"silent\" };\n if (value === \"completion\")\n return { strategy: \"completion\", minimumCharacters: 0, maximumDelayMs: 0 };\n return { strategy: value };\n}\n\nfunction mapTools(value: ToolVerbosity): PolicyOverrides[\"tools\"] | undefined {\n if (value === \"preset\") return undefined;\n return {\n announceStart: value === \"status\" || value === \"progress\",\n announceProgress: value === \"progress\",\n announceCompletion: value === \"status\" || value === \"progress\",\n announceFailure: value !== \"off\",\n };\n}\n\nfunction serializeError(cause: unknown): Readonly<{\n name: string;\n message: string;\n}> {\n const fallback = { name: \"Error\", message: \"Unknown error\" } as const;\n try {\n if (cause instanceof Error) {\n const name = cause.name;\n const message = cause.message;\n if (typeof name !== \"string\" || typeof message !== \"string\") {\n return fallback;\n }\n return { name: name || \"Error\", message };\n }\n if (\n typeof cause === \"string\" ||\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\" ||\n typeof cause === \"symbol\"\n ) {\n return { name: \"Error\", message: String(cause) };\n }\n } catch {\n return fallback;\n }\n return fallback;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,IAAM,gBAAgB,oBAAI,QAAiB;AAGpC,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AACF,GAA8C;AAC5C,MAAI,cAAc,IAAI,OAAO,GAAG;AAC9B,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,gBAAc,IAAI,OAAO;AACzB,MAAI,SAAS;AACb,MAAI;AACJ,MAAI;AACJ,MAAI,WAAW;AACf,QAAM,SAAS,MAAM;AACnB,QAAI,CAAC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d,SACA,UAA4B,CAAC,GACb;AAChB,QAAM,YAAY,gBAAgB,OAAO;AACzC,MAAI,WAAW;AACf,MAAI;AACJ,MAAI;AACF,kBAAc,QAAQ,uBAAuB,CAAC,WAAW;AACvD,UAAI,CAAC,SAAU,WAAU,SAAS,MAAM;AAAA,IAC1C,CAAC;AAAA,EACH,SAAS,OAAO;AACd,cAAU,QAAQ;AAClB,UAAM;AAAA,EACR;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AACR,UAAI,SAAU;AACd,iBAAW;AACX,UAAI;AACF,oBAAY;AAAA,MACd,UAAE;AACA,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;","names":["document","document","window","document","serializeError"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PresetName, PolicyOverrides, AnnouncementIntent
|
|
1
|
+
import { Runtime, PresetName, PolicyOverrides, AnnouncementIntent } from '@generative-a11y/core';
|
|
2
2
|
|
|
3
3
|
interface ExternalStore<T> {
|
|
4
4
|
subscribe(listener: () => void): () => void;
|
|
@@ -31,6 +31,16 @@ interface AttentionIntersectionObserver {
|
|
|
31
31
|
type AttentionIntersectionObserverFactory = (callback: IntersectionObserverCallback, options?: IntersectionObserverInit) => AttentionIntersectionObserver;
|
|
32
32
|
declare function createAttentionStore(options?: AttentionStoreOptions): AttentionStore;
|
|
33
33
|
|
|
34
|
+
interface AttentionBindingOptions {
|
|
35
|
+
readonly runtime: Runtime;
|
|
36
|
+
readonly attentionStore: AttentionStore;
|
|
37
|
+
}
|
|
38
|
+
interface AttentionBinding {
|
|
39
|
+
dispose(): void;
|
|
40
|
+
}
|
|
41
|
+
/** Borrow a store and runtime, forwarding observations without changing overrides. */
|
|
42
|
+
declare function bindAttention({ runtime, attentionStore, }: AttentionBindingOptions): AttentionBinding;
|
|
43
|
+
|
|
34
44
|
interface FocusCapture {
|
|
35
45
|
readonly document: Document | null;
|
|
36
46
|
readonly target: Element | null;
|
|
@@ -111,12 +121,12 @@ declare function createPreferenceStore(options?: PreferenceStoreOptions): Prefer
|
|
|
111
121
|
declare function normalizePreferences(value: PreferenceSchemaV1): PreferenceSchemaV1;
|
|
112
122
|
declare function samePreferences(left: PreferenceSchemaV1, right: PreferenceSchemaV1): boolean;
|
|
113
123
|
|
|
114
|
-
type
|
|
115
|
-
interface
|
|
124
|
+
type DeliveryMode = "auto" | "live-region";
|
|
125
|
+
interface LiveRegions {
|
|
116
126
|
polite: HTMLElement;
|
|
117
127
|
assertive: HTMLElement;
|
|
118
128
|
}
|
|
119
|
-
interface
|
|
129
|
+
interface DeliveryResult {
|
|
120
130
|
status: "notified" | "mutated" | "unavailable" | "disposed";
|
|
121
131
|
method: "aria-notify" | "live-region" | "none";
|
|
122
132
|
channel: AnnouncementIntent["channel"];
|
|
@@ -140,22 +150,22 @@ interface DOMDeliveryResult {
|
|
|
140
150
|
message: string;
|
|
141
151
|
};
|
|
142
152
|
}
|
|
143
|
-
interface
|
|
153
|
+
interface AnnouncerOptions {
|
|
144
154
|
document?: Document;
|
|
145
|
-
mode?:
|
|
146
|
-
regions?:
|
|
147
|
-
|
|
155
|
+
mode?: DeliveryMode;
|
|
156
|
+
regions?: LiveRegions;
|
|
157
|
+
onDelivery?: (result: DeliveryResult) => void;
|
|
148
158
|
}
|
|
149
|
-
interface
|
|
150
|
-
announce(intent: AnnouncementIntent):
|
|
151
|
-
getRegions():
|
|
159
|
+
interface Announcer {
|
|
160
|
+
announce(intent: AnnouncementIntent): DeliveryResult;
|
|
161
|
+
getRegions(): LiveRegions | undefined;
|
|
152
162
|
dispose(): void;
|
|
153
163
|
}
|
|
154
|
-
interface
|
|
155
|
-
announcer:
|
|
164
|
+
interface RuntimeBinding {
|
|
165
|
+
announcer: Announcer;
|
|
156
166
|
dispose(): void;
|
|
157
167
|
}
|
|
158
|
-
declare function
|
|
159
|
-
declare function
|
|
168
|
+
declare function createAnnouncer(options?: AnnouncerOptions): Announcer;
|
|
169
|
+
declare function bindRuntime(runtime: Runtime, options?: AnnouncerOptions): RuntimeBinding;
|
|
160
170
|
|
|
161
|
-
export { type
|
|
171
|
+
export { type Announcer, type AnnouncerOptions, type AttentionBinding, type AttentionBindingOptions, type AttentionIntersectionObserver, type AttentionIntersectionObserverFactory, type AttentionSnapshot, type AttentionStore, type AttentionStoreOptions, type CorePreferenceConfiguration, type DeliveryMode, type DeliveryResult, type ExternalStore, type FocusCapture, type FocusElementOptions, type FocusResult, type FocusSkippedReason, type LiveRegions, type PreferenceDiagnostic, type PreferenceDiagnosticCode, type PreferenceDiagnosticSource, type PreferencePersistence, type PreferenceSchemaV1, type PreferenceStorage, type PreferenceStorageEvent, type PreferenceStorageEventSource, type PreferenceStore, type PreferenceStoreOptions, type RestoreFocusOptions, type RuntimeBinding, type StreamingVerbosity, type ToolVerbosity, bindAttention, bindRuntime, captureFocus, createAnnouncer, createAttentionStore, createPreferenceStore, defaultPreferences, focusElement, normalizePreferences, preferencesToCoreConfiguration, restoreFocus, samePreferences };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PresetName, PolicyOverrides, AnnouncementIntent
|
|
1
|
+
import { Runtime, PresetName, PolicyOverrides, AnnouncementIntent } from '@generative-a11y/core';
|
|
2
2
|
|
|
3
3
|
interface ExternalStore<T> {
|
|
4
4
|
subscribe(listener: () => void): () => void;
|
|
@@ -31,6 +31,16 @@ interface AttentionIntersectionObserver {
|
|
|
31
31
|
type AttentionIntersectionObserverFactory = (callback: IntersectionObserverCallback, options?: IntersectionObserverInit) => AttentionIntersectionObserver;
|
|
32
32
|
declare function createAttentionStore(options?: AttentionStoreOptions): AttentionStore;
|
|
33
33
|
|
|
34
|
+
interface AttentionBindingOptions {
|
|
35
|
+
readonly runtime: Runtime;
|
|
36
|
+
readonly attentionStore: AttentionStore;
|
|
37
|
+
}
|
|
38
|
+
interface AttentionBinding {
|
|
39
|
+
dispose(): void;
|
|
40
|
+
}
|
|
41
|
+
/** Borrow a store and runtime, forwarding observations without changing overrides. */
|
|
42
|
+
declare function bindAttention({ runtime, attentionStore, }: AttentionBindingOptions): AttentionBinding;
|
|
43
|
+
|
|
34
44
|
interface FocusCapture {
|
|
35
45
|
readonly document: Document | null;
|
|
36
46
|
readonly target: Element | null;
|
|
@@ -111,12 +121,12 @@ declare function createPreferenceStore(options?: PreferenceStoreOptions): Prefer
|
|
|
111
121
|
declare function normalizePreferences(value: PreferenceSchemaV1): PreferenceSchemaV1;
|
|
112
122
|
declare function samePreferences(left: PreferenceSchemaV1, right: PreferenceSchemaV1): boolean;
|
|
113
123
|
|
|
114
|
-
type
|
|
115
|
-
interface
|
|
124
|
+
type DeliveryMode = "auto" | "live-region";
|
|
125
|
+
interface LiveRegions {
|
|
116
126
|
polite: HTMLElement;
|
|
117
127
|
assertive: HTMLElement;
|
|
118
128
|
}
|
|
119
|
-
interface
|
|
129
|
+
interface DeliveryResult {
|
|
120
130
|
status: "notified" | "mutated" | "unavailable" | "disposed";
|
|
121
131
|
method: "aria-notify" | "live-region" | "none";
|
|
122
132
|
channel: AnnouncementIntent["channel"];
|
|
@@ -140,22 +150,22 @@ interface DOMDeliveryResult {
|
|
|
140
150
|
message: string;
|
|
141
151
|
};
|
|
142
152
|
}
|
|
143
|
-
interface
|
|
153
|
+
interface AnnouncerOptions {
|
|
144
154
|
document?: Document;
|
|
145
|
-
mode?:
|
|
146
|
-
regions?:
|
|
147
|
-
|
|
155
|
+
mode?: DeliveryMode;
|
|
156
|
+
regions?: LiveRegions;
|
|
157
|
+
onDelivery?: (result: DeliveryResult) => void;
|
|
148
158
|
}
|
|
149
|
-
interface
|
|
150
|
-
announce(intent: AnnouncementIntent):
|
|
151
|
-
getRegions():
|
|
159
|
+
interface Announcer {
|
|
160
|
+
announce(intent: AnnouncementIntent): DeliveryResult;
|
|
161
|
+
getRegions(): LiveRegions | undefined;
|
|
152
162
|
dispose(): void;
|
|
153
163
|
}
|
|
154
|
-
interface
|
|
155
|
-
announcer:
|
|
164
|
+
interface RuntimeBinding {
|
|
165
|
+
announcer: Announcer;
|
|
156
166
|
dispose(): void;
|
|
157
167
|
}
|
|
158
|
-
declare function
|
|
159
|
-
declare function
|
|
168
|
+
declare function createAnnouncer(options?: AnnouncerOptions): Announcer;
|
|
169
|
+
declare function bindRuntime(runtime: Runtime, options?: AnnouncerOptions): RuntimeBinding;
|
|
160
170
|
|
|
161
|
-
export { type
|
|
171
|
+
export { type Announcer, type AnnouncerOptions, type AttentionBinding, type AttentionBindingOptions, type AttentionIntersectionObserver, type AttentionIntersectionObserverFactory, type AttentionSnapshot, type AttentionStore, type AttentionStoreOptions, type CorePreferenceConfiguration, type DeliveryMode, type DeliveryResult, type ExternalStore, type FocusCapture, type FocusElementOptions, type FocusResult, type FocusSkippedReason, type LiveRegions, type PreferenceDiagnostic, type PreferenceDiagnosticCode, type PreferenceDiagnosticSource, type PreferencePersistence, type PreferenceSchemaV1, type PreferenceStorage, type PreferenceStorageEvent, type PreferenceStorageEventSource, type PreferenceStore, type PreferenceStoreOptions, type RestoreFocusOptions, type RuntimeBinding, type StreamingVerbosity, type ToolVerbosity, bindAttention, bindRuntime, captureFocus, createAnnouncer, createAttentionStore, createPreferenceStore, defaultPreferences, focusElement, normalizePreferences, preferencesToCoreConfiguration, restoreFocus, samePreferences };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
+
// src/attention-binding.ts
|
|
2
|
+
var boundRuntimes = /* @__PURE__ */ new WeakSet();
|
|
3
|
+
function bindAttention({
|
|
4
|
+
runtime,
|
|
5
|
+
attentionStore
|
|
6
|
+
}) {
|
|
7
|
+
if (boundRuntimes.has(runtime)) {
|
|
8
|
+
throw new Error("Runtime already has an attention binding");
|
|
9
|
+
}
|
|
10
|
+
boundRuntimes.add(runtime);
|
|
11
|
+
let active = true;
|
|
12
|
+
let unsubscribe;
|
|
13
|
+
let lastMode;
|
|
14
|
+
let revision = 0;
|
|
15
|
+
const update = () => {
|
|
16
|
+
if (!active) return;
|
|
17
|
+
const readRevision = ++revision;
|
|
18
|
+
const mode = attentionStore.getSnapshot().mode;
|
|
19
|
+
if (!active || revision !== readRevision || mode === lastMode) return;
|
|
20
|
+
lastMode = mode;
|
|
21
|
+
runtime.dispatch({ type: "attention.changed", mode });
|
|
22
|
+
};
|
|
23
|
+
const dispose = () => {
|
|
24
|
+
if (!active) return;
|
|
25
|
+
active = false;
|
|
26
|
+
try {
|
|
27
|
+
try {
|
|
28
|
+
unsubscribe?.();
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
if (lastMode !== void 0) {
|
|
32
|
+
runtime.dispatch({ type: "attention.changed", mode: "unknown" });
|
|
33
|
+
}
|
|
34
|
+
} finally {
|
|
35
|
+
boundRuntimes.delete(runtime);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
unsubscribe = attentionStore.subscribe(update);
|
|
40
|
+
update();
|
|
41
|
+
} catch (error) {
|
|
42
|
+
try {
|
|
43
|
+
dispose();
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
return { dispose };
|
|
49
|
+
}
|
|
50
|
+
|
|
1
51
|
// src/composed-tree.ts
|
|
2
52
|
function deepActiveElement(document2) {
|
|
3
53
|
let active = document2.activeElement;
|
|
@@ -145,7 +195,7 @@ function createAttentionStore(options = {}) {
|
|
|
145
195
|
update();
|
|
146
196
|
};
|
|
147
197
|
};
|
|
148
|
-
const
|
|
198
|
+
const createChatObserver = (registration, target) => {
|
|
149
199
|
const factory = options.createIntersectionObserver ?? defaultIntersectionObserverFactory(selectedWindow);
|
|
150
200
|
if (!factory) return void 0;
|
|
151
201
|
let created;
|
|
@@ -195,7 +245,7 @@ function createAttentionStore(options = {}) {
|
|
|
195
245
|
stopObserver(newestTarget);
|
|
196
246
|
newestTarget = element;
|
|
197
247
|
newestResult = "unknown";
|
|
198
|
-
observer =
|
|
248
|
+
observer = createChatObserver(registration, element);
|
|
199
249
|
update();
|
|
200
250
|
let registered = true;
|
|
201
251
|
return () => {
|
|
@@ -763,7 +813,9 @@ function serializeError(cause) {
|
|
|
763
813
|
}
|
|
764
814
|
|
|
765
815
|
// src/index.ts
|
|
766
|
-
function
|
|
816
|
+
function createAnnouncer(options = {}) {
|
|
817
|
+
if (options.mode !== void 0 && options.mode !== "auto" && options.mode !== "live-region")
|
|
818
|
+
throw new TypeError('mode must be "auto" or "live-region"');
|
|
767
819
|
validateSuppliedRegions(options);
|
|
768
820
|
const selectedDocument = options.document ?? options.regions?.polite.ownerDocument ?? (typeof document === "undefined" ? void 0 : document);
|
|
769
821
|
const ownsRegions = options.regions === void 0;
|
|
@@ -776,7 +828,7 @@ function createDOMAnnouncer(options = {}) {
|
|
|
776
828
|
let disposed = false;
|
|
777
829
|
const report = (result) => {
|
|
778
830
|
try {
|
|
779
|
-
options.
|
|
831
|
+
options.onDelivery?.(result);
|
|
780
832
|
} catch {
|
|
781
833
|
}
|
|
782
834
|
return result;
|
|
@@ -954,8 +1006,8 @@ function applyLocale(region, locale) {
|
|
|
954
1006
|
if (locale === void 0) region.removeAttribute("lang");
|
|
955
1007
|
else region.setAttribute("lang", locale);
|
|
956
1008
|
}
|
|
957
|
-
function
|
|
958
|
-
const announcer =
|
|
1009
|
+
function bindRuntime(runtime, options = {}) {
|
|
1010
|
+
const announcer = createAnnouncer(options);
|
|
959
1011
|
let disposed = false;
|
|
960
1012
|
let unsubscribe;
|
|
961
1013
|
try {
|
|
@@ -980,10 +1032,11 @@ function connectRuntimeToDOM(runtime, options = {}) {
|
|
|
980
1032
|
};
|
|
981
1033
|
}
|
|
982
1034
|
export {
|
|
1035
|
+
bindAttention,
|
|
1036
|
+
bindRuntime,
|
|
983
1037
|
captureFocus,
|
|
984
|
-
|
|
1038
|
+
createAnnouncer,
|
|
985
1039
|
createAttentionStore,
|
|
986
|
-
createDOMAnnouncer,
|
|
987
1040
|
createPreferenceStore,
|
|
988
1041
|
defaultPreferences,
|
|
989
1042
|
focusElement,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/composed-tree.ts","../src/attention.ts","../src/focus.ts","../src/preferences.ts","../src/index.ts"],"sourcesContent":["export function deepActiveElement(document: Document): Element | null {\n let active = document.activeElement;\n const visited = new Set<Element>();\n while (active) {\n if (visited.has(active)) throw new Error(\"Cyclic active element\");\n visited.add(active);\n const shadow = (active as Element & { shadowRoot?: ShadowRoot | null })\n .shadowRoot;\n const nested = shadow?.activeElement;\n if (!nested) return active;\n active = nested;\n }\n return null;\n}\n\nexport function composedContains(ancestor: Element, target: Element): boolean {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (current === ancestor) return true;\n if (visited.has(current)) throw new Error(\"Cyclic composed tree\");\n visited.add(current);\n current = composedParent(current);\n }\n return false;\n}\n\nexport function composedParent(element: Element): Element | null {\n const assignedSlot = (\n element as Element & { assignedSlot?: HTMLSlotElement | null }\n ).assignedSlot;\n if (assignedSlot) return assignedSlot;\n if (element.parentElement) return element.parentElement;\n const root = element.getRootNode();\n if (root && \"host\" in root) {\n const host = (root as ShadowRoot).host;\n if (host.ownerDocument === element.ownerDocument) return host;\n }\n return null;\n}\n","import { composedContains, deepActiveElement } from \"./composed-tree.js\";\n\nexport interface ExternalStore<T> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): T;\n getServerSnapshot(): T;\n}\n\nexport interface AttentionSnapshot {\n readonly visibility: \"visible\" | \"hidden\" | \"unknown\";\n readonly windowFocus: \"focused\" | \"blurred\" | \"unknown\";\n readonly focusArea:\n \"composer\" | \"conversation\" | \"elsewhere\" | \"none\" | \"unknown\";\n readonly newestResponse: \"visible\" | \"outside\" | \"unobserved\" | \"unknown\";\n readonly mode:\n \"foreground\" | \"background\" | \"reading-history\" | \"away\" | \"unknown\";\n}\n\nexport interface AttentionStore extends ExternalStore<AttentionSnapshot> {\n registerComposer(element: Element): () => void;\n registerConversation(element: Element): () => void;\n registerNewestResponse(element: Element): () => void;\n dispose(): void;\n}\n\nexport interface AttentionStoreOptions {\n document?: Document;\n createIntersectionObserver?: AttentionIntersectionObserverFactory;\n intersectionObserverInit?: IntersectionObserverInit;\n}\n\nexport interface AttentionIntersectionObserver {\n observe(target: Element): void;\n unobserve(target: Element): void;\n disconnect(): void;\n}\n\nexport type AttentionIntersectionObserverFactory = (\n callback: IntersectionObserverCallback,\n options?: IntersectionObserverInit,\n) => AttentionIntersectionObserver;\n\nconst UNKNOWN_SNAPSHOT: AttentionSnapshot = Object.freeze({\n visibility: \"unknown\",\n windowFocus: \"unknown\",\n focusArea: \"unknown\",\n newestResponse: \"unknown\",\n mode: \"unknown\",\n});\n\nexport function createAttentionStore(\n options: AttentionStoreOptions = {},\n): AttentionStore {\n const selectedDocument =\n options.document ??\n (typeof document === \"undefined\" ? undefined : document);\n if (!selectedDocument) {\n return {\n subscribe: () => () => undefined,\n getSnapshot: () => UNKNOWN_SNAPSHOT,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: () => () => undefined,\n registerConversation: () => () => undefined,\n registerNewestResponse: () => () => undefined,\n dispose: () => undefined,\n };\n }\n\n const listeners = new Set<() => void>();\n const composers = new Map<Element, number>();\n const conversations = new Map<Element, number>();\n const selectedWindow = selectedDocument.defaultView;\n let disposed = false;\n let newestTarget: Element | undefined;\n let newestResult: AttentionSnapshot[\"newestResponse\"] = \"unobserved\";\n let newestRegistration = 0;\n let observer: AttentionIntersectionObserver | undefined;\n let snapshot = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n const update = () => {\n if (disposed) return;\n const next = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n if (sameSnapshot(snapshot, next)) return;\n snapshot = next;\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store observers cannot prevent other observers from running.\n }\n }\n };\n const handleFocusOut = (event: FocusEvent) => {\n if (event.relatedTarget === null) update();\n };\n const listenerCleanups: Array<() => void> = [];\n const installListener = (install: () => void, cleanup: () => void): void => {\n // Register cleanup first because a hostile EventTarget can install and then\n // throw from addEventListener(). Removing a listener that was not installed\n // is harmless, while omitting cleanup would leak the accepted listener.\n listenerCleanups.push(cleanup);\n install();\n };\n const cleanupListeners = (): void => {\n for (const cleanup of listenerCleanups.splice(0).reverse()) {\n try {\n cleanup();\n } catch {\n // One hostile removal cannot strand the remaining listeners.\n }\n }\n };\n try {\n installListener(\n () => selectedDocument.addEventListener(\"visibilitychange\", update),\n () => selectedDocument.removeEventListener(\"visibilitychange\", update),\n );\n if (selectedWindow) {\n installListener(\n () => selectedWindow.addEventListener(\"focus\", update),\n () => selectedWindow.removeEventListener(\"focus\", update),\n );\n installListener(\n () => selectedWindow.addEventListener(\"blur\", update),\n () => selectedWindow.removeEventListener(\"blur\", update),\n );\n }\n installListener(\n () => selectedDocument.addEventListener(\"focusin\", update),\n () => selectedDocument.removeEventListener(\"focusin\", update),\n );\n installListener(\n () => selectedDocument.addEventListener(\"focusout\", handleFocusOut),\n () => selectedDocument.removeEventListener(\"focusout\", handleFocusOut),\n );\n } catch (error) {\n cleanupListeners();\n throw error;\n }\n\n const register = (\n elements: Map<Element, number>,\n element: Element,\n ): (() => void) => {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n elements.set(element, (elements.get(element) ?? 0) + 1);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n const remaining = (elements.get(element) ?? 1) - 1;\n if (remaining === 0) elements.delete(element);\n else elements.set(element, remaining);\n update();\n };\n };\n\n const createObserver = (\n registration: number,\n target: Element,\n ): AttentionIntersectionObserver | undefined => {\n const factory =\n options.createIntersectionObserver ??\n defaultIntersectionObserverFactory(selectedWindow);\n if (!factory) return undefined;\n let created: AttentionIntersectionObserver | undefined;\n try {\n created = factory((entries) => {\n if (\n disposed ||\n registration !== newestRegistration ||\n newestTarget !== target ||\n observer !== created\n ) {\n return;\n }\n let latest: IntersectionObserverEntry | undefined;\n for (const entry of entries) {\n if (entry.target === target) latest = entry;\n }\n if (!latest) return;\n newestResult = latest.isIntersecting ? \"visible\" : \"outside\";\n update();\n }, options.intersectionObserverInit);\n created.observe(target);\n return created;\n } catch {\n cleanupObserver(created, target);\n return undefined;\n }\n };\n\n const stopObserver = (target?: Element): void => {\n const current = observer;\n observer = undefined;\n cleanupObserver(current, target);\n };\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: (element) => register(composers, element),\n registerConversation: (element) => register(conversations, element),\n registerNewestResponse(element) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n const registration = ++newestRegistration;\n stopObserver(newestTarget);\n newestTarget = element;\n newestResult = \"unknown\";\n observer = createObserver(registration, element);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n if (registration !== newestRegistration || newestTarget !== element)\n return;\n stopObserver(element);\n newestTarget = undefined;\n newestResult = \"unobserved\";\n update();\n };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n listeners.clear();\n composers.clear();\n conversations.clear();\n stopObserver(newestTarget);\n newestTarget = undefined;\n cleanupListeners();\n },\n };\n}\n\nfunction makeSnapshot(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot {\n const visibility = readVisibility(document);\n const windowFocus = readWindowFocus(document);\n return Object.freeze({\n visibility,\n windowFocus,\n focusArea: readFocusArea(document, composers, conversations),\n newestResponse,\n mode: deriveMode(visibility, windowFocus, newestResponse),\n });\n}\n\nfunction deriveMode(\n visibility: AttentionSnapshot[\"visibility\"],\n windowFocus: AttentionSnapshot[\"windowFocus\"],\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot[\"mode\"] {\n if (visibility === \"hidden\") return \"background\";\n if (visibility !== \"visible\") return \"unknown\";\n if (windowFocus === \"blurred\") return \"away\";\n if (windowFocus !== \"focused\") return \"unknown\";\n if (newestResponse === \"outside\") return \"reading-history\";\n if (newestResponse === \"visible\") return \"foreground\";\n return \"unknown\";\n}\n\nfunction defaultIntersectionObserverFactory(\n window: (Window & typeof globalThis) | null,\n): AttentionIntersectionObserverFactory | undefined {\n const Constructor = window?.IntersectionObserver;\n if (typeof Constructor !== \"function\") return undefined;\n return (callback, options) => new Constructor(callback, options);\n}\n\nfunction cleanupObserver(\n observer: AttentionIntersectionObserver | undefined,\n target?: Element,\n): void {\n if (!observer) return;\n if (target) {\n try {\n observer.unobserve(target);\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n }\n try {\n observer.disconnect();\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n}\n\nfunction readFocusArea(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n): AttentionSnapshot[\"focusArea\"] {\n let activeElement: Element | null;\n try {\n activeElement = deepActiveElement(document);\n } catch {\n return \"unknown\";\n }\n if (\n activeElement === null ||\n activeElement === document.body ||\n activeElement === document.documentElement\n ) {\n return \"none\";\n }\n if (\n [...composers.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"composer\";\n }\n if (\n [...conversations.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"conversation\";\n }\n return \"elsewhere\";\n}\n\nfunction readVisibility(document: Document): AttentionSnapshot[\"visibility\"] {\n try {\n if (document.visibilityState === \"visible\") return \"visible\";\n if (document.visibilityState === \"hidden\") return \"hidden\";\n } catch {\n // Browser integrations can expose throwing accessors.\n }\n return \"unknown\";\n}\n\nfunction readWindowFocus(document: Document): AttentionSnapshot[\"windowFocus\"] {\n try {\n if (typeof document.hasFocus !== \"function\") return \"unknown\";\n return document.hasFocus() ? \"focused\" : \"blurred\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction sameSnapshot(\n left: AttentionSnapshot,\n right: AttentionSnapshot,\n): boolean {\n return (\n left.visibility === right.visibility &&\n left.windowFocus === right.windowFocus &&\n left.focusArea === right.focusArea &&\n left.newestResponse === right.newestResponse &&\n left.mode === right.mode\n );\n}\n","import {\n composedContains,\n composedParent,\n deepActiveElement,\n} from \"./composed-tree.js\";\n\nexport interface FocusCapture {\n readonly document: Document | null;\n readonly target: Element | null;\n}\n\nexport interface FocusElementOptions {\n preventScroll?: boolean;\n}\n\nexport interface RestoreFocusOptions extends FocusElementOptions {\n onlyIfFocusWithin?: Element;\n}\n\nexport type FocusSkippedReason =\n | \"unavailable\"\n | \"cross-document\"\n | \"disconnected\"\n | \"disabled\"\n | \"hidden\"\n | \"aria-hidden\"\n | \"inert\"\n | \"missing-focus\"\n | \"guard-mismatch\"\n | \"focus-error\"\n | \"focus-not-applied\";\n\nexport type FocusResult =\n | { readonly status: \"focused\"; readonly target: Element }\n | {\n readonly status: \"skipped\";\n readonly reason: FocusSkippedReason;\n readonly target: Element | null;\n };\n\nexport function captureFocus(selectedDocument?: Document): FocusCapture {\n const document =\n selectedDocument ??\n (typeof globalThis.document === \"undefined\"\n ? undefined\n : globalThis.document);\n if (!document) return Object.freeze({ document: null, target: null });\n let target: Element | null = null;\n try {\n const active = deepActiveElement(document);\n if (\n active !== null &&\n active !== document.body &&\n active !== document.documentElement &&\n active.ownerDocument === document\n ) {\n target = active;\n }\n } catch {\n // A hostile document is captured without a restorable target.\n }\n return Object.freeze({ document, target });\n}\n\nexport function focusElement(\n target: Element,\n options: FocusElementOptions = {},\n): FocusResult {\n const eligibility = focusEligibility(target);\n if (eligibility) {\n return { status: \"skipped\", reason: eligibility, target };\n }\n let focus: ((options?: FocusOptions) => void) | undefined;\n let document: Document;\n let previous: Element | null;\n try {\n document = target.ownerDocument;\n previous = deepActiveElement(document);\n focus = (target as Element & { focus?: (options?: FocusOptions) => void })\n .focus;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target };\n }\n if (typeof focus !== \"function\") {\n return { status: \"skipped\", reason: \"missing-focus\", target };\n }\n let focusThrew = false;\n try {\n focus.call(target, { preventScroll: options.preventScroll ?? true });\n } catch {\n focusThrew = true;\n }\n if (focusThrew) {\n restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n const postFocusEligibility = focusEligibility(target);\n let active: Element | null;\n try {\n active = deepActiveElement(document);\n } catch {\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n if (postFocusEligibility) {\n if (active === target) restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: postFocusEligibility, target };\n }\n if (active !== target) {\n return { status: \"skipped\", reason: \"focus-not-applied\", target };\n }\n return { status: \"focused\", target };\n}\n\nexport function restoreFocus(\n capture: FocusCapture,\n options: RestoreFocusOptions = {},\n): FocusResult {\n let document: Document | null;\n let target: Element | null;\n try {\n document = capture.document;\n target = capture.target;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n if (!document || !target) {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n try {\n if (target.ownerDocument !== document) {\n return { status: \"skipped\", reason: \"cross-document\", target };\n }\n const guard = options.onlyIfFocusWithin;\n if (guard !== undefined) {\n const active = deepActiveElement(document);\n if (\n guard.ownerDocument !== document ||\n active === null ||\n !composedContains(guard, active)\n ) {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n }\n } catch {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n return focusElement(target, options);\n}\n\nfunction focusEligibility(target: Element): FocusSkippedReason | undefined {\n let ownerDocument: Document;\n try {\n ownerDocument = target.ownerDocument;\n const ElementConstructor = ownerDocument.defaultView?.Element;\n if (\n !ownerDocument ||\n (ElementConstructor && !(target instanceof ElementConstructor))\n ) {\n return \"unavailable\";\n }\n if (target.isConnected !== true) return \"disconnected\";\n if (\n target.getAttribute(\"disabled\") !== null ||\n (target as Element & { disabled?: unknown }).disabled === true\n ) {\n return \"disabled\";\n }\n } catch {\n return \"unavailable\";\n }\n try {\n const matches = target.matches;\n if (typeof matches === \"function\" && matches.call(target, \":disabled\")) {\n return \"disabled\";\n }\n } catch {\n // Fall back to the direct disabled checks above.\n }\n\n try {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (visited.has(current)) return \"unavailable\";\n visited.add(current);\n if (current.hasAttribute(\"hidden\")) return \"hidden\";\n if (current.getAttribute(\"aria-hidden\")?.trim().toLowerCase() === \"true\")\n return \"aria-hidden\";\n if (\n current.hasAttribute(\"inert\") ||\n (current as Element & { inert?: unknown }).inert === true\n ) {\n return \"inert\";\n }\n current = composedParent(current);\n }\n } catch {\n return \"unavailable\";\n }\n\n try {\n const focus = (\n target as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus !== \"function\") return \"missing-focus\";\n } catch {\n return \"unavailable\";\n }\n return undefined;\n}\n\nfunction restorePreviousFocus(\n previous: Element | null,\n attempted: Element,\n document: Document,\n): void {\n try {\n if (\n !previous ||\n deepActiveElement(document) !== attempted ||\n focusEligibility(previous) !== undefined\n ) {\n return;\n }\n const focus = (\n previous as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus === \"function\")\n focus.call(previous, { preventScroll: true });\n } catch {\n // Focus rollback is best-effort at hostile DOM boundaries.\n }\n}\n","import type { PolicyOverrides, PresetName } from \"@generative-a11y/core\";\n\nimport type { ExternalStore } from \"./attention.js\";\n\nexport type StreamingVerbosity =\n \"preset\" | \"off\" | \"completion\" | \"paragraph\" | \"sentence\";\n\nexport type ToolVerbosity =\n \"preset\" | \"off\" | \"failures\" | \"status\" | \"progress\";\n\nexport type PreferenceSchemaV1 =\n | Readonly<{ version: 1; preset: \"completion-only\" }>\n | Readonly<{\n version: 1;\n preset: \"minimal\" | \"balanced\" | \"verbose\";\n streaming: StreamingVerbosity;\n tools: ToolVerbosity;\n }>;\n\nexport interface PreferenceStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nexport interface PreferenceStorageEvent {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly storageArea?: PreferenceStorage | null;\n}\n\nexport interface PreferenceStorageEventSource {\n subscribe(listener: (event: PreferenceStorageEvent) => void): () => void;\n}\n\nexport type PreferenceDiagnosticSource =\n | \"storage-read\"\n | \"storage-write\"\n | \"storage-event\"\n | \"event-subscribe\"\n | \"event-unsubscribe\";\n\nexport type PreferenceDiagnosticCode =\n | \"operation-failed\"\n | \"invalid-json\"\n | \"invalid-preference\"\n | \"unsupported-version\";\n\nexport interface PreferenceDiagnostic {\n readonly source: PreferenceDiagnosticSource;\n readonly code: PreferenceDiagnosticCode;\n readonly error?: Readonly<{ name: string; message: string }>;\n}\n\nexport interface PreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nexport interface PreferenceStoreOptions {\n readonly defaultValue?: PreferenceSchemaV1;\n readonly persistence?: PreferencePersistence;\n readonly onDiagnostic?: (diagnostic: PreferenceDiagnostic) => void;\n}\n\nexport interface PreferenceStore extends ExternalStore<PreferenceSchemaV1> {\n setPreferences(value: PreferenceSchemaV1): void;\n dispose(): void;\n}\n\nexport interface CorePreferenceConfiguration {\n readonly preset: PresetName;\n readonly policy?: PolicyOverrides;\n}\n\nexport const defaultPreferences: PreferenceSchemaV1 = Object.freeze({\n version: 1,\n preset: \"balanced\",\n streaming: \"preset\",\n tools: \"preset\",\n});\n\nexport function preferencesToCoreConfiguration(\n value: PreferenceSchemaV1,\n): CorePreferenceConfiguration {\n const preferences = normalizePreferences(value);\n if (preferences.preset === \"completion-only\") {\n return { preset: \"completion-only\" };\n }\n const policy: PolicyOverrides = {};\n const text = mapStreaming(preferences.streaming);\n const tools = mapTools(preferences.tools);\n if (text) policy.text = text;\n if (tools) policy.tools = tools;\n return Object.keys(policy).length === 0\n ? { preset: preferences.preset }\n : { preset: preferences.preset, policy };\n}\n\nexport function createPreferenceStore(\n options: PreferenceStoreOptions = {},\n): PreferenceStore {\n const configuredDefault = options.defaultValue\n ? normalizePreferences(options.defaultValue)\n : defaultPreferences;\n const persistence = resolvePersistence(options.persistence);\n const report = (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ): void => {\n const diagnostic: PreferenceDiagnostic = {\n source,\n code,\n ...(cause === undefined ? {} : { error: serializeError(cause) }),\n };\n try {\n options.onDiagnostic?.(diagnostic);\n } catch {\n // Diagnostics are observational.\n }\n };\n let current = configuredDefault;\n if (persistence?.storage) {\n try {\n const stored = persistence.storage.getItem(persistence.key);\n if (stored !== null) {\n current = parsePreferences(stored, \"storage-read\", report) ?? current;\n }\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n }\n let disposed = false;\n let eventEpoch = 0;\n const listeners = new Set<() => void>();\n let unsubscribeEvents: (() => void) | undefined;\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store listeners cannot prevent other listeners.\n }\n }\n };\n const replace = (next: PreferenceSchemaV1): boolean => {\n if (samePreferences(current, next)) return false;\n current = next;\n notify();\n return true;\n };\n const handleStorageEvent = (event: PreferenceStorageEvent): void => {\n if (disposed || !persistence) return;\n const epoch = ++eventEpoch;\n let key: string | null;\n let newValue: string | null;\n let storageArea: PreferenceStorage | null | undefined;\n try {\n key = event.key;\n newValue = event.newValue;\n storageArea = event.storageArea;\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n return;\n }\n if (disposed || epoch !== eventEpoch) return;\n try {\n if (storageArea != null && storageArea !== persistence.storage) {\n return;\n }\n if (key !== null && key !== persistence.key) return;\n if (key === null || newValue === null) {\n replace(configuredDefault);\n return;\n }\n const next = parsePreferences(newValue, \"storage-event\", report);\n if (!disposed && epoch === eventEpoch && next) replace(next);\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n }\n };\n\n if (persistence?.events) {\n try {\n unsubscribeEvents = persistence.events.subscribe(handleStorageEvent);\n } catch (cause) {\n report(\"event-subscribe\", \"operation-failed\", cause);\n }\n }\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => current,\n getServerSnapshot: () => configuredDefault,\n setPreferences(value) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n const next = normalizePreferences(value);\n const changed = replace(next);\n if (!disposed && persistence?.storage && samePreferences(current, next)) {\n const serialized = JSON.stringify(next);\n if (!changed) {\n const epoch = eventEpoch;\n let matchesStoredValue = false;\n try {\n matchesStoredValue =\n persistence.storage.getItem(persistence.key) === serialized;\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n if (\n matchesStoredValue ||\n disposed ||\n epoch !== eventEpoch ||\n !samePreferences(current, next)\n ) {\n return;\n }\n }\n if (disposed || !samePreferences(current, next)) return;\n try {\n persistence.storage.setItem(persistence.key, serialized);\n } catch (cause) {\n report(\"storage-write\", \"operation-failed\", cause);\n }\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n eventEpoch += 1;\n listeners.clear();\n const unsubscribe = unsubscribeEvents;\n unsubscribeEvents = undefined;\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (cause) {\n report(\"event-unsubscribe\", \"operation-failed\", cause);\n }\n }\n },\n };\n}\n\ninterface ResolvedPreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nfunction resolvePersistence(\n persistence: PreferencePersistence | undefined,\n): ResolvedPreferencePersistence | undefined {\n if (!persistence) return undefined;\n if (persistence.storage) return persistence;\n const browser = getBrowserPersistence();\n return {\n key: persistence.key,\n ...(browser?.storage ? { storage: browser.storage } : {}),\n ...(persistence.events\n ? { events: persistence.events }\n : browser?.events\n ? { events: browser.events }\n : {}),\n };\n}\n\nfunction getBrowserPersistence():\n | { storage: PreferenceStorage; events: PreferenceStorageEventSource }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n const browserWindow = window;\n const storage = browserWindow.localStorage;\n if (!storage) return undefined;\n return {\n storage,\n events: {\n subscribe(listener) {\n const handle = (event: StorageEvent): void => listener(event);\n browserWindow.addEventListener(\"storage\", handle);\n return () => browserWindow.removeEventListener(\"storage\", handle);\n },\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction parsePreferences(\n raw: string,\n source: \"storage-read\" | \"storage-event\",\n report: (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ) => void,\n): PreferenceSchemaV1 | undefined {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (cause) {\n report(source, \"invalid-json\", cause);\n return undefined;\n }\n try {\n return normalizePreferences(value as PreferenceSchemaV1);\n } catch (cause) {\n report(\n source,\n cause instanceof UnsupportedPreferenceVersionError\n ? \"unsupported-version\"\n : \"invalid-preference\",\n cause,\n );\n return undefined;\n }\n}\n\nclass UnsupportedPreferenceVersionError extends TypeError {}\n\nexport function normalizePreferences(\n value: PreferenceSchemaV1,\n): PreferenceSchemaV1 {\n const fields = snapshotPreferenceFields(value);\n if (fields.version !== 1)\n throw new UnsupportedPreferenceVersionError(\n \"Unsupported preference version\",\n );\n if (fields.preset === \"completion-only\") {\n if (!hasExactKeys(fields, [\"version\", \"preset\"]))\n throw new TypeError(\"Invalid completion-only preferences\");\n return Object.freeze({ version: 1, preset: \"completion-only\" });\n }\n if (\n !([\"minimal\", \"balanced\", \"verbose\"] as unknown[]).includes(fields.preset)\n )\n throw new TypeError(\"Invalid preference preset\");\n if (!hasExactKeys(fields, [\"version\", \"preset\", \"streaming\", \"tools\"]))\n throw new TypeError(\"Invalid preference fields\");\n if (!STREAMING_VALUES.includes(fields.streaming as StreamingVerbosity))\n throw new TypeError(\"Invalid streaming preference\");\n if (!TOOL_VALUES.includes(fields.tools as ToolVerbosity))\n throw new TypeError(\"Invalid tool preference\");\n return Object.freeze({\n version: 1,\n preset: fields.preset as \"minimal\" | \"balanced\" | \"verbose\",\n streaming: fields.streaming as StreamingVerbosity,\n tools: fields.tools as ToolVerbosity,\n });\n}\n\nconst STREAMING_VALUES: readonly StreamingVerbosity[] = [\n \"preset\",\n \"off\",\n \"completion\",\n \"paragraph\",\n \"sentence\",\n];\nconst TOOL_VALUES: readonly ToolVerbosity[] = [\n \"preset\",\n \"off\",\n \"failures\",\n \"status\",\n \"progress\",\n];\n\nfunction snapshotPreferenceFields(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(\"Invalid preferences\");\n }\n try {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const fields = Object.create(null) as Record<string, unknown>;\n for (const key of Reflect.ownKeys(descriptors)) {\n if (typeof key !== \"string\")\n throw new TypeError(\"Invalid preference fields\");\n const descriptor = descriptors[key];\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\n \"Preference fields must be enumerable data properties\",\n );\n }\n fields[key] = descriptor.value;\n }\n return fields;\n } catch {\n throw new TypeError(\"Invalid preferences\");\n }\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value);\n return (\n keys.length === expected.length &&\n expected.every((key) => keys.includes(key))\n );\n}\n\nexport function samePreferences(\n left: PreferenceSchemaV1,\n right: PreferenceSchemaV1,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction mapStreaming(\n value: StreamingVerbosity,\n): PolicyOverrides[\"text\"] | undefined {\n if (value === \"preset\") return undefined;\n if (value === \"off\") return { strategy: \"silent\" };\n if (value === \"completion\")\n return { strategy: \"completion\", minimumCharacters: 0, maximumDelayMs: 0 };\n return { strategy: value };\n}\n\nfunction mapTools(value: ToolVerbosity): PolicyOverrides[\"tools\"] | undefined {\n if (value === \"preset\") return undefined;\n return {\n announceStart: value === \"status\" || value === \"progress\",\n announceProgress: value === \"progress\",\n announceCompletion: value === \"status\" || value === \"progress\",\n announceFailure: value !== \"off\",\n };\n}\n\nfunction serializeError(cause: unknown): Readonly<{\n name: string;\n message: string;\n}> {\n const fallback = { name: \"Error\", message: \"Unknown error\" } as const;\n try {\n if (cause instanceof Error) {\n const name = cause.name;\n const message = cause.message;\n if (typeof name !== \"string\" || typeof message !== \"string\") {\n return fallback;\n }\n return { name: name || \"Error\", message };\n }\n if (\n typeof cause === \"string\" ||\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\" ||\n typeof cause === \"symbol\"\n ) {\n return { name: \"Error\", message: String(cause) };\n }\n } catch {\n return fallback;\n }\n return fallback;\n}\n","import type {\n AnnouncementIntent,\n GenerativeA11yRuntime,\n} from \"@generative-a11y/core\";\n\nexport {\n createAttentionStore,\n type AttentionIntersectionObserver,\n type AttentionIntersectionObserverFactory,\n type AttentionSnapshot,\n type AttentionStore,\n type AttentionStoreOptions,\n type ExternalStore,\n} from \"./attention.js\";\n\nexport {\n captureFocus,\n focusElement,\n restoreFocus,\n type FocusCapture,\n type FocusElementOptions,\n type FocusResult,\n type FocusSkippedReason,\n type RestoreFocusOptions,\n} from \"./focus.js\";\n\nexport {\n createPreferenceStore,\n defaultPreferences,\n normalizePreferences,\n preferencesToCoreConfiguration,\n type CorePreferenceConfiguration,\n type PreferenceDiagnostic,\n type PreferenceDiagnosticCode,\n type PreferenceDiagnosticSource,\n type PreferencePersistence,\n type PreferenceSchemaV1,\n type PreferenceStorage,\n type PreferenceStorageEvent,\n type PreferenceStorageEventSource,\n type PreferenceStore,\n type PreferenceStoreOptions,\n samePreferences,\n type StreamingVerbosity,\n type ToolVerbosity,\n} from \"./preferences.js\";\n\nexport type DOMAnnouncementMode = \"auto\" | \"aria-notify\" | \"live-region\";\n\nexport interface DOMLiveRegions {\n polite: HTMLElement;\n assertive: HTMLElement;\n}\n\nexport interface DOMDeliveryResult {\n status: \"notified\" | \"mutated\" | \"unavailable\" | \"disposed\";\n method: \"aria-notify\" | \"live-region\" | \"none\";\n channel: AnnouncementIntent[\"channel\"];\n announcementId: string;\n sourceType: AnnouncementIntent[\"sourceType\"];\n at: number;\n sourceEventId?: string;\n responseId?: string;\n toolId?: string;\n interactionId?: string;\n /** Stable logical run identity associated with the delivered intent. */\n runId?: string;\n /** Stable run attempt identity associated with the delivered intent. */\n runInstanceId?: string;\n /** Stable logical step identity associated with the delivered intent. */\n stepId?: string;\n /** Stable step attempt identity associated with the delivered intent. */\n stepInstanceId?: string;\n error?: { name: string; message: string };\n}\n\nexport interface DOMAnnouncerOptions {\n document?: Document;\n mode?: DOMAnnouncementMode;\n regions?: DOMLiveRegions;\n onDiagnostic?: (result: DOMDeliveryResult) => void;\n}\n\nexport interface DOMAnnouncer {\n announce(intent: AnnouncementIntent): DOMDeliveryResult;\n getRegions(): DOMLiveRegions | undefined;\n dispose(): void;\n}\n\nexport interface DOMRuntimeBinding {\n announcer: DOMAnnouncer;\n dispose(): void;\n}\n\nexport function createDOMAnnouncer(\n options: DOMAnnouncerOptions = {},\n): DOMAnnouncer {\n validateSuppliedRegions(options);\n const selectedDocument =\n options.document ??\n options.regions?.polite.ownerDocument ??\n (typeof document === \"undefined\" ? undefined : document);\n const ownsRegions = options.regions === undefined;\n const regions = options.regions ?? createLiveRegions(selectedDocument);\n\n if (regions) {\n configureRegion(regions.polite, \"polite\");\n configureRegion(regions.assertive, \"assertive\");\n }\n let notifierEnabled = true;\n let disposed = false;\n\n const report = (result: DOMDeliveryResult): DOMDeliveryResult => {\n try {\n options.onDiagnostic?.(result);\n } catch {\n // Diagnostics are observational and cannot affect delivery.\n }\n return result;\n };\n\n return {\n announce(intent) {\n if (disposed) {\n return report({\n status: \"disposed\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n if (regions) {\n const region = regions[intent.channel];\n applyLocale(region, intent.locale);\n let error: DOMDeliveryResult[\"error\"];\n if (notifierEnabled && options.mode !== \"live-region\") {\n let notified = false;\n try {\n const ariaNotify = (region as AriaNotifyRegion).ariaNotify;\n if (typeof ariaNotify === \"function\") {\n ariaNotify.call(region, intent.text, {\n priority: intent.channel === \"assertive\" ? \"high\" : \"normal\",\n });\n notified = true;\n }\n } catch (cause) {\n notifierEnabled = false;\n error = serializeError(cause);\n }\n if (notified) {\n return report({\n status: \"notified\",\n method: \"aria-notify\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n }\n region.textContent = intent.text;\n return report({\n status: \"mutated\",\n method: \"live-region\",\n channel: intent.channel,\n ...deliveryContext(intent),\n ...(error === undefined ? {} : { error }),\n });\n }\n return report({\n status: \"unavailable\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n },\n getRegions() {\n return regions;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n if (ownsRegions) {\n regions?.polite.remove();\n regions?.assertive.remove();\n }\n },\n };\n}\n\nfunction deliveryContext(\n intent: AnnouncementIntent,\n): Pick<\n DOMDeliveryResult,\n | \"announcementId\"\n | \"sourceType\"\n | \"at\"\n | \"sourceEventId\"\n | \"responseId\"\n | \"toolId\"\n | \"interactionId\"\n | \"runId\"\n | \"runInstanceId\"\n | \"stepId\"\n | \"stepInstanceId\"\n> {\n return {\n announcementId: intent.id,\n sourceType: intent.sourceType,\n at: intent.at,\n ...(intent.sourceEventId !== undefined\n ? { sourceEventId: intent.sourceEventId }\n : {}),\n ...(intent.responseId !== undefined\n ? { responseId: intent.responseId }\n : {}),\n ...(intent.toolId !== undefined ? { toolId: intent.toolId } : {}),\n ...(intent.interactionId !== undefined\n ? { interactionId: intent.interactionId }\n : {}),\n ...(intent.runId !== undefined ? { runId: intent.runId } : {}),\n ...(intent.runInstanceId !== undefined\n ? { runInstanceId: intent.runInstanceId }\n : {}),\n ...(intent.stepId !== undefined ? { stepId: intent.stepId } : {}),\n ...(intent.stepInstanceId !== undefined\n ? { stepInstanceId: intent.stepInstanceId }\n : {}),\n };\n}\n\nfunction validateSuppliedRegions(options: DOMAnnouncerOptions): void {\n if (options.regions === undefined) return;\n const { polite, assertive } = options.regions;\n if (polite === assertive) {\n throw new TypeError(\n \"Polite and assertive regions must be distinct elements\",\n );\n }\n if (!polite.isConnected || !assertive.isConnected) {\n throw new TypeError(\"Supplied regions must be connected\");\n }\n if (polite.contains(assertive) || assertive.contains(polite)) {\n throw new TypeError(\n \"Polite and assertive regions must not contain one another\",\n );\n }\n if (polite.ownerDocument !== assertive.ownerDocument) {\n throw new TypeError(\n \"Polite and assertive regions must belong to the same document\",\n );\n }\n if (\n options.document !== undefined &&\n (polite.ownerDocument !== options.document ||\n assertive.ownerDocument !== options.document)\n ) {\n throw new TypeError(\n \"Supplied regions must belong to the provided document\",\n );\n }\n}\n\nfunction serializeError(\n error: unknown,\n): NonNullable<DOMDeliveryResult[\"error\"]> {\n try {\n if (error instanceof Error) {\n return {\n name: readErrorString(error, \"name\", \"Error\"),\n message: readErrorString(error, \"message\", \"Unknown error\"),\n };\n }\n } catch {\n // Hostile proxies can throw during instanceof checks.\n }\n return { name: \"Error\", message: safeString(error, \"Unknown error\") };\n}\n\nfunction readErrorString(\n error: Error,\n property: \"name\" | \"message\",\n fallback: string,\n): string {\n try {\n return safeString(error[property], fallback);\n } catch {\n return fallback;\n }\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\ninterface AriaNotifyRegion extends HTMLElement {\n ariaNotify?: (\n text: string,\n options?: { priority: \"normal\" | \"high\" },\n ) => void;\n}\n\nfunction createLiveRegions(\n selectedDocument: Document | undefined,\n): DOMLiveRegions | undefined {\n const parent = selectedDocument?.body ?? selectedDocument?.documentElement;\n if (!selectedDocument || !parent) return undefined;\n\n const regions = {\n polite: selectedDocument.createElement(\"div\"),\n assertive: selectedDocument.createElement(\"div\"),\n };\n parent.append(regions.polite, regions.assertive);\n return regions;\n}\n\nfunction configureRegion(\n region: HTMLElement,\n channel: AnnouncementIntent[\"channel\"],\n): void {\n region.removeAttribute(\"role\");\n region.removeAttribute(\"aria-busy\");\n region.removeAttribute(\"hidden\");\n region.removeAttribute(\"aria-hidden\");\n region.inert = false;\n region.removeAttribute(\"inert\");\n region.style.removeProperty(\"display\");\n region.style.removeProperty(\"visibility\");\n region.style.removeProperty(\"content-visibility\");\n region.setAttribute(\"aria-live\", channel);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(\"aria-relevant\", \"additions text\");\n Object.assign(region.style, {\n position: \"absolute\",\n width: \"1px\",\n height: \"1px\",\n padding: \"0\",\n margin: \"-1px\",\n overflow: \"hidden\",\n clip: \"rect(0, 0, 0, 0)\",\n whiteSpace: \"nowrap\",\n border: \"0\",\n });\n}\n\nfunction applyLocale(region: HTMLElement, locale: string | undefined): void {\n if (locale === undefined) region.removeAttribute(\"lang\");\n else region.setAttribute(\"lang\", locale);\n}\n\nexport function connectRuntimeToDOM(\n runtime: GenerativeA11yRuntime,\n options: DOMAnnouncerOptions = {},\n): DOMRuntimeBinding {\n const announcer = createDOMAnnouncer(options);\n let disposed = false;\n let unsubscribe: () => void;\n try {\n unsubscribe = runtime.subscribeAnnouncements((intent) => {\n if (!disposed) announcer.announce(intent);\n });\n } catch (cause) {\n announcer.dispose();\n throw cause;\n }\n\n return {\n announcer,\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n unsubscribe();\n } finally {\n announcer.dispose();\n }\n },\n };\n}\n"],"mappings":";AAAO,SAAS,kBAAkBA,WAAoC;AACpE,MAAI,SAASA,UAAS;AACtB,QAAM,UAAU,oBAAI,IAAa;AACjC,SAAO,QAAQ;AACb,QAAI,QAAQ,IAAI,MAAM,EAAG,OAAM,IAAI,MAAM,uBAAuB;AAChE,YAAQ,IAAI,MAAM;AAClB,UAAM,SAAU,OACb;AACH,UAAM,SAAS,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ACT,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,QAAQ;AAAA,EACV,CAAC;AACH;AAEA,SAAS,YAAY,QAAqB,QAAkC;AAC1E,MAAI,WAAW,OAAW,QAAO,gBAAgB,MAAM;AAAA,MAClD,QAAO,aAAa,QAAQ,MAAM;AACzC;AAEO,SAAS,oBACd,SACA,UAA+B,CAAC,GACb;AACnB,QAAM,YAAY,mBAAmB,OAAO;AAC5C,MAAI,WAAW;AACf,MAAI;AACJ,MAAI;AACF,kBAAc,QAAQ,uBAAuB,CAAC,WAAW;AACvD,UAAI,CAAC,SAAU,WAAU,SAAS,MAAM;AAAA,IAC1C,CAAC;AAAA,EACH,SAAS,OAAO;AACd,cAAU,QAAQ;AAClB,UAAM;AAAA,EACR;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AACR,UAAI,SAAU;AACd,iBAAW;AACX,UAAI;AACF,oBAAY;AAAA,MACd,UAAE;AACA,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;","names":["document","document","window","document","serializeError"]}
|
|
1
|
+
{"version":3,"sources":["../src/attention-binding.ts","../src/composed-tree.ts","../src/attention.ts","../src/focus.ts","../src/preferences.ts","../src/index.ts"],"sourcesContent":["import type { Runtime } from \"@generative-a11y/core\";\nimport type { AttentionSnapshot, AttentionStore } from \"./attention.js\";\n\nexport interface AttentionBindingOptions {\n readonly runtime: Runtime;\n readonly attentionStore: AttentionStore;\n}\n\nexport interface AttentionBinding {\n dispose(): void;\n}\n\nconst boundRuntimes = new WeakSet<Runtime>();\n\n/** Borrow a store and runtime, forwarding observations without changing overrides. */\nexport function bindAttention({\n runtime,\n attentionStore,\n}: AttentionBindingOptions): AttentionBinding {\n if (boundRuntimes.has(runtime)) {\n throw new Error(\"Runtime already has an attention binding\");\n }\n // Claim before invoking any external code, including store accessors.\n boundRuntimes.add(runtime);\n let active = true;\n let unsubscribe: (() => void) | undefined;\n let lastMode: AttentionSnapshot[\"mode\"] | undefined;\n let revision = 0;\n const update = () => {\n if (!active) return;\n const readRevision = ++revision;\n const mode = attentionStore.getSnapshot().mode;\n if (!active || revision !== readRevision || mode === lastMode) return;\n lastMode = mode;\n runtime.dispatch({ type: \"attention.changed\", mode });\n };\n const dispose = () => {\n if (!active) return;\n active = false;\n try {\n try {\n unsubscribe?.();\n } catch {\n // A throwing borrowed store cannot prevent observation reset.\n }\n if (lastMode !== undefined) {\n runtime.dispatch({ type: \"attention.changed\", mode: \"unknown\" });\n }\n } finally {\n boundRuntimes.delete(runtime);\n }\n };\n try {\n unsubscribe = attentionStore.subscribe(update);\n update();\n } catch (error) {\n try {\n dispose();\n } catch {\n // Preserve the original construction error.\n }\n throw error;\n }\n return { dispose };\n}\n","export function deepActiveElement(document: Document): Element | null {\n let active = document.activeElement;\n const visited = new Set<Element>();\n while (active) {\n if (visited.has(active)) throw new Error(\"Cyclic active element\");\n visited.add(active);\n const shadow = (active as Element & { shadowRoot?: ShadowRoot | null })\n .shadowRoot;\n const nested = shadow?.activeElement;\n if (!nested) return active;\n active = nested;\n }\n return null;\n}\n\nexport function composedContains(ancestor: Element, target: Element): boolean {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (current === ancestor) return true;\n if (visited.has(current)) throw new Error(\"Cyclic composed tree\");\n visited.add(current);\n current = composedParent(current);\n }\n return false;\n}\n\nexport function composedParent(element: Element): Element | null {\n const assignedSlot = (\n element as Element & { assignedSlot?: HTMLSlotElement | null }\n ).assignedSlot;\n if (assignedSlot) return assignedSlot;\n if (element.parentElement) return element.parentElement;\n const root = element.getRootNode();\n if (root && \"host\" in root) {\n const host = (root as ShadowRoot).host;\n if (host.ownerDocument === element.ownerDocument) return host;\n }\n return null;\n}\n","import { composedContains, deepActiveElement } from \"./composed-tree.js\";\n\nexport interface ExternalStore<T> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): T;\n getServerSnapshot(): T;\n}\n\nexport interface AttentionSnapshot {\n readonly visibility: \"visible\" | \"hidden\" | \"unknown\";\n readonly windowFocus: \"focused\" | \"blurred\" | \"unknown\";\n readonly focusArea:\n \"composer\" | \"conversation\" | \"elsewhere\" | \"none\" | \"unknown\";\n readonly newestResponse: \"visible\" | \"outside\" | \"unobserved\" | \"unknown\";\n readonly mode:\n \"foreground\" | \"background\" | \"reading-history\" | \"away\" | \"unknown\";\n}\n\nexport interface AttentionStore extends ExternalStore<AttentionSnapshot> {\n registerComposer(element: Element): () => void;\n registerConversation(element: Element): () => void;\n registerNewestResponse(element: Element): () => void;\n dispose(): void;\n}\n\nexport interface AttentionStoreOptions {\n document?: Document;\n createIntersectionObserver?: AttentionIntersectionObserverFactory;\n intersectionObserverInit?: IntersectionObserverInit;\n}\n\nexport interface AttentionIntersectionObserver {\n observe(target: Element): void;\n unobserve(target: Element): void;\n disconnect(): void;\n}\n\nexport type AttentionIntersectionObserverFactory = (\n callback: IntersectionObserverCallback,\n options?: IntersectionObserverInit,\n) => AttentionIntersectionObserver;\n\nconst UNKNOWN_SNAPSHOT: AttentionSnapshot = Object.freeze({\n visibility: \"unknown\",\n windowFocus: \"unknown\",\n focusArea: \"unknown\",\n newestResponse: \"unknown\",\n mode: \"unknown\",\n});\n\nexport function createAttentionStore(\n options: AttentionStoreOptions = {},\n): AttentionStore {\n const selectedDocument =\n options.document ??\n (typeof document === \"undefined\" ? undefined : document);\n if (!selectedDocument) {\n return {\n subscribe: () => () => undefined,\n getSnapshot: () => UNKNOWN_SNAPSHOT,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: () => () => undefined,\n registerConversation: () => () => undefined,\n registerNewestResponse: () => () => undefined,\n dispose: () => undefined,\n };\n }\n\n const listeners = new Set<() => void>();\n const composers = new Map<Element, number>();\n const conversations = new Map<Element, number>();\n const selectedWindow = selectedDocument.defaultView;\n let disposed = false;\n let newestTarget: Element | undefined;\n let newestResult: AttentionSnapshot[\"newestResponse\"] = \"unobserved\";\n let newestRegistration = 0;\n let observer: AttentionIntersectionObserver | undefined;\n let snapshot = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n const update = () => {\n if (disposed) return;\n const next = makeSnapshot(\n selectedDocument,\n composers,\n conversations,\n newestResult,\n );\n if (sameSnapshot(snapshot, next)) return;\n snapshot = next;\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store observers cannot prevent other observers from running.\n }\n }\n };\n const handleFocusOut = (event: FocusEvent) => {\n if (event.relatedTarget === null) update();\n };\n const listenerCleanups: Array<() => void> = [];\n const installListener = (install: () => void, cleanup: () => void): void => {\n // Register cleanup first because a hostile EventTarget can install and then\n // throw from addEventListener(). Removing a listener that was not installed\n // is harmless, while omitting cleanup would leak the accepted listener.\n listenerCleanups.push(cleanup);\n install();\n };\n const cleanupListeners = (): void => {\n for (const cleanup of listenerCleanups.splice(0).reverse()) {\n try {\n cleanup();\n } catch {\n // One hostile removal cannot strand the remaining listeners.\n }\n }\n };\n try {\n installListener(\n () => selectedDocument.addEventListener(\"visibilitychange\", update),\n () => selectedDocument.removeEventListener(\"visibilitychange\", update),\n );\n if (selectedWindow) {\n installListener(\n () => selectedWindow.addEventListener(\"focus\", update),\n () => selectedWindow.removeEventListener(\"focus\", update),\n );\n installListener(\n () => selectedWindow.addEventListener(\"blur\", update),\n () => selectedWindow.removeEventListener(\"blur\", update),\n );\n }\n installListener(\n () => selectedDocument.addEventListener(\"focusin\", update),\n () => selectedDocument.removeEventListener(\"focusin\", update),\n );\n installListener(\n () => selectedDocument.addEventListener(\"focusout\", handleFocusOut),\n () => selectedDocument.removeEventListener(\"focusout\", handleFocusOut),\n );\n } catch (error) {\n cleanupListeners();\n throw error;\n }\n\n const register = (\n elements: Map<Element, number>,\n element: Element,\n ): (() => void) => {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n elements.set(element, (elements.get(element) ?? 0) + 1);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n const remaining = (elements.get(element) ?? 1) - 1;\n if (remaining === 0) elements.delete(element);\n else elements.set(element, remaining);\n update();\n };\n };\n\n const createChatObserver = (\n registration: number,\n target: Element,\n ): AttentionIntersectionObserver | undefined => {\n const factory =\n options.createIntersectionObserver ??\n defaultIntersectionObserverFactory(selectedWindow);\n if (!factory) return undefined;\n let created: AttentionIntersectionObserver | undefined;\n try {\n created = factory((entries) => {\n if (\n disposed ||\n registration !== newestRegistration ||\n newestTarget !== target ||\n observer !== created\n ) {\n return;\n }\n let latest: IntersectionObserverEntry | undefined;\n for (const entry of entries) {\n if (entry.target === target) latest = entry;\n }\n if (!latest) return;\n newestResult = latest.isIntersecting ? \"visible\" : \"outside\";\n update();\n }, options.intersectionObserverInit);\n created.observe(target);\n return created;\n } catch {\n cleanupObserver(created, target);\n return undefined;\n }\n };\n\n const stopObserver = (target?: Element): void => {\n const current = observer;\n observer = undefined;\n cleanupObserver(current, target);\n };\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n getServerSnapshot: () => UNKNOWN_SNAPSHOT,\n registerComposer: (element) => register(composers, element),\n registerConversation: (element) => register(conversations, element),\n registerNewestResponse(element) {\n if (disposed) throw new Error(\"AttentionStore is disposed\");\n const registration = ++newestRegistration;\n stopObserver(newestTarget);\n newestTarget = element;\n newestResult = \"unknown\";\n observer = createChatObserver(registration, element);\n update();\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n if (registration !== newestRegistration || newestTarget !== element)\n return;\n stopObserver(element);\n newestTarget = undefined;\n newestResult = \"unobserved\";\n update();\n };\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n listeners.clear();\n composers.clear();\n conversations.clear();\n stopObserver(newestTarget);\n newestTarget = undefined;\n cleanupListeners();\n },\n };\n}\n\nfunction makeSnapshot(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot {\n const visibility = readVisibility(document);\n const windowFocus = readWindowFocus(document);\n return Object.freeze({\n visibility,\n windowFocus,\n focusArea: readFocusArea(document, composers, conversations),\n newestResponse,\n mode: deriveMode(visibility, windowFocus, newestResponse),\n });\n}\n\nfunction deriveMode(\n visibility: AttentionSnapshot[\"visibility\"],\n windowFocus: AttentionSnapshot[\"windowFocus\"],\n newestResponse: AttentionSnapshot[\"newestResponse\"],\n): AttentionSnapshot[\"mode\"] {\n if (visibility === \"hidden\") return \"background\";\n if (visibility !== \"visible\") return \"unknown\";\n if (windowFocus === \"blurred\") return \"away\";\n if (windowFocus !== \"focused\") return \"unknown\";\n if (newestResponse === \"outside\") return \"reading-history\";\n if (newestResponse === \"visible\") return \"foreground\";\n return \"unknown\";\n}\n\nfunction defaultIntersectionObserverFactory(\n window: (Window & typeof globalThis) | null,\n): AttentionIntersectionObserverFactory | undefined {\n const Constructor = window?.IntersectionObserver;\n if (typeof Constructor !== \"function\") return undefined;\n return (callback, options) => new Constructor(callback, options);\n}\n\nfunction cleanupObserver(\n observer: AttentionIntersectionObserver | undefined,\n target?: Element,\n): void {\n if (!observer) return;\n if (target) {\n try {\n observer.unobserve(target);\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n }\n try {\n observer.disconnect();\n } catch {\n // Intersection cleanup errors are deliberately suppressed.\n }\n}\n\nfunction readFocusArea(\n document: Document,\n composers: ReadonlyMap<Element, number>,\n conversations: ReadonlyMap<Element, number>,\n): AttentionSnapshot[\"focusArea\"] {\n let activeElement: Element | null;\n try {\n activeElement = deepActiveElement(document);\n } catch {\n return \"unknown\";\n }\n if (\n activeElement === null ||\n activeElement === document.body ||\n activeElement === document.documentElement\n ) {\n return \"none\";\n }\n if (\n [...composers.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"composer\";\n }\n if (\n [...conversations.keys()].some((element) =>\n composedContains(element, activeElement),\n )\n ) {\n return \"conversation\";\n }\n return \"elsewhere\";\n}\n\nfunction readVisibility(document: Document): AttentionSnapshot[\"visibility\"] {\n try {\n if (document.visibilityState === \"visible\") return \"visible\";\n if (document.visibilityState === \"hidden\") return \"hidden\";\n } catch {\n // Browser integrations can expose throwing accessors.\n }\n return \"unknown\";\n}\n\nfunction readWindowFocus(document: Document): AttentionSnapshot[\"windowFocus\"] {\n try {\n if (typeof document.hasFocus !== \"function\") return \"unknown\";\n return document.hasFocus() ? \"focused\" : \"blurred\";\n } catch {\n return \"unknown\";\n }\n}\n\nfunction sameSnapshot(\n left: AttentionSnapshot,\n right: AttentionSnapshot,\n): boolean {\n return (\n left.visibility === right.visibility &&\n left.windowFocus === right.windowFocus &&\n left.focusArea === right.focusArea &&\n left.newestResponse === right.newestResponse &&\n left.mode === right.mode\n );\n}\n","import {\n composedContains,\n composedParent,\n deepActiveElement,\n} from \"./composed-tree.js\";\n\nexport interface FocusCapture {\n readonly document: Document | null;\n readonly target: Element | null;\n}\n\nexport interface FocusElementOptions {\n preventScroll?: boolean;\n}\n\nexport interface RestoreFocusOptions extends FocusElementOptions {\n onlyIfFocusWithin?: Element;\n}\n\nexport type FocusSkippedReason =\n | \"unavailable\"\n | \"cross-document\"\n | \"disconnected\"\n | \"disabled\"\n | \"hidden\"\n | \"aria-hidden\"\n | \"inert\"\n | \"missing-focus\"\n | \"guard-mismatch\"\n | \"focus-error\"\n | \"focus-not-applied\";\n\nexport type FocusResult =\n | { readonly status: \"focused\"; readonly target: Element }\n | {\n readonly status: \"skipped\";\n readonly reason: FocusSkippedReason;\n readonly target: Element | null;\n };\n\nexport function captureFocus(selectedDocument?: Document): FocusCapture {\n const document =\n selectedDocument ??\n (typeof globalThis.document === \"undefined\"\n ? undefined\n : globalThis.document);\n if (!document) return Object.freeze({ document: null, target: null });\n let target: Element | null = null;\n try {\n const active = deepActiveElement(document);\n if (\n active !== null &&\n active !== document.body &&\n active !== document.documentElement &&\n active.ownerDocument === document\n ) {\n target = active;\n }\n } catch {\n // A hostile document is captured without a restorable target.\n }\n return Object.freeze({ document, target });\n}\n\nexport function focusElement(\n target: Element,\n options: FocusElementOptions = {},\n): FocusResult {\n const eligibility = focusEligibility(target);\n if (eligibility) {\n return { status: \"skipped\", reason: eligibility, target };\n }\n let focus: ((options?: FocusOptions) => void) | undefined;\n let document: Document;\n let previous: Element | null;\n try {\n document = target.ownerDocument;\n previous = deepActiveElement(document);\n focus = (target as Element & { focus?: (options?: FocusOptions) => void })\n .focus;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target };\n }\n if (typeof focus !== \"function\") {\n return { status: \"skipped\", reason: \"missing-focus\", target };\n }\n let focusThrew = false;\n try {\n focus.call(target, { preventScroll: options.preventScroll ?? true });\n } catch {\n focusThrew = true;\n }\n if (focusThrew) {\n restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n const postFocusEligibility = focusEligibility(target);\n let active: Element | null;\n try {\n active = deepActiveElement(document);\n } catch {\n return { status: \"skipped\", reason: \"focus-error\", target };\n }\n if (postFocusEligibility) {\n if (active === target) restorePreviousFocus(previous, target, document);\n return { status: \"skipped\", reason: postFocusEligibility, target };\n }\n if (active !== target) {\n return { status: \"skipped\", reason: \"focus-not-applied\", target };\n }\n return { status: \"focused\", target };\n}\n\nexport function restoreFocus(\n capture: FocusCapture,\n options: RestoreFocusOptions = {},\n): FocusResult {\n let document: Document | null;\n let target: Element | null;\n try {\n document = capture.document;\n target = capture.target;\n } catch {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n if (!document || !target) {\n return { status: \"skipped\", reason: \"unavailable\", target: null };\n }\n try {\n if (target.ownerDocument !== document) {\n return { status: \"skipped\", reason: \"cross-document\", target };\n }\n const guard = options.onlyIfFocusWithin;\n if (guard !== undefined) {\n const active = deepActiveElement(document);\n if (\n guard.ownerDocument !== document ||\n active === null ||\n !composedContains(guard, active)\n ) {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n }\n } catch {\n return { status: \"skipped\", reason: \"guard-mismatch\", target };\n }\n return focusElement(target, options);\n}\n\nfunction focusEligibility(target: Element): FocusSkippedReason | undefined {\n let ownerDocument: Document;\n try {\n ownerDocument = target.ownerDocument;\n const ElementConstructor = ownerDocument.defaultView?.Element;\n if (\n !ownerDocument ||\n (ElementConstructor && !(target instanceof ElementConstructor))\n ) {\n return \"unavailable\";\n }\n if (target.isConnected !== true) return \"disconnected\";\n if (\n target.getAttribute(\"disabled\") !== null ||\n (target as Element & { disabled?: unknown }).disabled === true\n ) {\n return \"disabled\";\n }\n } catch {\n return \"unavailable\";\n }\n try {\n const matches = target.matches;\n if (typeof matches === \"function\" && matches.call(target, \":disabled\")) {\n return \"disabled\";\n }\n } catch {\n // Fall back to the direct disabled checks above.\n }\n\n try {\n let current: Element | null = target;\n const visited = new Set<Element>();\n while (current) {\n if (visited.has(current)) return \"unavailable\";\n visited.add(current);\n if (current.hasAttribute(\"hidden\")) return \"hidden\";\n if (current.getAttribute(\"aria-hidden\")?.trim().toLowerCase() === \"true\")\n return \"aria-hidden\";\n if (\n current.hasAttribute(\"inert\") ||\n (current as Element & { inert?: unknown }).inert === true\n ) {\n return \"inert\";\n }\n current = composedParent(current);\n }\n } catch {\n return \"unavailable\";\n }\n\n try {\n const focus = (\n target as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus !== \"function\") return \"missing-focus\";\n } catch {\n return \"unavailable\";\n }\n return undefined;\n}\n\nfunction restorePreviousFocus(\n previous: Element | null,\n attempted: Element,\n document: Document,\n): void {\n try {\n if (\n !previous ||\n deepActiveElement(document) !== attempted ||\n focusEligibility(previous) !== undefined\n ) {\n return;\n }\n const focus = (\n previous as Element & {\n focus?: (options?: FocusOptions) => void;\n }\n ).focus;\n if (typeof focus === \"function\")\n focus.call(previous, { preventScroll: true });\n } catch {\n // Focus rollback is best-effort at hostile DOM boundaries.\n }\n}\n","import type { PolicyOverrides, PresetName } from \"@generative-a11y/core\";\n\nimport type { ExternalStore } from \"./attention.js\";\n\nexport type StreamingVerbosity =\n \"preset\" | \"off\" | \"completion\" | \"paragraph\" | \"sentence\";\n\nexport type ToolVerbosity =\n \"preset\" | \"off\" | \"failures\" | \"status\" | \"progress\";\n\nexport type PreferenceSchemaV1 =\n | Readonly<{ version: 1; preset: \"completion-only\" }>\n | Readonly<{\n version: 1;\n preset: \"minimal\" | \"balanced\" | \"verbose\";\n streaming: StreamingVerbosity;\n tools: ToolVerbosity;\n }>;\n\nexport interface PreferenceStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nexport interface PreferenceStorageEvent {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly storageArea?: PreferenceStorage | null;\n}\n\nexport interface PreferenceStorageEventSource {\n subscribe(listener: (event: PreferenceStorageEvent) => void): () => void;\n}\n\nexport type PreferenceDiagnosticSource =\n | \"storage-read\"\n | \"storage-write\"\n | \"storage-event\"\n | \"event-subscribe\"\n | \"event-unsubscribe\";\n\nexport type PreferenceDiagnosticCode =\n | \"operation-failed\"\n | \"invalid-json\"\n | \"invalid-preference\"\n | \"unsupported-version\";\n\nexport interface PreferenceDiagnostic {\n readonly source: PreferenceDiagnosticSource;\n readonly code: PreferenceDiagnosticCode;\n readonly error?: Readonly<{ name: string; message: string }>;\n}\n\nexport interface PreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nexport interface PreferenceStoreOptions {\n readonly defaultValue?: PreferenceSchemaV1;\n readonly persistence?: PreferencePersistence;\n readonly onDiagnostic?: (diagnostic: PreferenceDiagnostic) => void;\n}\n\nexport interface PreferenceStore extends ExternalStore<PreferenceSchemaV1> {\n setPreferences(value: PreferenceSchemaV1): void;\n dispose(): void;\n}\n\nexport interface CorePreferenceConfiguration {\n readonly preset: PresetName;\n readonly policy?: PolicyOverrides;\n}\n\nexport const defaultPreferences: PreferenceSchemaV1 = Object.freeze({\n version: 1,\n preset: \"balanced\",\n streaming: \"preset\",\n tools: \"preset\",\n});\n\nexport function preferencesToCoreConfiguration(\n value: PreferenceSchemaV1,\n): CorePreferenceConfiguration {\n const preferences = normalizePreferences(value);\n if (preferences.preset === \"completion-only\") {\n return { preset: \"completion-only\" };\n }\n const policy: PolicyOverrides = {};\n const text = mapStreaming(preferences.streaming);\n const tools = mapTools(preferences.tools);\n if (text) policy.text = text;\n if (tools) policy.tools = tools;\n return Object.keys(policy).length === 0\n ? { preset: preferences.preset }\n : { preset: preferences.preset, policy };\n}\n\nexport function createPreferenceStore(\n options: PreferenceStoreOptions = {},\n): PreferenceStore {\n const configuredDefault = options.defaultValue\n ? normalizePreferences(options.defaultValue)\n : defaultPreferences;\n const persistence = resolvePersistence(options.persistence);\n const report = (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ): void => {\n const diagnostic: PreferenceDiagnostic = {\n source,\n code,\n ...(cause === undefined ? {} : { error: serializeError(cause) }),\n };\n try {\n options.onDiagnostic?.(diagnostic);\n } catch {\n // Diagnostics are observational.\n }\n };\n let current = configuredDefault;\n if (persistence?.storage) {\n try {\n const stored = persistence.storage.getItem(persistence.key);\n if (stored !== null) {\n current = parsePreferences(stored, \"storage-read\", report) ?? current;\n }\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n }\n let disposed = false;\n let eventEpoch = 0;\n const listeners = new Set<() => void>();\n let unsubscribeEvents: (() => void) | undefined;\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // External-store listeners cannot prevent other listeners.\n }\n }\n };\n const replace = (next: PreferenceSchemaV1): boolean => {\n if (samePreferences(current, next)) return false;\n current = next;\n notify();\n return true;\n };\n const handleStorageEvent = (event: PreferenceStorageEvent): void => {\n if (disposed || !persistence) return;\n const epoch = ++eventEpoch;\n let key: string | null;\n let newValue: string | null;\n let storageArea: PreferenceStorage | null | undefined;\n try {\n key = event.key;\n newValue = event.newValue;\n storageArea = event.storageArea;\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n return;\n }\n if (disposed || epoch !== eventEpoch) return;\n try {\n if (storageArea != null && storageArea !== persistence.storage) {\n return;\n }\n if (key !== null && key !== persistence.key) return;\n if (key === null || newValue === null) {\n replace(configuredDefault);\n return;\n }\n const next = parsePreferences(newValue, \"storage-event\", report);\n if (!disposed && epoch === eventEpoch && next) replace(next);\n } catch (cause) {\n if (!disposed && epoch === eventEpoch) {\n report(\"storage-event\", \"operation-failed\", cause);\n }\n }\n };\n\n if (persistence?.events) {\n try {\n unsubscribeEvents = persistence.events.subscribe(handleStorageEvent);\n } catch (cause) {\n report(\"event-subscribe\", \"operation-failed\", cause);\n }\n }\n\n return {\n subscribe(listener) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed) return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n getSnapshot: () => current,\n getServerSnapshot: () => configuredDefault,\n setPreferences(value) {\n if (disposed) throw new Error(\"PreferenceStore is disposed\");\n const next = normalizePreferences(value);\n const changed = replace(next);\n if (!disposed && persistence?.storage && samePreferences(current, next)) {\n const serialized = JSON.stringify(next);\n if (!changed) {\n const epoch = eventEpoch;\n let matchesStoredValue = false;\n try {\n matchesStoredValue =\n persistence.storage.getItem(persistence.key) === serialized;\n } catch (cause) {\n report(\"storage-read\", \"operation-failed\", cause);\n }\n if (\n matchesStoredValue ||\n disposed ||\n epoch !== eventEpoch ||\n !samePreferences(current, next)\n ) {\n return;\n }\n }\n if (disposed || !samePreferences(current, next)) return;\n try {\n persistence.storage.setItem(persistence.key, serialized);\n } catch (cause) {\n report(\"storage-write\", \"operation-failed\", cause);\n }\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n eventEpoch += 1;\n listeners.clear();\n const unsubscribe = unsubscribeEvents;\n unsubscribeEvents = undefined;\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch (cause) {\n report(\"event-unsubscribe\", \"operation-failed\", cause);\n }\n }\n },\n };\n}\n\ninterface ResolvedPreferencePersistence {\n readonly key: string;\n readonly storage?: PreferenceStorage;\n readonly events?: PreferenceStorageEventSource;\n}\n\nfunction resolvePersistence(\n persistence: PreferencePersistence | undefined,\n): ResolvedPreferencePersistence | undefined {\n if (!persistence) return undefined;\n if (persistence.storage) return persistence;\n const browser = getBrowserPersistence();\n return {\n key: persistence.key,\n ...(browser?.storage ? { storage: browser.storage } : {}),\n ...(persistence.events\n ? { events: persistence.events }\n : browser?.events\n ? { events: browser.events }\n : {}),\n };\n}\n\nfunction getBrowserPersistence():\n | { storage: PreferenceStorage; events: PreferenceStorageEventSource }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n const browserWindow = window;\n const storage = browserWindow.localStorage;\n if (!storage) return undefined;\n return {\n storage,\n events: {\n subscribe(listener) {\n const handle = (event: StorageEvent): void => listener(event);\n browserWindow.addEventListener(\"storage\", handle);\n return () => browserWindow.removeEventListener(\"storage\", handle);\n },\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction parsePreferences(\n raw: string,\n source: \"storage-read\" | \"storage-event\",\n report: (\n source: PreferenceDiagnosticSource,\n code: PreferenceDiagnosticCode,\n cause?: unknown,\n ) => void,\n): PreferenceSchemaV1 | undefined {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch (cause) {\n report(source, \"invalid-json\", cause);\n return undefined;\n }\n try {\n return normalizePreferences(value as PreferenceSchemaV1);\n } catch (cause) {\n report(\n source,\n cause instanceof UnsupportedPreferenceVersionError\n ? \"unsupported-version\"\n : \"invalid-preference\",\n cause,\n );\n return undefined;\n }\n}\n\nclass UnsupportedPreferenceVersionError extends TypeError {}\n\nexport function normalizePreferences(\n value: PreferenceSchemaV1,\n): PreferenceSchemaV1 {\n const fields = snapshotPreferenceFields(value);\n if (fields.version !== 1)\n throw new UnsupportedPreferenceVersionError(\n \"Unsupported preference version\",\n );\n if (fields.preset === \"completion-only\") {\n if (!hasExactKeys(fields, [\"version\", \"preset\"]))\n throw new TypeError(\"Invalid completion-only preferences\");\n return Object.freeze({ version: 1, preset: \"completion-only\" });\n }\n if (\n !([\"minimal\", \"balanced\", \"verbose\"] as unknown[]).includes(fields.preset)\n )\n throw new TypeError(\"Invalid preference preset\");\n if (!hasExactKeys(fields, [\"version\", \"preset\", \"streaming\", \"tools\"]))\n throw new TypeError(\"Invalid preference fields\");\n if (!STREAMING_VALUES.includes(fields.streaming as StreamingVerbosity))\n throw new TypeError(\"Invalid streaming preference\");\n if (!TOOL_VALUES.includes(fields.tools as ToolVerbosity))\n throw new TypeError(\"Invalid tool preference\");\n return Object.freeze({\n version: 1,\n preset: fields.preset as \"minimal\" | \"balanced\" | \"verbose\",\n streaming: fields.streaming as StreamingVerbosity,\n tools: fields.tools as ToolVerbosity,\n });\n}\n\nconst STREAMING_VALUES: readonly StreamingVerbosity[] = [\n \"preset\",\n \"off\",\n \"completion\",\n \"paragraph\",\n \"sentence\",\n];\nconst TOOL_VALUES: readonly ToolVerbosity[] = [\n \"preset\",\n \"off\",\n \"failures\",\n \"status\",\n \"progress\",\n];\n\nfunction snapshotPreferenceFields(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(\"Invalid preferences\");\n }\n try {\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const fields = Object.create(null) as Record<string, unknown>;\n for (const key of Reflect.ownKeys(descriptors)) {\n if (typeof key !== \"string\")\n throw new TypeError(\"Invalid preference fields\");\n const descriptor = descriptors[key];\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) {\n throw new TypeError(\n \"Preference fields must be enumerable data properties\",\n );\n }\n fields[key] = descriptor.value;\n }\n return fields;\n } catch {\n throw new TypeError(\"Invalid preferences\");\n }\n}\n\nfunction hasExactKeys(\n value: Record<string, unknown>,\n expected: readonly string[],\n): boolean {\n const keys = Object.keys(value);\n return (\n keys.length === expected.length &&\n expected.every((key) => keys.includes(key))\n );\n}\n\nexport function samePreferences(\n left: PreferenceSchemaV1,\n right: PreferenceSchemaV1,\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction mapStreaming(\n value: StreamingVerbosity,\n): PolicyOverrides[\"text\"] | undefined {\n if (value === \"preset\") return undefined;\n if (value === \"off\") return { strategy: \"silent\" };\n if (value === \"completion\")\n return { strategy: \"completion\", minimumCharacters: 0, maximumDelayMs: 0 };\n return { strategy: value };\n}\n\nfunction mapTools(value: ToolVerbosity): PolicyOverrides[\"tools\"] | undefined {\n if (value === \"preset\") return undefined;\n return {\n announceStart: value === \"status\" || value === \"progress\",\n announceProgress: value === \"progress\",\n announceCompletion: value === \"status\" || value === \"progress\",\n announceFailure: value !== \"off\",\n };\n}\n\nfunction serializeError(cause: unknown): Readonly<{\n name: string;\n message: string;\n}> {\n const fallback = { name: \"Error\", message: \"Unknown error\" } as const;\n try {\n if (cause instanceof Error) {\n const name = cause.name;\n const message = cause.message;\n if (typeof name !== \"string\" || typeof message !== \"string\") {\n return fallback;\n }\n return { name: name || \"Error\", message };\n }\n if (\n typeof cause === \"string\" ||\n typeof cause === \"number\" ||\n typeof cause === \"boolean\" ||\n typeof cause === \"bigint\" ||\n typeof cause === \"symbol\"\n ) {\n return { name: \"Error\", message: String(cause) };\n }\n } catch {\n return fallback;\n }\n return fallback;\n}\n","export {\n bindAttention,\n type AttentionBinding,\n type AttentionBindingOptions,\n} from \"./attention-binding.js\";\n\nimport type { AnnouncementIntent, Runtime } from \"@generative-a11y/core\";\n\nexport {\n createAttentionStore,\n type AttentionIntersectionObserver,\n type AttentionIntersectionObserverFactory,\n type AttentionSnapshot,\n type AttentionStore,\n type AttentionStoreOptions,\n type ExternalStore,\n} from \"./attention.js\";\n\nexport {\n captureFocus,\n focusElement,\n restoreFocus,\n type FocusCapture,\n type FocusElementOptions,\n type FocusResult,\n type FocusSkippedReason,\n type RestoreFocusOptions,\n} from \"./focus.js\";\n\nexport {\n createPreferenceStore,\n defaultPreferences,\n normalizePreferences,\n preferencesToCoreConfiguration,\n type CorePreferenceConfiguration,\n type PreferenceDiagnostic,\n type PreferenceDiagnosticCode,\n type PreferenceDiagnosticSource,\n type PreferencePersistence,\n type PreferenceSchemaV1,\n type PreferenceStorage,\n type PreferenceStorageEvent,\n type PreferenceStorageEventSource,\n type PreferenceStore,\n type PreferenceStoreOptions,\n samePreferences,\n type StreamingVerbosity,\n type ToolVerbosity,\n} from \"./preferences.js\";\n\nexport type DeliveryMode = \"auto\" | \"live-region\";\n\nexport interface LiveRegions {\n polite: HTMLElement;\n assertive: HTMLElement;\n}\n\nexport interface DeliveryResult {\n status: \"notified\" | \"mutated\" | \"unavailable\" | \"disposed\";\n method: \"aria-notify\" | \"live-region\" | \"none\";\n channel: AnnouncementIntent[\"channel\"];\n announcementId: string;\n sourceType: AnnouncementIntent[\"sourceType\"];\n at: number;\n sourceEventId?: string;\n responseId?: string;\n toolId?: string;\n interactionId?: string;\n /** Stable logical run identity associated with the delivered intent. */\n runId?: string;\n /** Stable run attempt identity associated with the delivered intent. */\n runInstanceId?: string;\n /** Stable logical step identity associated with the delivered intent. */\n stepId?: string;\n /** Stable step attempt identity associated with the delivered intent. */\n stepInstanceId?: string;\n error?: { name: string; message: string };\n}\n\nexport interface AnnouncerOptions {\n document?: Document;\n mode?: DeliveryMode;\n regions?: LiveRegions;\n onDelivery?: (result: DeliveryResult) => void;\n}\n\nexport interface Announcer {\n announce(intent: AnnouncementIntent): DeliveryResult;\n getRegions(): LiveRegions | undefined;\n dispose(): void;\n}\n\nexport interface RuntimeBinding {\n announcer: Announcer;\n dispose(): void;\n}\n\nexport function createAnnouncer(options: AnnouncerOptions = {}): Announcer {\n if (\n options.mode !== undefined &&\n options.mode !== \"auto\" &&\n options.mode !== \"live-region\"\n )\n throw new TypeError('mode must be \"auto\" or \"live-region\"');\n validateSuppliedRegions(options);\n const selectedDocument =\n options.document ??\n options.regions?.polite.ownerDocument ??\n (typeof document === \"undefined\" ? undefined : document);\n const ownsRegions = options.regions === undefined;\n const regions = options.regions ?? createLiveRegions(selectedDocument);\n\n if (regions) {\n configureRegion(regions.polite, \"polite\");\n configureRegion(regions.assertive, \"assertive\");\n }\n let notifierEnabled = true;\n let disposed = false;\n\n const report = (result: DeliveryResult): DeliveryResult => {\n try {\n options.onDelivery?.(result);\n } catch {\n // Diagnostics are observational and cannot affect delivery.\n }\n return result;\n };\n\n return {\n announce(intent) {\n if (disposed) {\n return report({\n status: \"disposed\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n if (regions) {\n const region = regions[intent.channel];\n applyLocale(region, intent.locale);\n let error: DeliveryResult[\"error\"];\n if (notifierEnabled && options.mode !== \"live-region\") {\n let notified = false;\n try {\n const ariaNotify = (region as AriaNotifyRegion).ariaNotify;\n if (typeof ariaNotify === \"function\") {\n ariaNotify.call(region, intent.text, {\n priority: intent.channel === \"assertive\" ? \"high\" : \"normal\",\n });\n notified = true;\n }\n } catch (cause) {\n notifierEnabled = false;\n error = serializeError(cause);\n }\n if (notified) {\n return report({\n status: \"notified\",\n method: \"aria-notify\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n }\n }\n region.textContent = intent.text;\n return report({\n status: \"mutated\",\n method: \"live-region\",\n channel: intent.channel,\n ...deliveryContext(intent),\n ...(error === undefined ? {} : { error }),\n });\n }\n return report({\n status: \"unavailable\",\n method: \"none\",\n channel: intent.channel,\n ...deliveryContext(intent),\n });\n },\n getRegions() {\n return regions;\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n if (ownsRegions) {\n regions?.polite.remove();\n regions?.assertive.remove();\n }\n },\n };\n}\n\nfunction deliveryContext(\n intent: AnnouncementIntent,\n): Pick<\n DeliveryResult,\n | \"announcementId\"\n | \"sourceType\"\n | \"at\"\n | \"sourceEventId\"\n | \"responseId\"\n | \"toolId\"\n | \"interactionId\"\n | \"runId\"\n | \"runInstanceId\"\n | \"stepId\"\n | \"stepInstanceId\"\n> {\n return {\n announcementId: intent.id,\n sourceType: intent.sourceType,\n at: intent.at,\n ...(intent.sourceEventId !== undefined\n ? { sourceEventId: intent.sourceEventId }\n : {}),\n ...(intent.responseId !== undefined\n ? { responseId: intent.responseId }\n : {}),\n ...(intent.toolId !== undefined ? { toolId: intent.toolId } : {}),\n ...(intent.interactionId !== undefined\n ? { interactionId: intent.interactionId }\n : {}),\n ...(intent.runId !== undefined ? { runId: intent.runId } : {}),\n ...(intent.runInstanceId !== undefined\n ? { runInstanceId: intent.runInstanceId }\n : {}),\n ...(intent.stepId !== undefined ? { stepId: intent.stepId } : {}),\n ...(intent.stepInstanceId !== undefined\n ? { stepInstanceId: intent.stepInstanceId }\n : {}),\n };\n}\n\nfunction validateSuppliedRegions(options: AnnouncerOptions): void {\n if (options.regions === undefined) return;\n const { polite, assertive } = options.regions;\n if (polite === assertive) {\n throw new TypeError(\n \"Polite and assertive regions must be distinct elements\",\n );\n }\n if (!polite.isConnected || !assertive.isConnected) {\n throw new TypeError(\"Supplied regions must be connected\");\n }\n if (polite.contains(assertive) || assertive.contains(polite)) {\n throw new TypeError(\n \"Polite and assertive regions must not contain one another\",\n );\n }\n if (polite.ownerDocument !== assertive.ownerDocument) {\n throw new TypeError(\n \"Polite and assertive regions must belong to the same document\",\n );\n }\n if (\n options.document !== undefined &&\n (polite.ownerDocument !== options.document ||\n assertive.ownerDocument !== options.document)\n ) {\n throw new TypeError(\n \"Supplied regions must belong to the provided document\",\n );\n }\n}\n\nfunction serializeError(error: unknown): NonNullable<DeliveryResult[\"error\"]> {\n try {\n if (error instanceof Error) {\n return {\n name: readErrorString(error, \"name\", \"Error\"),\n message: readErrorString(error, \"message\", \"Unknown error\"),\n };\n }\n } catch {\n // Hostile proxies can throw during instanceof checks.\n }\n return { name: \"Error\", message: safeString(error, \"Unknown error\") };\n}\n\nfunction readErrorString(\n error: Error,\n property: \"name\" | \"message\",\n fallback: string,\n): string {\n try {\n return safeString(error[property], fallback);\n } catch {\n return fallback;\n }\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\ninterface AriaNotifyRegion extends HTMLElement {\n ariaNotify?: (\n text: string,\n options?: { priority: \"normal\" | \"high\" },\n ) => void;\n}\n\nfunction createLiveRegions(\n selectedDocument: Document | undefined,\n): LiveRegions | undefined {\n const parent = selectedDocument?.body ?? selectedDocument?.documentElement;\n if (!selectedDocument || !parent) return undefined;\n\n const regions = {\n polite: selectedDocument.createElement(\"div\"),\n assertive: selectedDocument.createElement(\"div\"),\n };\n parent.append(regions.polite, regions.assertive);\n return regions;\n}\n\nfunction configureRegion(\n region: HTMLElement,\n channel: AnnouncementIntent[\"channel\"],\n): void {\n region.removeAttribute(\"role\");\n region.removeAttribute(\"aria-busy\");\n region.removeAttribute(\"hidden\");\n region.removeAttribute(\"aria-hidden\");\n region.inert = false;\n region.removeAttribute(\"inert\");\n region.style.removeProperty(\"display\");\n region.style.removeProperty(\"visibility\");\n region.style.removeProperty(\"content-visibility\");\n region.setAttribute(\"aria-live\", channel);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.setAttribute(\"aria-relevant\", \"additions text\");\n Object.assign(region.style, {\n position: \"absolute\",\n width: \"1px\",\n height: \"1px\",\n padding: \"0\",\n margin: \"-1px\",\n overflow: \"hidden\",\n clip: \"rect(0, 0, 0, 0)\",\n whiteSpace: \"nowrap\",\n border: \"0\",\n });\n}\n\nfunction applyLocale(region: HTMLElement, locale: string | undefined): void {\n if (locale === undefined) region.removeAttribute(\"lang\");\n else region.setAttribute(\"lang\", locale);\n}\n\nexport function bindRuntime(\n runtime: Runtime,\n options: AnnouncerOptions = {},\n): RuntimeBinding {\n const announcer = createAnnouncer(options);\n let disposed = false;\n let unsubscribe: () => void;\n try {\n unsubscribe = runtime.subscribeAnnouncements((intent) => {\n if (!disposed) announcer.announce(intent);\n });\n } catch (cause) {\n announcer.dispose();\n throw cause;\n }\n\n return {\n announcer,\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n unsubscribe();\n } finally {\n announcer.dispose();\n }\n },\n };\n}\n"],"mappings":";AAYA,IAAM,gBAAgB,oBAAI,QAAiB;AAGpC,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AACF,GAA8C;AAC5C,MAAI,cAAc,IAAI,OAAO,GAAG;AAC9B,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,gBAAc,IAAI,OAAO;AACzB,MAAI,SAAS;AACb,MAAI;AACJ,MAAI;AACJ,MAAI,WAAW;AACf,QAAM,SAAS,MAAM;AACnB,QAAI,CAAC,OAAQ;AACb,UAAM,eAAe,EAAE;AACvB,UAAM,OAAO,eAAe,YAAY,EAAE;AAC1C,QAAI,CAAC,UAAU,aAAa,gBAAgB,SAAS,SAAU;AAC/D,eAAW;AACX,YAAQ,SAAS,EAAE,MAAM,qBAAqB,KAAK,CAAC;AAAA,EACtD;AACA,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,OAAQ;AACb,aAAS;AACT,QAAI;AACF,UAAI;AACF,sBAAc;AAAA,MAChB,QAAQ;AAAA,MAER;AACA,UAAI,aAAa,QAAW;AAC1B,gBAAQ,SAAS,EAAE,MAAM,qBAAqB,MAAM,UAAU,CAAC;AAAA,MACjE;AAAA,IACF,UAAE;AACA,oBAAc,OAAO,OAAO;AAAA,IAC9B;AAAA,EACF;AACA,MAAI;AACF,kBAAc,eAAe,UAAU,MAAM;AAC7C,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI;AACF,cAAQ;AAAA,IACV,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACA,SAAO,EAAE,QAAQ;AACnB;;;AChEO,SAAS,kBAAkBA,WAAoC;AACpE,MAAI,SAASA,UAAS;AACtB,QAAM,UAAU,oBAAI,IAAa;AACjC,SAAO,QAAQ;AACb,QAAI,QAAQ,IAAI,MAAM,EAAG,OAAM,IAAI,MAAM,uBAAuB;AAChE,YAAQ,IAAI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MAAM;AACzC,SAAO,aAAa,iBAAiB,gBAAgB;AACrD,SAAO,OAAO,OAAO,OAAO;AAAA,IAC1B,UAAU;AAAA,IACV,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,QAAQ;AAAA,EACV,CAAC;AACH;AAEA,SAAS,YAAY,QAAqB,QAAkC;AAC1E,MAAI,WAAW,OAAW,QAAO,gBAAgB,MAAM;AAAA,MAClD,QAAO,aAAa,QAAQ,MAAM;AACzC;AAEO,SAAS,YACd,SACA,UAA4B,CAAC,GACb;AAChB,QAAM,YAAY,gBAAgB,OAAO;AACzC,MAAI,WAAW;AACf,MAAI;AACJ,MAAI;AACF,kBAAc,QAAQ,uBAAuB,CAAC,WAAW;AACvD,UAAI,CAAC,SAAU,WAAU,SAAS,MAAM;AAAA,IAC1C,CAAC;AAAA,EACH,SAAS,OAAO;AACd,cAAU,QAAQ;AAClB,UAAM;AAAA,EACR;AAEA,SAAO;AAAA,IACL;AAAA,IACA,UAAU;AACR,UAAI,SAAU;AACd,iBAAW;AACX,UAAI;AACF,oBAAY;AAAA,MACd,UAAE;AACA,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;","names":["document","document","window","document","serializeError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@generative-a11y/dom",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DOM accessibility delivery for paced screen-reader announcements in streaming AI and agent interfaces.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"accessibility",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"README.md"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@generative-a11y/core": "0.
|
|
48
|
+
"@generative-a11y/core": "0.4.0"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/jsdom": "30.0.0",
|