@cognitap/radiant 0.0.90 → 0.0.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/library/a2ui/A2uiPlaceholder.d.ts +14 -0
  3. package/dist/library/a2ui/A2uiPlaceholder.d.ts.map +1 -0
  4. package/dist/library/a2ui/A2uiPlaceholder.js +44 -0
  5. package/dist/library/a2ui/A2uiPlaceholder.js.map +1 -0
  6. package/dist/library/a2ui/A2uiSurface.d.ts +33 -0
  7. package/dist/library/a2ui/A2uiSurface.d.ts.map +1 -0
  8. package/dist/library/a2ui/A2uiSurface.js +542 -0
  9. package/dist/library/a2ui/A2uiSurface.js.map +1 -0
  10. package/dist/library/a2ui/accessibility.d.ts +31 -0
  11. package/dist/library/a2ui/accessibility.d.ts.map +1 -0
  12. package/dist/library/a2ui/accessibility.js +108 -0
  13. package/dist/library/a2ui/accessibility.js.map +1 -0
  14. package/dist/library/a2ui/accessibilityRules.d.ts +28 -0
  15. package/dist/library/a2ui/accessibilityRules.d.ts.map +1 -0
  16. package/dist/library/a2ui/accessibilityRules.js +73 -0
  17. package/dist/library/a2ui/accessibilityRules.js.map +1 -0
  18. package/dist/library/a2ui/catalogGenerator.d.ts +29 -0
  19. package/dist/library/a2ui/catalogGenerator.d.ts.map +1 -0
  20. package/dist/library/a2ui/catalogGenerator.js +578 -0
  21. package/dist/library/a2ui/catalogGenerator.js.map +1 -0
  22. package/dist/library/a2ui/coerce.d.ts +16 -0
  23. package/dist/library/a2ui/coerce.d.ts.map +1 -0
  24. package/dist/library/a2ui/coerce.js +254 -0
  25. package/dist/library/a2ui/coerce.js.map +1 -0
  26. package/dist/library/a2ui/entries.d.ts +6 -0
  27. package/dist/library/a2ui/entries.d.ts.map +1 -0
  28. package/dist/library/a2ui/entries.js +277 -0
  29. package/dist/library/a2ui/entries.js.map +1 -0
  30. package/dist/library/a2ui/fixtures.d.ts +38 -0
  31. package/dist/library/a2ui/fixtures.d.ts.map +1 -0
  32. package/dist/library/a2ui/fixtures.js +389 -0
  33. package/dist/library/a2ui/fixtures.js.map +1 -0
  34. package/dist/library/a2ui/index.d.ts +17 -0
  35. package/dist/library/a2ui/index.d.ts.map +1 -0
  36. package/dist/library/a2ui/index.js +9 -0
  37. package/dist/library/a2ui/index.js.map +1 -0
  38. package/dist/library/a2ui/protocolErrors.d.ts +13 -0
  39. package/dist/library/a2ui/protocolErrors.d.ts.map +1 -0
  40. package/dist/library/a2ui/protocolErrors.js +48 -0
  41. package/dist/library/a2ui/protocolErrors.js.map +1 -0
  42. package/dist/library/a2ui/registry.d.ts +58 -0
  43. package/dist/library/a2ui/registry.d.ts.map +1 -0
  44. package/dist/library/a2ui/registry.js +128 -0
  45. package/dist/library/a2ui/registry.js.map +1 -0
  46. package/dist/library/a2ui/sanitize.d.ts +7 -0
  47. package/dist/library/a2ui/sanitize.d.ts.map +1 -0
  48. package/dist/library/a2ui/sanitize.js +54 -0
  49. package/dist/library/a2ui/sanitize.js.map +1 -0
  50. package/dist/library/a2ui/surfaceRuntime.d.ts +34 -0
  51. package/dist/library/a2ui/surfaceRuntime.d.ts.map +1 -0
  52. package/dist/library/a2ui/surfaceRuntime.js +284 -0
  53. package/dist/library/a2ui/surfaceRuntime.js.map +1 -0
  54. package/dist/library/catalog/actions.d.ts +40 -0
  55. package/dist/library/catalog/actions.d.ts.map +1 -0
  56. package/dist/library/catalog/actions.js +70 -0
  57. package/dist/library/catalog/actions.js.map +1 -0
  58. package/dist/library/catalog/coerce.d.ts +70 -0
  59. package/dist/library/catalog/coerce.d.ts.map +1 -0
  60. package/dist/library/catalog/coerce.js +332 -0
  61. package/dist/library/catalog/coerce.js.map +1 -0
  62. package/dist/library/catalog/index.d.ts +9 -0
  63. package/dist/library/catalog/index.d.ts.map +1 -0
  64. package/dist/library/catalog/index.js +6 -0
  65. package/dist/library/catalog/index.js.map +1 -0
  66. package/dist/library/catalog/radiantCatalog.d.ts +9 -0
  67. package/dist/library/catalog/radiantCatalog.d.ts.map +1 -0
  68. package/dist/library/catalog/radiantCatalog.js +902 -0
  69. package/dist/library/catalog/radiantCatalog.js.map +1 -0
  70. package/dist/library/catalog/types.d.ts +113 -0
  71. package/dist/library/catalog/types.d.ts.map +1 -0
  72. package/dist/library/catalog/types.js +27 -0
  73. package/dist/library/catalog/types.js.map +1 -0
  74. package/dist/library/catalog/validate.d.ts +31 -0
  75. package/dist/library/catalog/validate.d.ts.map +1 -0
  76. package/dist/library/catalog/validate.js +420 -0
  77. package/dist/library/catalog/validate.js.map +1 -0
  78. package/dist/library/components/Card/Card.d.ts +6 -2
  79. package/dist/library/components/Card/Card.d.ts.map +1 -1
  80. package/dist/library/components/Card/Card.js +12 -4
  81. package/dist/library/components/Card/Card.js.map +1 -1
  82. package/dist/library/components/Checkbox/Checkbox.d.ts.map +1 -1
  83. package/dist/library/components/Checkbox/Checkbox.js +2 -2
  84. package/dist/library/components/Checkbox/Checkbox.js.map +1 -1
  85. package/dist/library/components/Collapsible/Collapsible.js +1 -1
  86. package/dist/library/components/Collapsible/Collapsible.js.map +1 -1
  87. package/dist/library/components/InputGroup/InputGroup.js +1 -1
  88. package/dist/library/components/InputGroup/InputGroup.js.map +1 -1
  89. package/dist/library/components/NavLink/NavLink.d.ts.map +1 -1
  90. package/dist/library/components/NavLink/NavLink.js +1 -1
  91. package/dist/library/components/NavLink/NavLink.js.map +1 -1
  92. package/dist/library/components/RadioGroup/RadioGroup.d.ts.map +1 -1
  93. package/dist/library/components/RadioGroup/RadioGroup.js +3 -3
  94. package/dist/library/components/RadioGroup/RadioGroup.js.map +1 -1
  95. package/dist/library/components/ScrollArea/ScrollArea.d.ts.map +1 -1
  96. package/dist/library/components/ScrollArea/ScrollArea.js +4 -1
  97. package/dist/library/components/ScrollArea/ScrollArea.js.map +1 -1
  98. package/dist/library/components/Switch/Switch.d.ts.map +1 -1
  99. package/dist/library/components/Switch/Switch.js +2 -2
  100. package/dist/library/components/Switch/Switch.js.map +1 -1
  101. package/dist/library/components/Table/Table.d.ts +6 -2
  102. package/dist/library/components/Table/Table.d.ts.map +1 -1
  103. package/dist/library/components/Table/Table.js +10 -4
  104. package/dist/library/components/Table/Table.js.map +1 -1
  105. package/dist/library/components/TagsInput/TagsInput.d.ts.map +1 -1
  106. package/dist/library/components/TagsInput/TagsInput.js +1 -1
  107. package/dist/library/components/TagsInput/TagsInput.js.map +1 -1
  108. package/dist/library/components/TimeInput/TimeInput.d.ts.map +1 -1
  109. package/dist/library/components/TimeInput/TimeInput.js +28 -20
  110. package/dist/library/components/TimeInput/TimeInput.js.map +1 -1
  111. package/dist/library/components/Toast/Toast.js +1 -1
  112. package/dist/library/components/Toast/Toast.js.map +1 -1
  113. package/dist/library/components/ToggleGroup/ToggleGroup.js +1 -1
  114. package/dist/library/components/ToggleGroup/ToggleGroup.js.map +1 -1
  115. package/dist/library/index.d.ts +1 -1
  116. package/dist/library/index.d.ts.map +1 -1
  117. package/dist/library/presentation.d.ts +3 -0
  118. package/dist/library/presentation.d.ts.map +1 -1
  119. package/dist/library/styles.css +1 -1
  120. package/dist/library/themes/components.d.ts +6 -0
  121. package/dist/library/themes/components.d.ts.map +1 -1
  122. package/dist/library/themes/components.js +6 -0
  123. package/dist/library/themes/components.js.map +1 -1
  124. package/dist/library/themes/tokens.d.ts +4 -0
  125. package/dist/library/themes/tokens.d.ts.map +1 -1
  126. package/dist/library/themes/tokens.js +3 -0
  127. package/dist/library/themes/tokens.js.map +1 -1
  128. package/docs/accessibility.md +6 -0
  129. package/docs/architecture.md +20 -1
  130. package/docs/theming.md +13 -0
  131. package/package.json +17 -5
  132. package/src/a2ui/A2uiPlaceholder.tsx +64 -0
  133. package/src/a2ui/A2uiSurface.tsx +790 -0
  134. package/src/a2ui/accessibility.ts +145 -0
  135. package/src/a2ui/accessibilityRules.ts +106 -0
  136. package/src/a2ui/catalog.json +317 -0
  137. package/src/a2ui/catalogGenerator.ts +717 -0
  138. package/src/a2ui/coerce.ts +379 -0
  139. package/src/a2ui/entries.tsx +519 -0
  140. package/src/a2ui/fixtures.ts +402 -0
  141. package/src/a2ui/index.ts +50 -0
  142. package/src/a2ui/protocolErrors.ts +63 -0
  143. package/src/a2ui/registry.ts +221 -0
  144. package/src/a2ui/sanitize.ts +51 -0
  145. package/src/a2ui/surfaceRuntime.ts +317 -0
  146. package/src/catalog/actions.ts +108 -0
  147. package/src/catalog/coerce.ts +447 -0
  148. package/src/catalog/index.ts +67 -0
  149. package/src/catalog/radiantCatalog.ts +949 -0
  150. package/src/catalog/types.ts +159 -0
  151. package/src/catalog/validate.ts +454 -0
  152. package/src/components/Card/Card.tsx +35 -19
  153. package/src/components/Checkbox/Checkbox.tsx +2 -0
  154. package/src/components/Collapsible/Collapsible.tsx +1 -1
  155. package/src/components/InputGroup/InputGroup.tsx +2 -2
  156. package/src/components/NavLink/NavLink.tsx +1 -6
  157. package/src/components/RadioGroup/RadioGroup.tsx +3 -0
  158. package/src/components/ScrollArea/ScrollArea.tsx +5 -1
  159. package/src/components/Switch/Switch.tsx +2 -0
  160. package/src/components/Table/Table.tsx +16 -3
  161. package/src/components/TagsInput/TagsInput.tsx +1 -0
  162. package/src/components/TimeInput/TimeInput.tsx +100 -75
  163. package/src/components/Toast/Toast.tsx +1 -1
  164. package/src/components/ToggleGroup/ToggleGroup.tsx +1 -1
  165. package/src/index.ts +1 -1
  166. package/src/presentation.ts +3 -0
  167. package/src/themes/baseline.css +3 -0
  168. package/src/themes/components.ts +6 -0
  169. package/src/themes/tokens.ts +7 -0
@@ -0,0 +1,221 @@
1
+ import type { ComponentType, ReactNode } from 'react'
2
+ import {
3
+ Catalog as WebCoreCatalog,
4
+ type ComponentApi,
5
+ type FunctionImplementation
6
+ } from '@a2ui/web_core/catalog'
7
+ import type { ComponentNode } from '@a2ui/web_core/resolution'
8
+ import { findForbiddenPropsInSchema, type CatalogJsonSchema } from '../catalog/index.js'
9
+ import {
10
+ A2UI_PROTOCOL_VERSION,
11
+ type A2uiCatalogDocument,
12
+ type A2uiJsonSchema
13
+ } from './catalogGenerator.js'
14
+ import type { A2uiAccessibilityRule } from './accessibilityRules.js'
15
+
16
+ const ENTRY_NAME_PATTERN = /^[A-Z][A-Za-z0-9]*$/
17
+
18
+ export type A2uiRenderOptions = {
19
+ readonly inline?: boolean
20
+ }
21
+
22
+ export type A2uiAdapterContext = {
23
+ readonly node: ComponentNode
24
+ readonly inline: boolean
25
+ readonly renderNode: (child: ComponentNode, options?: A2uiRenderOptions) => ReactNode
26
+ }
27
+
28
+ export type A2uiComponentAdapter = (
29
+ props: Readonly<Record<string, unknown>>,
30
+ context: A2uiAdapterContext
31
+ ) => ReactNode
32
+
33
+ export type A2uiComponentReference =
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ | ComponentType<any>
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ | readonly ComponentType<any>[]
38
+ | string
39
+
40
+ export type A2uiRegistryEntryInput = {
41
+ readonly name: string
42
+ readonly component: A2uiComponentReference
43
+ readonly schema: A2uiJsonSchema
44
+ readonly description: string
45
+ readonly adapter: A2uiComponentAdapter
46
+ /** Accessibility rules checked by `validateA2uiAccessibility`; `[]` declares none. */
47
+ readonly accessibility: readonly A2uiAccessibilityRule[]
48
+ }
49
+
50
+ export type A2uiRegistryEntry = {
51
+ readonly name: string
52
+ readonly component: A2uiComponentReference
53
+ readonly schema: A2uiJsonSchema
54
+ readonly description: string
55
+ readonly adapter: A2uiComponentAdapter
56
+ /** Accessibility rules checked by `validateA2uiAccessibility`; `[]` declares none. */
57
+ readonly accessibility: readonly A2uiAccessibilityRule[]
58
+ }
59
+
60
+ export type A2uiRegistryInput = {
61
+ readonly catalogId: string
62
+ readonly title: string
63
+ readonly description: string
64
+ readonly entries: readonly A2uiRegistryEntry[]
65
+ }
66
+
67
+ export type A2uiRegistry = {
68
+ readonly catalogId: string
69
+ readonly title: string
70
+ readonly description: string
71
+ readonly entries: Readonly<Record<string, A2uiRegistryEntry>>
72
+ toCatalogJson(): A2uiCatalogDocument
73
+ toWebCoreCatalog(): WebCoreCatalog<ComponentApi, FunctionImplementation>
74
+ }
75
+
76
+ function findForbiddenInA2uiSchema(schema: A2uiJsonSchema, path: string): readonly string[] {
77
+ const violations: string[] = [...findForbiddenPropsInSchema(schema as CatalogJsonSchema, path)]
78
+ if (Array.isArray(schema.allOf)) {
79
+ for (let i = 0; i < schema.allOf.length; i++) {
80
+ const branch = schema.allOf[i]
81
+ if (branch && typeof branch === 'object') {
82
+ violations.push(
83
+ ...findForbiddenInA2uiSchema(branch as A2uiJsonSchema, `${path}.allOf[${i}]`)
84
+ )
85
+ }
86
+ }
87
+ }
88
+ return violations
89
+ }
90
+
91
+ /**
92
+ * Defines a single validated A2UI registry entry pairing a Radiant component,
93
+ * its curated JSON Schema, its agent-facing description, and its prop adapter.
94
+ */
95
+ export function createA2uiRegistryEntry(input: A2uiRegistryEntryInput): A2uiRegistryEntry {
96
+ if (typeof input.name !== 'string' || !ENTRY_NAME_PATTERN.test(input.name)) {
97
+ throw new TypeError(`A2UI registry entry name must be PascalCase; received "${input.name}".`)
98
+ }
99
+ if (typeof input.description !== 'string' || !input.description.trim()) {
100
+ throw new TypeError(`A2UI registry entry "${input.name}" requires a non-empty description.`)
101
+ }
102
+ if (!input.schema || typeof input.schema !== 'object' || Array.isArray(input.schema)) {
103
+ throw new TypeError(`A2UI registry entry "${input.name}" requires a JSON Schema object.`)
104
+ }
105
+ if (typeof input.adapter !== 'function') {
106
+ throw new TypeError(`A2UI registry entry "${input.name}" requires an adapter function.`)
107
+ }
108
+ if (!Array.isArray(input.accessibility)) {
109
+ throw new TypeError(`A2UI registry entry "${input.name}" must declare accessibility rules.`)
110
+ }
111
+ if (
112
+ !input.accessibility.every(
113
+ rule => rule && typeof rule.id === 'string' && rule.id && typeof rule.check === 'function'
114
+ )
115
+ ) {
116
+ throw new TypeError(
117
+ `A2UI registry entry "${input.name}" has an accessibility rule without an id or check function.`
118
+ )
119
+ }
120
+ const forbidden = findForbiddenInA2uiSchema(input.schema, `${input.name}.schema`)
121
+ if (forbidden.length > 0) {
122
+ throw new TypeError(
123
+ `A2UI registry entry "${input.name}" exposes forbidden props: ${forbidden.join(', ')}.`
124
+ )
125
+ }
126
+ return Object.freeze({
127
+ name: input.name,
128
+ component: input.component,
129
+ schema: structuredClone(input.schema),
130
+ description: input.description,
131
+ adapter: input.adapter,
132
+ accessibility: Object.freeze([...input.accessibility])
133
+ })
134
+ }
135
+
136
+ /**
137
+ * Builds an immutable A2UI 1.0 registry that generates both its JSON Schema catalog
138
+ * document and its executable `@a2ui/web_core` catalog from the same entry list.
139
+ */
140
+ export function createA2uiRegistry(input: A2uiRegistryInput): A2uiRegistry {
141
+ if (typeof input.catalogId !== 'string' || !input.catalogId.trim()) {
142
+ throw new TypeError('A2UI registry requires a non-empty catalogId.')
143
+ }
144
+ if (typeof input.title !== 'string' || !input.title.trim()) {
145
+ throw new TypeError('A2UI registry requires a non-empty title.')
146
+ }
147
+ if (typeof input.description !== 'string' || !input.description.trim()) {
148
+ throw new TypeError('A2UI registry requires a non-empty description.')
149
+ }
150
+ if (!Array.isArray(input.entries) || input.entries.length === 0) {
151
+ throw new TypeError('A2UI registry requires at least one entry.')
152
+ }
153
+
154
+ const entryMap: Record<string, A2uiRegistryEntry> = {}
155
+ for (const entry of input.entries) {
156
+ if (Object.hasOwn(entryMap, entry.name)) {
157
+ throw new TypeError(`Duplicate A2UI registry entry "${entry.name}".`)
158
+ }
159
+ const validated = createA2uiRegistryEntry(entry)
160
+ entryMap[validated.name] = validated
161
+ }
162
+ const frozenEntries = Object.freeze(entryMap)
163
+
164
+ const buildDocument = (): A2uiCatalogDocument => {
165
+ const components: Record<string, A2uiJsonSchema> = {}
166
+ for (const [name, entry] of Object.entries(frozenEntries)) {
167
+ components[name] = structuredClone(entry.schema)
168
+ }
169
+ return {
170
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
171
+ $id: input.catalogId,
172
+ catalogId: input.catalogId,
173
+ protocolVersion: A2UI_PROTOCOL_VERSION,
174
+ title: input.title,
175
+ description: input.description,
176
+ components,
177
+ functions: {},
178
+ $defs: {
179
+ anyComponent: {
180
+ oneOf: Object.keys(components).map(name => ({ $ref: `#/components/${name}` })),
181
+ discriminator: { propertyName: 'component' }
182
+ },
183
+ anyFunction: { not: {} },
184
+ Weight: {
185
+ type: 'number',
186
+ description:
187
+ 'Relative flex growth of this component inside a Row or Column. Set it only on direct children of a Row or Column.'
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ let cachedCatalog: WebCoreCatalog<ComponentApi, FunctionImplementation> | undefined
194
+
195
+ return Object.freeze({
196
+ catalogId: input.catalogId,
197
+ title: input.title,
198
+ description: input.description,
199
+ entries: frozenEntries,
200
+ toCatalogJson(): A2uiCatalogDocument {
201
+ return buildDocument()
202
+ },
203
+ toWebCoreCatalog(): WebCoreCatalog<ComponentApi, FunctionImplementation> {
204
+ if (!cachedCatalog) {
205
+ const parsed = WebCoreCatalog.fromJson(buildDocument(), A2UI_PROTOCOL_VERSION)
206
+ cachedCatalog = new WebCoreCatalog<ComponentApi, FunctionImplementation>(
207
+ parsed.id,
208
+ A2UI_PROTOCOL_VERSION,
209
+ [...parsed.components.values()],
210
+ [],
211
+ {
212
+ defs: parsed.defs,
213
+ title: parsed.title,
214
+ description: parsed.description
215
+ }
216
+ )
217
+ }
218
+ return cachedCatalog
219
+ }
220
+ })
221
+ }
@@ -0,0 +1,51 @@
1
+ export type A2uiMessage = Readonly<Record<string, unknown>>
2
+
3
+ function stripThemeFromObject(value: Record<string, unknown>): Record<string, unknown> {
4
+ const next: Record<string, unknown> = {}
5
+ for (const [key, entry] of Object.entries(value)) {
6
+ if (key === 'theme') continue
7
+ if (key === 'metadata' && entry && typeof entry === 'object' && !Array.isArray(entry)) {
8
+ const cleanedMeta = stripThemeFromMetadata(entry as Record<string, unknown>)
9
+ if (Object.keys(cleanedMeta).length > 0) next.metadata = cleanedMeta
10
+ continue
11
+ }
12
+ next[key] = entry
13
+ }
14
+ return next
15
+ }
16
+
17
+ function stripThemeFromMetadata(metadata: Record<string, unknown>): Record<string, unknown> {
18
+ const next: Record<string, unknown> = {}
19
+ for (const [key, entry] of Object.entries(metadata)) {
20
+ if (key === 'theme') continue
21
+ if (key === 'extensions' && entry && typeof entry === 'object' && !Array.isArray(entry)) {
22
+ const ext: Record<string, unknown> = {}
23
+ for (const [extKey, extValue] of Object.entries(entry as Record<string, unknown>)) {
24
+ if (extKey === 'theme') continue
25
+ ext[extKey] = extValue
26
+ }
27
+ if (Object.keys(ext).length > 0) next.extensions = ext
28
+ continue
29
+ }
30
+ next[key] = entry
31
+ }
32
+ return next
33
+ }
34
+
35
+ /**
36
+ * Returns a copy of incoming A2UI messages with agent-supplied theme hints stripped so
37
+ * the surrounding Radiant ThemeScope remains the sole styling authority.
38
+ */
39
+ export function sanitizeA2uiMessages(messages: readonly A2uiMessage[]): readonly A2uiMessage[] {
40
+ return messages.map(message => {
41
+ if (!message || typeof message !== 'object' || Array.isArray(message)) return message
42
+ const createSurface = message.createSurface
43
+ if (!createSurface || typeof createSurface !== 'object' || Array.isArray(createSurface)) {
44
+ return message
45
+ }
46
+ return {
47
+ ...message,
48
+ createSurface: stripThemeFromObject(createSurface as Record<string, unknown>)
49
+ }
50
+ })
51
+ }
@@ -0,0 +1,317 @@
1
+ import { isPlainRecord } from '../catalog/coerce.js'
2
+ import type { MotionProfile } from '../motion/config.js'
3
+ import type { A2uiMessage } from './sanitize.js'
4
+
5
+ const FOCUSABLE_SELECTOR =
6
+ 'a[href],area[href],button,input,select,textarea,summary,[tabindex],[contenteditable]:not([contenteditable="false"])'
7
+ const DEFAULT_ENTRY_EASING = 'cubic-bezier(0.2, 0.8, 0.2, 1)'
8
+
9
+ export const A2UI_NODE_ENTRY_ANIMATION_ID = 'radiant-a2ui-entry'
10
+
11
+ function cloneFallback<T>(value: T, seen = new WeakMap<object, unknown>()): T {
12
+ if (!value || typeof value !== 'object') return value
13
+ if (seen.has(value)) return seen.get(value) as T
14
+ if (Array.isArray(value)) {
15
+ const next: unknown[] = []
16
+ seen.set(value, next)
17
+ for (let i = 0; i < value.length; i++) next[i] = cloneFallback(value[i], seen)
18
+ return next as unknown as T
19
+ }
20
+ if (!isPlainRecord(value)) return value
21
+ const next: Record<string, unknown> = {}
22
+ seen.set(value, next)
23
+ for (const key of Object.keys(value)) {
24
+ Object.defineProperty(next, key, {
25
+ value: cloneFallback(value[key], seen),
26
+ enumerable: true,
27
+ writable: true,
28
+ configurable: true
29
+ })
30
+ }
31
+ return next as T
32
+ }
33
+
34
+ /** Deep-clones wire messages so live state cannot mutate caller or stored history. */
35
+ export function cloneMessageValue<T>(value: T): T {
36
+ if (!value || typeof value !== 'object') return value
37
+ try {
38
+ return structuredClone(value)
39
+ } catch {
40
+ return cloneFallback(value)
41
+ }
42
+ }
43
+
44
+ function sameMessageValue(a: unknown, b: unknown): boolean {
45
+ const seen = new WeakMap<object, WeakSet<object>>()
46
+ const stack: [unknown, unknown][] = [[a, b]]
47
+ while (stack.length > 0) {
48
+ const [left, right] = stack.pop()!
49
+ if (Object.is(left, right)) continue
50
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false
51
+ let rightSeen = seen.get(left)
52
+ if (rightSeen?.has(right)) continue
53
+ if (!rightSeen) seen.set(left, (rightSeen = new WeakSet()))
54
+ rightSeen.add(right)
55
+ if (Array.isArray(left) || Array.isArray(right)) {
56
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
57
+ return false
58
+ }
59
+ for (let i = 0; i < left.length; i++) stack.push([left[i], right[i]])
60
+ continue
61
+ }
62
+ if (!isPlainRecord(left) || !isPlainRecord(right)) return false
63
+ const keys = Object.keys(left)
64
+ if (keys.length !== Object.keys(right).length) return false
65
+ for (const key of keys) {
66
+ if (!Object.hasOwn(right, key)) return false
67
+ stack.push([left[key], right[key]])
68
+ }
69
+ }
70
+ return true
71
+ }
72
+
73
+ /** Returns true when `previous` is a structurally equal prefix of `next`. */
74
+ export function isMessagePrefix(
75
+ previous: readonly A2uiMessage[],
76
+ next: readonly A2uiMessage[]
77
+ ): boolean {
78
+ if (previous.length > next.length) return false
79
+ for (let i = 0; i < previous.length; i++) {
80
+ if (!sameMessageValue(previous[i], next[i])) return false
81
+ }
82
+ return true
83
+ }
84
+
85
+ /** Coalesces repeated calls within the same turn into a single microtask invocation. */
86
+ export function createMicrotaskCoalescer(run: () => void): () => void {
87
+ let scheduled = false
88
+ return () => {
89
+ if (scheduled) return
90
+ scheduled = true
91
+ queueMicrotask(() => {
92
+ scheduled = false
93
+ run()
94
+ })
95
+ }
96
+ }
97
+
98
+ export function isHtmlElement(node: unknown): node is HTMLElement {
99
+ if (typeof node !== 'object' || node === null || !('ownerDocument' in node)) return false
100
+ const win = (node as Element).ownerDocument?.defaultView
101
+ return Boolean(win && node instanceof win.HTMLElement)
102
+ }
103
+
104
+ export type NodeHost = {
105
+ readonly nodeId: string
106
+ readonly instanceId: string
107
+ readonly element: HTMLElement
108
+ readonly isContainer: boolean
109
+ }
110
+
111
+ function isFocusableWithin(
112
+ element: HTMLElement,
113
+ root: HTMLElement,
114
+ allowProgrammatic = false
115
+ ): boolean {
116
+ if (!element.isConnected || !root.contains(element) || element === root) return false
117
+ if (element.tabIndex < 0 && !(allowProgrammatic && element.hasAttribute('tabindex'))) return false
118
+ if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'hidden') return false
119
+ if (element.matches(':disabled') || element.getAttribute('aria-disabled') === 'true') return false
120
+ if (element.closest('[hidden],[inert]') || element.getClientRects().length === 0) return false
121
+ const win = element.ownerDocument.defaultView
122
+ return !win || win.getComputedStyle(element).visibility !== 'hidden'
123
+ }
124
+
125
+ function queryFocusable(
126
+ scope: HTMLElement,
127
+ root: HTMLElement,
128
+ allowProgrammatic = false
129
+ ): HTMLElement[] {
130
+ const results = scope !== root && isFocusableWithin(scope, root, allowProgrammatic) ? [scope] : []
131
+ for (const element of scope.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)) {
132
+ if (isFocusableWithin(element, root, allowProgrammatic)) results.push(element)
133
+ }
134
+ return results
135
+ }
136
+
137
+ function findOwningHost(
138
+ active: HTMLElement,
139
+ hosts: ReadonlyMap<string, NodeHost>
140
+ ): NodeHost | null {
141
+ let owner: NodeHost | null = null
142
+ for (const host of hosts.values()) {
143
+ if (host.isContainer || !host.element.isConnected || !host.element.contains(active)) continue
144
+ if (!owner || owner.element.contains(host.element)) owner = host
145
+ }
146
+ return owner
147
+ }
148
+
149
+ function findUniqueHostByInstance(
150
+ hosts: ReadonlyMap<string, NodeHost>,
151
+ instanceId: string
152
+ ): NodeHost | null {
153
+ let match: NodeHost | null = null
154
+ for (const host of hosts.values()) {
155
+ if (host.instanceId !== instanceId || !host.element.isConnected) continue
156
+ if (match) return null
157
+ match = host
158
+ }
159
+ return match
160
+ }
161
+
162
+ export type FocusSnapshot = {
163
+ readonly active: HTMLElement
164
+ readonly restoreInstanceId: string | null
165
+ readonly controlIndex: number
166
+ readonly after: readonly HTMLElement[]
167
+ readonly before: readonly HTMLElement[]
168
+ readonly selectionStart: number | null
169
+ readonly selectionEnd: number | null
170
+ readonly scrollTop: number
171
+ readonly scrollLeft: number
172
+ }
173
+
174
+ /** Captures the active control, unambiguous owning instance, and surrounding tabbable order. */
175
+ export function captureFocusSnapshot(
176
+ root: HTMLElement | null,
177
+ hosts: ReadonlyMap<string, NodeHost>
178
+ ): FocusSnapshot | null {
179
+ if (!root?.isConnected) return null
180
+ const active = root.ownerDocument.activeElement
181
+ if (!isHtmlElement(active) || !root.contains(active) || active === root) return null
182
+
183
+ const after: HTMLElement[] = []
184
+ const before: HTMLElement[] = []
185
+ for (const candidate of queryFocusable(root, root)) {
186
+ if (candidate === active) continue
187
+ const pos = active.compareDocumentPosition(candidate)
188
+ if (pos & active.DOCUMENT_POSITION_FOLLOWING) after.push(candidate)
189
+ else if (pos & active.DOCUMENT_POSITION_PRECEDING) before.push(candidate)
190
+ }
191
+ before.reverse()
192
+
193
+ const owner = findOwningHost(active, hosts)
194
+ const restoreInstanceId =
195
+ owner && findUniqueHostByInstance(hosts, owner.instanceId) === owner ? owner.instanceId : null
196
+ const controlIndex = owner
197
+ ? Math.max(0, queryFocusable(owner.element, root, true).indexOf(active))
198
+ : 0
199
+
200
+ let selectionStart: number | null = null
201
+ let selectionEnd: number | null = null
202
+ if (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA') {
203
+ try {
204
+ const input = active as HTMLInputElement | HTMLTextAreaElement
205
+ selectionStart = input.selectionStart
206
+ selectionEnd = input.selectionEnd
207
+ } catch {
208
+ // Non-text inputs do not expose selection ranges.
209
+ }
210
+ }
211
+
212
+ return {
213
+ active,
214
+ restoreInstanceId,
215
+ controlIndex,
216
+ after,
217
+ before,
218
+ selectionStart,
219
+ selectionEnd,
220
+ scrollTop: active.scrollTop,
221
+ scrollLeft: active.scrollLeft
222
+ }
223
+ }
224
+
225
+ function restoreControlState(target: HTMLElement, snapshot: FocusSnapshot): void {
226
+ target.focus({ preventScroll: true })
227
+ if (
228
+ (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') &&
229
+ snapshot.selectionStart !== null &&
230
+ snapshot.selectionEnd !== null
231
+ ) {
232
+ try {
233
+ ;(target as HTMLInputElement | HTMLTextAreaElement).setSelectionRange(
234
+ snapshot.selectionStart,
235
+ snapshot.selectionEnd
236
+ )
237
+ } catch {
238
+ // Ignore inputs that disallow setting a selection range.
239
+ }
240
+ }
241
+ if (snapshot.scrollTop > 0) target.scrollTop = snapshot.scrollTop
242
+ if (snapshot.scrollLeft > 0) target.scrollLeft = snapshot.scrollLeft
243
+ }
244
+
245
+ /** Restores focus synchronously in an active document using the order documented in architecture.md. */
246
+ export function restoreFocusFallback(
247
+ root: HTMLElement | null,
248
+ snapshot: FocusSnapshot,
249
+ hosts: ReadonlyMap<string, NodeHost>
250
+ ): void {
251
+ if (!root?.isConnected) return
252
+ const doc = root.ownerDocument
253
+ if (typeof doc.hasFocus === 'function' && !doc.hasFocus()) return
254
+ const current = doc.activeElement
255
+ if (current && current !== doc.body && current !== doc.documentElement) return
256
+
257
+ if (isFocusableWithin(snapshot.active, root, true)) {
258
+ restoreControlState(snapshot.active, snapshot)
259
+ return
260
+ }
261
+
262
+ if (snapshot.restoreInstanceId) {
263
+ const movedHost = findUniqueHostByInstance(hosts, snapshot.restoreInstanceId)
264
+ if (movedHost) {
265
+ const controls = queryFocusable(movedHost.element, root, true)
266
+ const movedTarget = controls[snapshot.controlIndex] ?? controls[0]
267
+ if (movedTarget) {
268
+ restoreControlState(movedTarget, snapshot)
269
+ return
270
+ }
271
+ }
272
+ }
273
+
274
+ const target =
275
+ snapshot.after.find(element => isFocusableWithin(element, root)) ??
276
+ snapshot.before.find(element => isFocusableWithin(element, root)) ??
277
+ queryFocusable(root, root)[0] ??
278
+ root
279
+
280
+ target.focus({ preventScroll: true })
281
+ }
282
+
283
+ function parseDurationMs(value: string): number | undefined {
284
+ const match = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)$/.exec(value.trim())
285
+ if (!match) return undefined
286
+ const num = Number.parseFloat(match[1]!)
287
+ return Number.isFinite(num) ? (match[2] === 's' ? num * 1000 : num) : undefined
288
+ }
289
+
290
+ /** Runs entry motion once on a newly mounted node host, ignoring invalid easing values safely. */
291
+ export function animateNodeEntry(
292
+ element: HTMLElement,
293
+ profile: MotionProfile
294
+ ): Animation | undefined {
295
+ if (profile.mode === 'off') return undefined
296
+ const win = element.ownerDocument.defaultView
297
+ if (!win || win.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return undefined
298
+ if (typeof element.animate !== 'function') return undefined
299
+
300
+ const styles = win.getComputedStyle(element)
301
+ const duration = parseDurationMs(styles.getPropertyValue('--rad-motion-release-duration')) ?? 160
302
+ if (duration <= 0) return undefined
303
+ const easing = styles.getPropertyValue('--rad-motion-release-ease').trim() || DEFAULT_ENTRY_EASING
304
+ const keyframes = [{ transform: 'translateY(6px)' }, { transform: 'translateY(0px)' }]
305
+ const options = { id: A2UI_NODE_ENTRY_ANIMATION_ID, duration, easing, fill: 'none' as const }
306
+
307
+ try {
308
+ return element.animate(keyframes, options)
309
+ } catch {
310
+ if (easing === DEFAULT_ENTRY_EASING) return undefined
311
+ try {
312
+ return element.animate(keyframes, { ...options, easing: DEFAULT_ENTRY_EASING })
313
+ } catch {
314
+ return undefined
315
+ }
316
+ }
317
+ }
@@ -0,0 +1,108 @@
1
+ export type CatalogJsonValue =
2
+ | string
3
+ | number
4
+ | boolean
5
+ | null
6
+ | readonly CatalogJsonValue[]
7
+ | { readonly [key: string]: CatalogJsonValue }
8
+
9
+ /**
10
+ * Immutable JSON snapshot of a surface's client-side state.
11
+ * Preserves any JSON root value supported by the runtime (object, array, primitive, or `null`).
12
+ * When no state is available (`undefined`) or the root is unsupported, snapshots normalize to a
13
+ * frozen empty object (`{}`).
14
+ */
15
+ export type CatalogSurfaceState = CatalogJsonValue
16
+
17
+ /**
18
+ * Outbound event delivered to the host when a generated surface triggers a named action.
19
+ * Local interactive entries update client state directly without invoking this callback;
20
+ * only named actions deliver the action name and a snapshot of the surface state.
21
+ */
22
+ export type CatalogActionEvent = {
23
+ readonly action: string
24
+ readonly surfaceId: string
25
+ readonly nodeId: string
26
+ readonly state: CatalogSurfaceState
27
+ }
28
+
29
+ /** Host callback invoked when a generated surface dispatches a named outbound action. */
30
+ export type CatalogActionHandler = (event: CatalogActionEvent) => void
31
+
32
+ export type CatalogActionEventInput = {
33
+ readonly action: string
34
+ readonly surfaceId: string
35
+ readonly nodeId: string
36
+ readonly state?: unknown
37
+ }
38
+
39
+ const UNSUPPORTED = Symbol('unsupported')
40
+
41
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
42
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
43
+ const proto = Object.getPrototypeOf(value)
44
+ return proto === Object.prototype || proto === null
45
+ }
46
+
47
+ /**
48
+ * Converts arbitrary runtime values to deeply frozen JSON values.
49
+ * Non-JSON objects (such as Map, Set, Date, RegExp, or class instances), non-finite numbers,
50
+ * functions, and symbols are dropped from objects, replaced with `null` in arrays, and
51
+ * normalized to `{}` at the root so no mutable reference can survive `Object.freeze`.
52
+ */
53
+ function snapshotJsonValue(
54
+ value: unknown,
55
+ seen: Set<object>
56
+ ): CatalogJsonValue | typeof UNSUPPORTED {
57
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
58
+ if (typeof value === 'number') return Number.isFinite(value) ? value : UNSUPPORTED
59
+ if (Array.isArray(value)) {
60
+ if (seen.has(value)) return null
61
+ seen.add(value)
62
+ const copy = value.map(item => {
63
+ const next = snapshotJsonValue(item, seen)
64
+ return next === UNSUPPORTED ? null : next
65
+ })
66
+ seen.delete(value)
67
+ return Object.freeze(copy)
68
+ }
69
+ if (!isPlainObject(value)) return UNSUPPORTED
70
+ if (seen.has(value)) return Object.freeze({})
71
+ seen.add(value)
72
+ const copy: Record<string, CatalogJsonValue> = {}
73
+ for (const [key, entry] of Object.entries(value)) {
74
+ const next = snapshotJsonValue(entry, seen)
75
+ if (next !== UNSUPPORTED) copy[key] = next
76
+ }
77
+ seen.delete(value)
78
+ return Object.freeze(copy)
79
+ }
80
+
81
+ /**
82
+ * Captures an isolated, deeply frozen JSON snapshot of a surface's client-side state.
83
+ * When `rawState` is `undefined` or an unsupported non-JSON value, returns a frozen empty object.
84
+ */
85
+ export function snapshotSurfaceState(rawState: unknown): CatalogSurfaceState {
86
+ const snapshot = snapshotJsonValue(rawState, new Set())
87
+ return snapshot === UNSUPPORTED ? Object.freeze({}) : snapshot
88
+ }
89
+
90
+ function requireIdentifier(value: string, field: string): string {
91
+ if (typeof value !== 'string' || value.trim().length === 0) {
92
+ throw new TypeError(`CatalogActionEvent "${field}" must be a non-empty string.`)
93
+ }
94
+ return value
95
+ }
96
+
97
+ /**
98
+ * Builds a frozen protocol-independent action event with an isolated state snapshot.
99
+ * If `state` is omitted (`undefined`), `event.state` defaults to a frozen empty object (`{}`).
100
+ */
101
+ export function createCatalogActionEvent(input: CatalogActionEventInput): CatalogActionEvent {
102
+ return Object.freeze({
103
+ action: requireIdentifier(input.action, 'action'),
104
+ surfaceId: requireIdentifier(input.surfaceId, 'surfaceId'),
105
+ nodeId: requireIdentifier(input.nodeId, 'nodeId'),
106
+ state: snapshotSurfaceState(input.state)
107
+ })
108
+ }