@copilotkit/react-core 2.0.0-rc.42 → 2.0.0-rc.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MarkdownRendererContext-BL8ct_3U.d.mts → MarkdownRendererContext-CytkPOAJ.d.mts} +1 -1
- package/dist/{MarkdownRendererContext-BL8ct_3U.d.mts.map → MarkdownRendererContext-CytkPOAJ.d.mts.map} +1 -1
- package/dist/MarkdownSurfaces-DlYqJkAE.mjs +135 -0
- package/dist/MarkdownSurfaces-DlYqJkAE.mjs.map +1 -0
- package/dist/MarkdownSurfaces-DytbRzj2.cjs +141 -0
- package/dist/MarkdownSurfaces-DytbRzj2.cjs.map +1 -0
- package/dist/{MarkdownSurfaces-Byz821bg.mjs → ProviderMarkdown-BZaPDROY.mjs} +6 -132
- package/dist/ProviderMarkdown-BZaPDROY.mjs.map +1 -0
- package/dist/{MarkdownSurfaces-D2Ck-cbb.cjs → ProviderMarkdown-i_i2osOH.cjs} +4 -136
- package/dist/ProviderMarkdown-i_i2osOH.cjs.map +1 -0
- package/dist/accessibility-BLK-gE0R.mjs +129 -0
- package/dist/accessibility-BLK-gE0R.mjs.map +1 -0
- package/dist/accessibility-GnodqxkH.cjs +228 -0
- package/dist/accessibility-GnodqxkH.cjs.map +1 -0
- package/dist/{chat-Bf0vVdo7.mjs → chat-B1zczXUD.mjs} +21 -145
- package/dist/chat-B1zczXUD.mjs.map +1 -0
- package/dist/{chat-DgP2N7bD.d.mts → chat-C5XWeO1M.d.mts} +1 -1
- package/dist/{chat-DgP2N7bD.d.mts.map → chat-C5XWeO1M.d.mts.map} +1 -1
- package/dist/{chat-D3fxo6Ah.cjs → chat-CkFZMo5E.cjs} +29 -234
- package/dist/chat-CkFZMo5E.cjs.map +1 -0
- package/dist/context.cjs +2 -2
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +2 -2
- package/dist/context.d.mts +2 -2
- package/dist/context.mjs +2 -2
- package/dist/context.mjs.map +1 -1
- package/dist/generative-ui/native.cjs +9 -8
- package/dist/generative-ui/native.cjs.map +1 -1
- package/dist/generative-ui/native.d.cts.map +1 -1
- package/dist/generative-ui/native.d.mts +2 -2
- package/dist/generative-ui/native.d.mts.map +1 -1
- package/dist/generative-ui/native.mjs +4 -3
- package/dist/generative-ui/native.mjs.map +1 -1
- package/dist/generative-ui.cjs +11 -5767
- package/dist/generative-ui.cjs.map +1 -1
- package/dist/generative-ui.d.mts +4 -4
- package/dist/generative-ui.mjs +8 -5764
- package/dist/generative-ui.mjs.map +1 -1
- package/dist/{hooks-BRYonCVu.d.mts → hooks-DqsOIh8A.d.mts} +3 -3
- package/dist/{hooks-BRYonCVu.d.mts.map → hooks-DqsOIh8A.d.mts.map} +1 -1
- package/dist/index.cjs +180 -683
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -102
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +11 -104
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +64 -409
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +6132 -797
- package/dist/index.umd.js.map +1 -1
- package/dist/{refs-BIUfn1wb.cjs → refs-B5Dn59Pn.cjs} +2 -2
- package/dist/{refs-BIUfn1wb.cjs.map → refs-B5Dn59Pn.cjs.map} +1 -1
- package/dist/{refs-CMrRm3ta.mjs → refs-BW15wX_V.mjs} +1 -1
- package/dist/{refs-CMrRm3ta.mjs.map → refs-BW15wX_V.mjs.map} +1 -1
- package/dist/standard-CqGTZUZy.cjs +5780 -0
- package/dist/standard-CqGTZUZy.cjs.map +1 -0
- package/dist/standard-s8jByRiE.mjs +5784 -0
- package/dist/standard-s8jByRiE.mjs.map +1 -0
- package/dist/{use-generative-ui-root-C12htqbK.cjs → use-generative-ui-root-CIp0ytE6.cjs} +3 -3
- package/dist/{use-generative-ui-root-C12htqbK.cjs.map → use-generative-ui-root-CIp0ytE6.cjs.map} +1 -1
- package/dist/{use-generative-ui-root-CVgsDy1f.mjs → use-generative-ui-root-oBqPa6uy.mjs} +3 -2
- package/dist/{use-generative-ui-root-CVgsDy1f.mjs.map → use-generative-ui-root-oBqPa6uy.mjs.map} +1 -1
- package/package.json +7 -10
- package/dist/MarkdownSurfaces-Byz821bg.mjs.map +0 -1
- package/dist/MarkdownSurfaces-D2Ck-cbb.cjs.map +0 -1
- package/dist/chat-Bf0vVdo7.mjs.map +0 -1
- package/dist/chat-D3fxo6Ah.cjs.map +0 -1
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_accessibility = require('./accessibility-GnodqxkH.cjs');
|
|
2
2
|
let _copilotkit_core = require("@copilotkit/core");
|
|
3
3
|
let react = require("react");
|
|
4
|
-
react =
|
|
4
|
+
react = require_accessibility.__toESM(react);
|
|
5
5
|
let _copilotkit_markdown_react = require("@copilotkit/markdown/react");
|
|
6
6
|
let _copilotkit_markdown = require("@copilotkit/markdown");
|
|
7
7
|
let react_jsx_runtime = require("react/jsx-runtime");
|
|
8
|
-
let _copilotkit_shared = require("@copilotkit/shared");
|
|
9
|
-
let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
|
|
10
8
|
|
|
11
9
|
//#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
|
|
12
10
|
/**
|
|
@@ -138,7 +136,7 @@ const MemoizedSlotWrapper = react.default.memo(react.default.forwardRef(function
|
|
|
138
136
|
if (prev.$component !== next.$component) return false;
|
|
139
137
|
const { $slot: _ps, $component: _pc, ...prevRest } = prev;
|
|
140
138
|
const { $slot: _ns, $component: _nc, ...nextRest } = next;
|
|
141
|
-
return
|
|
139
|
+
return require_accessibility.shallowEqual(prevRest, nextRest);
|
|
142
140
|
});
|
|
143
141
|
/**
|
|
144
142
|
* Renders a slot value as a memoized React element.
|
|
@@ -196,130 +194,6 @@ function ProviderMarkdown({ content, isStreaming, className, ...config }) {
|
|
|
196
194
|
});
|
|
197
195
|
}
|
|
198
196
|
|
|
199
|
-
//#endregion
|
|
200
|
-
//#region src/generative-ui/markdown/MarkdownSurfaces.tsx
|
|
201
|
-
const FADE_STYLE_ID = "a2ui-markdown-fade";
|
|
202
|
-
/**
|
|
203
|
-
* Components fade in as they stream: each element that appears under a
|
|
204
|
-
* markdown surface runs the keyframes once on mount. React keeps the keys
|
|
205
|
-
* stable per component id, so an element that is already there never
|
|
206
|
-
* animates again. SVG internals are left out: a chart library re-creates
|
|
207
|
-
* its nodes on each render, and a fade on each of them would read as the
|
|
208
|
-
* chart flashing whenever a sibling arrives. The fade runs under reduced
|
|
209
|
-
* motion too, because it moves nothing.
|
|
210
|
-
*/
|
|
211
|
-
const FADE_CSS = ["@keyframes a2ui-fade-in{from{opacity:0}}", "[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}"].join("\n");
|
|
212
|
-
const noEffect = () => {};
|
|
213
|
-
const useInjectEffect = typeof document === "undefined" ? noEffect : react.useInsertionEffect;
|
|
214
|
-
function useFadeStyles() {
|
|
215
|
-
useInjectEffect(() => {
|
|
216
|
-
if (document.getElementById(FADE_STYLE_ID)) return;
|
|
217
|
-
const style = document.createElement("style");
|
|
218
|
-
style.id = FADE_STYLE_ID;
|
|
219
|
-
style.textContent = FADE_CSS;
|
|
220
|
-
document.head.appendChild(style);
|
|
221
|
-
}, []);
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* The default wrapper of a chat surface in the markdown transport. It draws
|
|
225
|
-
* no box: a surface sits in the flow of the reply like a paragraph, and a
|
|
226
|
-
* Card draws its own box when it is interactive. Nothing shows while the
|
|
227
|
-
* surface streams. A rejected operation gets one line.
|
|
228
|
-
*/
|
|
229
|
-
function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
|
|
230
|
-
useFadeStyles();
|
|
231
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
232
|
-
"data-generative-ui-chat-surface": surfaceId,
|
|
233
|
-
"data-a2ui-markdown-surface": surfaceId,
|
|
234
|
-
className: "cpk-markdown-chat-surface",
|
|
235
|
-
children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
236
|
-
role: "alert",
|
|
237
|
-
className: "cpk-markdown-chat-surface-error",
|
|
238
|
-
children: "Part of this UI couldn't be shown."
|
|
239
|
-
})]
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* One chat surface in the chat wrapper. Nothing renders until the surface
|
|
244
|
-
* has its root component, so a half-streamed fence shows no empty card.
|
|
245
|
-
*/
|
|
246
|
-
function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
|
|
247
|
-
const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
|
|
248
|
-
const root = surface?.model.componentsModel.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
|
|
249
|
-
if (!surface || !root && !surface.failed) return null;
|
|
250
|
-
const rejected = [...surface.serverRejected, ...surface.clientRejected];
|
|
251
|
-
const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
|
|
252
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
|
|
253
|
-
surfaceId,
|
|
254
|
-
isStreaming: surface.status === "streaming",
|
|
255
|
-
error,
|
|
256
|
-
rejected,
|
|
257
|
-
children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_chat.SurfaceView, { surface })
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
/** The blocks of one fence: lifted prose and chat surfaces, in order. */
|
|
261
|
-
function FenceBlocks({ blocks, runtime, threadId, isStreaming, markdownProps }) {
|
|
262
|
-
const Wrapper = (0, react.useContext)(require_chat.GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
|
|
263
|
-
let surfaceCount = 0;
|
|
264
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: blocks.map((block, index) => {
|
|
265
|
-
if (block.kind === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
|
|
266
|
-
...markdownProps,
|
|
267
|
-
content: block.markdown,
|
|
268
|
-
isStreaming: isStreaming && index === blocks.length - 1
|
|
269
|
-
}, `md-${surfaceCount}`);
|
|
270
|
-
surfaceCount++;
|
|
271
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChatSurface, {
|
|
272
|
-
runtime,
|
|
273
|
-
threadId,
|
|
274
|
-
surfaceId: block.surfaceId,
|
|
275
|
-
Wrapper
|
|
276
|
-
}, block.surfaceId);
|
|
277
|
-
}) });
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Experimental. Renders an assistant message of the markdown transport.
|
|
281
|
-
* Prose renders as markdown. In place of each ```a2ui fence:
|
|
282
|
-
*
|
|
283
|
-
* - the fence that created a chat surface renders that surface (and the
|
|
284
|
-
* prose lifted out of it) in the chat wrapper;
|
|
285
|
-
* - every other fence renders nothing: a fence that updates the surface of
|
|
286
|
-
* an earlier fence, or a fence for a named target, which
|
|
287
|
-
* `<GenerativeUISurface id>` renders.
|
|
288
|
-
*
|
|
289
|
-
* Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
|
|
290
|
-
* `CopilotChatAssistantMessage` uses it there on its own.
|
|
291
|
-
*
|
|
292
|
-
* @example
|
|
293
|
-
* ```tsx
|
|
294
|
-
* <MarkdownSurfaces content={message.content} messageId={message.id} />
|
|
295
|
-
* ```
|
|
296
|
-
*/
|
|
297
|
-
function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdownProps }) {
|
|
298
|
-
const runtime = require_chat.useRequiredGenerativeUIRuntime();
|
|
299
|
-
const chatThreadId = require_chat.useCopilotChatConfiguration()?.threadId;
|
|
300
|
-
require_chat.useManagerVersion(runtime);
|
|
301
|
-
const segments = (0, react.useMemo)(() => (0, _copilotkit_core.splitA2UIMarkdown)(content), [content]);
|
|
302
|
-
const threadId = chatThreadId ?? runtime.manager.getActiveThread();
|
|
303
|
-
const source = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(runtime);
|
|
304
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: segments.map((segment, index) => {
|
|
305
|
-
const isLast = index === segments.length - 1;
|
|
306
|
-
if (segment.type === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
|
|
307
|
-
...markdownProps,
|
|
308
|
-
content: segment.text,
|
|
309
|
-
isStreaming: isStreaming && isLast
|
|
310
|
-
}, `md-${index}`);
|
|
311
|
-
const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
|
|
312
|
-
if (!threadId || !blocks) return null;
|
|
313
|
-
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FenceBlocks, {
|
|
314
|
-
blocks,
|
|
315
|
-
runtime,
|
|
316
|
-
threadId,
|
|
317
|
-
isStreaming: isStreaming && isLast,
|
|
318
|
-
markdownProps
|
|
319
|
-
}, `a2ui-${segment.index}`);
|
|
320
|
-
}) });
|
|
321
|
-
}
|
|
322
|
-
|
|
323
197
|
//#endregion
|
|
324
198
|
Object.defineProperty(exports, 'CopilotIcon', {
|
|
325
199
|
enumerable: true,
|
|
@@ -339,12 +213,6 @@ Object.defineProperty(exports, 'MarkdownRendererProvider', {
|
|
|
339
213
|
return MarkdownRendererProvider;
|
|
340
214
|
}
|
|
341
215
|
});
|
|
342
|
-
Object.defineProperty(exports, 'MarkdownSurfaces', {
|
|
343
|
-
enumerable: true,
|
|
344
|
-
get: function () {
|
|
345
|
-
return MarkdownSurfaces;
|
|
346
|
-
}
|
|
347
|
-
});
|
|
348
216
|
Object.defineProperty(exports, 'ProviderMarkdown', {
|
|
349
217
|
enumerable: true,
|
|
350
218
|
get: function () {
|
|
@@ -375,4 +243,4 @@ Object.defineProperty(exports, 'useMarkdownRenderer', {
|
|
|
375
243
|
return useMarkdownRenderer;
|
|
376
244
|
}
|
|
377
245
|
});
|
|
378
|
-
//# sourceMappingURL=
|
|
246
|
+
//# sourceMappingURL=ProviderMarkdown-i_i2osOH.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProviderMarkdown-i_i2osOH.cjs","names":["StreamingMarkdownRenderer","CHAT_MARKDOWN_NODE_CLASS_NAMES","ɵcopilotIconSvgAttributes","ɵcopilotIcons","React","shallowEqual"],"sources":["../src/components/chat/StreamingMarkdownDefaultRenderer.tsx","../src/components/icons/CopilotIcon.tsx","../src/lib/slots.tsx","../src/providers/MarkdownRendererContext.tsx","../src/generative-ui/markdown/ProviderMarkdown.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownRenderer } from \"@copilotkit/markdown/react\";\nimport {\n CHAT_MARKDOWN_NODE_CLASS_NAMES,\n warnUnsupportedRichSyntaxOnce,\n} from \"@copilotkit/markdown\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * react-core's built-in default markdown renderer — a thin adapter over\n * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable\n * renderer contract (`{ content, isStreaming, className }`) onto the streaming\n * renderer for streaming-safe incremental rendering + per-token animation.\n * Still overridable via the slot/provider pluggable interface.\n */\nexport function StreamingMarkdownDefaultRenderer({\n content,\n isStreaming,\n className,\n nodeRenderers,\n caret,\n options,\n onLinkClick,\n onCitationClick,\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n if (!content) return null;\n // Dev-only: nudge upgraders from the bundled Streamdown default when their\n // content needs math/syntax highlighting the built-in renderer doesn't do.\n warnUnsupportedRichSyntaxOnce(content);\n return (\n <StreamingMarkdownRenderer\n className={className}\n isComplete={!isStreaming}\n caret={caret ?? !!isStreaming}\n nodeRenderers={nodeRenderers}\n nodeClassNames={CHAT_MARKDOWN_NODE_CLASS_NAMES}\n options={options}\n onLinkClick={onLinkClick}\n onCitationClick={onCitationClick}\n >\n {content}\n </StreamingMarkdownRenderer>\n );\n}\n\nStreamingMarkdownDefaultRenderer.displayName =\n \"StreamingMarkdownDefaultRenderer\";\n","import React, { createElement, forwardRef } from \"react\";\nimport { ɵcopilotIcons, ɵcopilotIconSvgAttributes } from \"@copilotkit/core\";\nimport type { CopilotIconName } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\n\n/** One SVG child element of an icon, such as a `<path>` or a `<circle>`. */\nexport interface IconSvgNode {\n readonly tag: string;\n readonly attributes: Readonly<Record<string, string | number>>;\n}\n\n/** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */\nfunction toReactAttributes(attributes: Readonly<Record<string, string>>) {\n return Object.fromEntries(\n Object.entries(attributes).map(([key, value]) => [\n key.replace(/-([a-z])/g, (_match, letter: string) =>\n letter.toUpperCase(),\n ),\n value,\n ]),\n );\n}\n\nconst svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);\n\n/** True when the props give the icon an accessible name or role. */\nfunction hasAccessibleProp(props: object) {\n return Object.keys(props).some(\n (key) => key.startsWith(\"aria-\") || key === \"role\" || key === \"title\",\n );\n}\n\ntype SvgProps = React.ComponentPropsWithoutRef<\"svg\">;\n\n/** Props of `IconSvg` and `CopilotIcon` that change how the icon is drawn. */\ninterface IconDrawProps extends SvgProps {\n /** Width and height of the icon. Defaults to `24`. */\n size?: number | string;\n}\n\ninterface IconSvgProps extends IconDrawProps {\n /** The Lucide icon name in kebab case, for the `lucide-<name>` class. */\n lucideName: string;\n nodes: readonly IconSvgNode[];\n}\n\n/**\n * Internal. Draws a Lucide icon from its node data, the way Lucide's React package\n * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,\n * and `aria-hidden=\"true\"` when no `aria-*`, `role` or `title` prop names it.\n */\nexport const IconSvg = forwardRef<SVGSVGElement, IconSvgProps>(function IconSvg(\n {\n lucideName,\n nodes,\n size = 24,\n color = \"currentColor\",\n strokeWidth = 2,\n className,\n children,\n ...props\n },\n ref,\n) {\n const isDecorative = !children && !hasAccessibleProp(props);\n return (\n <svg\n ref={ref}\n {...svgDefaults}\n width={size}\n height={size}\n stroke={color}\n strokeWidth={strokeWidth}\n className={cn(\"lucide\", `lucide-${lucideName}`, className)}\n aria-hidden={isDecorative || undefined}\n {...props}\n >\n {nodes.map((node, index) =>\n createElement(node.tag, { key: index, ...node.attributes }),\n )}\n {children}\n </svg>\n );\n});\n\n/** Props of `CopilotIcon`. Any other SVG prop goes on the `<svg>`. */\nexport interface CopilotIconProps extends IconDrawProps {\n /** The chat icon to draw, for example `\"ArrowUp\"`. */\n name: CopilotIconName;\n}\n\n/**\n * Draws one of the chat icons as an inline `<svg>`.\n *\n * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects\n * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden\n * from screen readers unless you give it an `aria-label`, `role` or `title`.\n *\n * @param props.name - The chat icon, for example `\"ArrowUp\"` or `\"X\"`.\n * @param props.size - Width and height. Defaults to `24`.\n * @param props.strokeWidth - Line width. Defaults to `2`.\n * @param props.color - Line color. Defaults to `currentColor`.\n *\n * @example\n * ```tsx\n * <CopilotIcon name=\"ArrowUp\" className=\"cpk-chat-input-send-icon\" />\n * <CopilotIcon name=\"X\" aria-label=\"Close\" />\n * ```\n */\nexport const CopilotIcon = forwardRef<SVGSVGElement, CopilotIconProps>(\n function CopilotIcon({ name, ...props }, ref) {\n const icon = ɵcopilotIcons[name];\n return (\n <IconSvg ref={ref} lucideName={icon.name} nodes={icon.nodes} {...props} />\n );\n },\n);\n","import React from \"react\";\nimport { cn } from \"./utils\";\nimport { shallowEqual, useShallowStableRef } from \"./shallow-stable-ref\";\n\n// Reference-stability helpers moved to ./shallow-stable-ref (a leaf module) so\n// the lean @copilotkit/react-core/headless entry can reach them without\n// pulling in this module (issue #4893). Re-exported here to preserve this\n// module's public surface for existing importers (e.g. CopilotChat).\nexport { shallowEqual, useShallowStableRef };\n\n/** Existing union (unchanged) */\nexport type SlotValue<C extends React.ComponentType<any>> =\n | C\n | string\n | Partial<React.ComponentProps<C>>;\n\n/** Utility: concrete React elements for every slot */\ntype SlotElements<S> = { [K in keyof S]: React.ReactElement };\n\nexport type WithSlots<\n S extends Record<string, React.ComponentType<any>>,\n Rest = {},\n> = {\n /** Per‑slot overrides */\n [K in keyof S]?: SlotValue<S[K]>;\n} & {\n children?: (props: SlotElements<S> & Rest) => React.ReactNode;\n} & Omit<Rest, \"children\">;\n\n/**\n * Check if a value is a React component type (function, class, forwardRef, memo, etc.)\n */\nexport function isReactComponentType(\n value: unknown,\n): value is React.ComponentType<any> {\n if (typeof value === \"function\") {\n return true;\n }\n // forwardRef, memo, lazy have $$typeof but are not valid elements\n if (\n value &&\n typeof value === \"object\" &&\n \"$$typeof\" in value &&\n !React.isValidElement(value)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Internal function to render a slot value as a React element (non-memoized).\n */\nfunction renderSlotElement(\n slot: SlotValue<React.ComponentType<any>> | undefined,\n DefaultComponent: React.ComponentType<any>,\n props: Record<string, unknown>,\n): React.ReactElement {\n if (typeof slot === \"string\") {\n // When slot is a string, treat it as a className and merge with existing className\n const existingClassName = props.className as string | undefined;\n return React.createElement(DefaultComponent, {\n ...props,\n className: cn(existingClassName, slot),\n });\n }\n\n // Check if slot is a React component type (function, forwardRef, memo, etc.)\n if (isReactComponentType(slot)) {\n return React.createElement(slot, props);\n }\n\n // If slot is a plain object (not a React element), treat it as props override\n if (slot && typeof slot === \"object\" && !React.isValidElement(slot)) {\n return React.createElement(DefaultComponent, {\n ...props,\n ...slot,\n });\n }\n\n return React.createElement(DefaultComponent, props);\n}\n\n/**\n * Internal memoized wrapper component for renderSlot.\n * Uses forwardRef to support ref forwarding.\n */\nconst MemoizedSlotWrapper = React.memo(\n React.forwardRef<unknown, any>(function MemoizedSlotWrapper(props, ref) {\n const { $slot, $component, ...rest } = props;\n const propsWithRef: Record<string, unknown> =\n ref !== null ? { ...rest, ref } : rest;\n return renderSlotElement($slot, $component, propsWithRef);\n }),\n (prev: any, next: any) => {\n // Compare slot and component references\n if (prev.$slot !== next.$slot) return false;\n if (prev.$component !== next.$component) return false;\n\n // Shallow compare remaining props (ref is handled separately by React)\n const { $slot: _ps, $component: _pc, ...prevRest } = prev;\n const { $slot: _ns, $component: _nc, ...nextRest } = next;\n return shallowEqual(\n prevRest as Record<string, unknown>,\n nextRest as Record<string, unknown>,\n );\n },\n);\n\n/**\n * Renders a slot value as a memoized React element.\n * Automatically prevents unnecessary re-renders using shallow prop comparison.\n * Supports ref forwarding.\n *\n * @example\n * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })\n */\nexport function renderSlot<\n C extends React.ComponentType<any>,\n P = React.ComponentProps<C>,\n>(\n slot: SlotValue<C> | undefined,\n DefaultComponent: C,\n props: P,\n): React.ReactElement {\n return React.createElement(MemoizedSlotWrapper, {\n ...props,\n $slot: slot,\n $component: DefaultComponent,\n } as any);\n}\n","\"use client\";\n\nimport React, { createContext, useContext } from \"react\";\nimport type { StreamingMarkdownRendererProps } from \"@copilotkit/markdown/react\";\n\n/** Props every markdown renderer (built-in or plugged-in) receives. */\nexport interface MarkdownRendererProps {\n /** Raw, possibly-partial (streaming) markdown string. */\n content: string;\n /** Hint that the message is still streaming, for cursor/affordance use. */\n isStreaming?: boolean;\n className?: string;\n}\n\n/**\n * Config for the built-in default renderer. Pass this (instead of a component)\n * as `markdownRenderer` to configure the built-in renderer without writing a\n * wrapper — e.g. `markdownRenderer={{ nodeRenderers: { codeBlock: Shiki } }}`.\n */\nexport type DefaultMarkdownRendererProps = Pick<\n StreamingMarkdownRendererProps,\n | \"nodeRenderers\"\n | \"caret\"\n | \"options\"\n | \"className\"\n | \"onLinkClick\"\n | \"onCitationClick\"\n>;\n\n/** A markdown renderer: a component, OR config for the built-in default. */\nexport type MarkdownRenderer =\n | React.ComponentType<MarkdownRendererProps>\n | DefaultMarkdownRendererProps;\n\nconst MarkdownRendererContext = createContext<MarkdownRenderer | undefined>(\n undefined,\n);\n\nexport const MarkdownRendererProvider: React.FC<{\n renderer?: MarkdownRenderer;\n children: React.ReactNode;\n}> = ({ renderer, children }) => (\n <MarkdownRendererContext.Provider value={renderer}>\n {children}\n </MarkdownRendererContext.Provider>\n);\n\n/**\n * The markdown renderer set at the provider level, or `undefined` when none was\n * supplied. Message components fall back to the built-in\n * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)\n * when this is `undefined`.\n */\nexport function useMarkdownRenderer(): MarkdownRenderer | undefined {\n return useContext(MarkdownRendererContext);\n}\n","\"use client\";\n\nimport React from \"react\";\nimport { StreamingMarkdownDefaultRenderer } from \"../../components/chat/StreamingMarkdownDefaultRenderer\";\nimport { isReactComponentType } from \"../../lib/slots\";\nimport { useMarkdownRenderer } from \"../../providers/MarkdownRendererContext\";\nimport type {\n DefaultMarkdownRendererProps,\n MarkdownRendererProps,\n} from \"../../providers/MarkdownRendererContext\";\n\n/**\n * Markdown prose inside generative UI, rendered like the chat text around\n * it: the renderer set on the provider when there is one, else the built-in\n * streaming renderer. Config passed here wins over provider config.\n */\nexport function ProviderMarkdown({\n content,\n isStreaming,\n className,\n ...config\n}: MarkdownRendererProps & DefaultMarkdownRendererProps) {\n const renderer = useMarkdownRenderer();\n if (renderer && isReactComponentType(renderer)) {\n const Renderer = renderer;\n return (\n <Renderer\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n }\n return (\n <StreamingMarkdownDefaultRenderer\n {...(renderer as DefaultMarkdownRendererProps | undefined)}\n {...config}\n content={content}\n isStreaming={isStreaming}\n className={className}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,SAAgB,iCAAiC,EAC/C,SACA,aACA,WACA,eACA,OACA,SACA,aACA,mBACuD;AACvD,KAAI,CAAC,QAAS,QAAO;AAGrB,yDAA8B,QAAQ;AACtC,QACE,2CAACA;EACY;EACX,YAAY,CAAC;EACb,OAAO,SAAS,CAAC,CAAC;EACH;EACf,gBAAgBC;EACP;EACI;EACI;YAEhB;GACyB;;AAIhC,iCAAiC,cAC/B;;;;;ACvCF,SAAS,kBAAkB,YAA8C;AACvE,QAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,KAAK,WAAW,CAC/C,IAAI,QAAQ,cAAc,QAAQ,WAChC,OAAO,aAAa,CACrB,EACD,MACD,CAAC,CACH;;AAGH,MAAM,cAAc,kBAAkBC,2CAA0B;;AAGhE,SAAS,kBAAkB,OAAe;AACxC,QAAO,OAAO,KAAK,MAAM,CAAC,MACvB,QAAQ,IAAI,WAAW,QAAQ,IAAI,QAAQ,UAAU,QAAQ,QAC/D;;;;;;;AAsBH,MAAa,gCAAkD,SAAS,QACtE,EACE,YACA,OACA,OAAO,IACP,QAAQ,gBACR,cAAc,GACd,WACA,UACA,GAAG,SAEL,KACA;CACA,MAAM,eAAe,CAAC,YAAY,CAAC,kBAAkB,MAAM;AAC3D,QACE,4CAAC;EACM;EACL,GAAI;EACJ,OAAO;EACP,QAAQ;EACR,QAAQ;EACK;EACb,qCAAc,UAAU,UAAU,cAAc,UAAU;EAC1D,eAAa,gBAAgB;EAC7B,GAAI;aAEH,MAAM,KAAK,MAAM,mCACF,KAAK,KAAK;GAAE,KAAK;GAAO,GAAG,KAAK;GAAY,CAAC,CAC5D,EACA;GACG;EAER;;;;;;;;;;;;;;;;;;;AA0BF,MAAa,oCACX,SAAS,YAAY,EAAE,MAAM,GAAG,SAAS,KAAK;CAC5C,MAAM,OAAOC,+BAAc;AAC3B,QACE,2CAAC;EAAa;EAAK,YAAY,KAAK;EAAM,OAAO,KAAK;EAAO,GAAI;GAAS;EAG/E;;;;;;;ACpFD,SAAgB,qBACd,OACmC;AACnC,KAAI,OAAO,UAAU,WACnB,QAAO;AAGT,KACE,SACA,OAAO,UAAU,YACjB,cAAc,SACd,CAACC,cAAM,eAAe,MAAM,CAE5B,QAAO;AAET,QAAO;;;;;AAMT,SAAS,kBACP,MACA,kBACA,OACoB;AACpB,KAAI,OAAO,SAAS,UAAU;EAE5B,MAAM,oBAAoB,MAAM;AAChC,SAAOA,cAAM,cAAc,kBAAkB;GAC3C,GAAG;GACH,qCAAc,mBAAmB,KAAK;GACvC,CAAC;;AAIJ,KAAI,qBAAqB,KAAK,CAC5B,QAAOA,cAAM,cAAc,MAAM,MAAM;AAIzC,KAAI,QAAQ,OAAO,SAAS,YAAY,CAACA,cAAM,eAAe,KAAK,CACjE,QAAOA,cAAM,cAAc,kBAAkB;EAC3C,GAAG;EACH,GAAG;EACJ,CAAC;AAGJ,QAAOA,cAAM,cAAc,kBAAkB,MAAM;;;;;;AAOrD,MAAM,sBAAsBA,cAAM,KAChCA,cAAM,WAAyB,SAAS,oBAAoB,OAAO,KAAK;CACtE,MAAM,EAAE,OAAO,YAAY,GAAG,SAAS;AAGvC,QAAO,kBAAkB,OAAO,YAD9B,QAAQ,OAAO;EAAE,GAAG;EAAM;EAAK,GAAG,KACqB;EACzD,GACD,MAAW,SAAc;AAExB,KAAI,KAAK,UAAU,KAAK,MAAO,QAAO;AACtC,KAAI,KAAK,eAAe,KAAK,WAAY,QAAO;CAGhD,MAAM,EAAE,OAAO,KAAK,YAAY,KAAK,GAAG,aAAa;CACrD,MAAM,EAAE,OAAO,KAAK,YAAY,KAAK,GAAG,aAAa;AACrD,QAAOC,mCACL,UACA,SACD;EAEJ;;;;;;;;;AAUD,SAAgB,WAId,MACA,kBACA,OACoB;AACpB,QAAOD,cAAM,cAAc,qBAAqB;EAC9C,GAAG;EACH,OAAO;EACP,YAAY;EACb,CAAQ;;;;;AC/FX,MAAM,mDACJ,OACD;AAED,MAAa,4BAGP,EAAE,UAAU,eAChB,2CAAC,wBAAwB;CAAS,OAAO;CACtC;EACgC;;;;;;;AASrC,SAAgB,sBAAoD;AAClE,8BAAkB,wBAAwB;;;;;;;;;;ACtC5C,SAAgB,iBAAiB,EAC/B,SACA,aACA,WACA,GAAG,UACoD;CACvD,MAAM,WAAW,qBAAqB;AACtC,KAAI,YAAY,qBAAqB,SAAS,CAE5C,QACE,2CAFe;EAGJ;EACI;EACF;GACX;AAGN,QACE,2CAAC;EACC,GAAK;EACL,GAAI;EACK;EACI;EACF;GACX"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ɵshallowEqualRecord } from "@copilotkit/core";
|
|
2
|
+
import { createContext, useContext, useMemo, useRef } from "react";
|
|
3
|
+
import { accessibilityAttributes, accessibilityAttributes as accessibilityAttributes$1, controlAria, namedRole, readAccessibility, reportErrorSafely, wrapperAria } from "@copilotkit/core/generative-ui";
|
|
4
|
+
import { catalogIdsOf, createGenerativeUI, setterNameOf } from "@copilotkit/shared/generative-ui";
|
|
5
|
+
|
|
6
|
+
//#region src/lib/shallow-stable-ref.ts
|
|
7
|
+
/**
|
|
8
|
+
* Shallow equality comparison for objects: same own keys, each holding the
|
|
9
|
+
* same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
|
|
10
|
+
*/
|
|
11
|
+
function shallowEqual(obj1, obj2) {
|
|
12
|
+
return ɵshallowEqualRecord(obj1, obj2);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
|
|
16
|
+
* class instances, and other exotic objects that happen to have typeof "object".
|
|
17
|
+
*/
|
|
18
|
+
function isPlainObject(obj) {
|
|
19
|
+
return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Returns the same reference as long as the value is shallowly equal to the
|
|
23
|
+
* previous render's value.
|
|
24
|
+
*
|
|
25
|
+
* - Identical references bail out immediately (O(1)).
|
|
26
|
+
* - Plain objects ({}) are shallow-compared key-by-key.
|
|
27
|
+
* - Arrays, Dates, class instances, functions, and primitives are compared by
|
|
28
|
+
* reference only — shallowEqual is never called on non-plain objects, which
|
|
29
|
+
* avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
|
|
30
|
+
*
|
|
31
|
+
* Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
|
|
32
|
+
* equality check isn't defeated by a new object reference on every render.
|
|
33
|
+
*/
|
|
34
|
+
function useShallowStableRef(value) {
|
|
35
|
+
const ref = useRef(value);
|
|
36
|
+
if (ref.current === value) return ref.current;
|
|
37
|
+
if (isPlainObject(ref.current) && isPlainObject(value)) {
|
|
38
|
+
if (shallowEqual(ref.current, value)) return ref.current;
|
|
39
|
+
}
|
|
40
|
+
ref.current = value;
|
|
41
|
+
return ref.current;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/generative-ui/runtime-context.ts
|
|
46
|
+
const GenerativeUIRuntimeContext = createContext(null);
|
|
47
|
+
function useGenerativeUIRuntime() {
|
|
48
|
+
return useContext(GenerativeUIRuntimeContext);
|
|
49
|
+
}
|
|
50
|
+
function useRequiredGenerativeUIRuntime() {
|
|
51
|
+
const runtime = useContext(GenerativeUIRuntimeContext);
|
|
52
|
+
if (!runtime) throw new Error("Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.");
|
|
53
|
+
return runtime;
|
|
54
|
+
}
|
|
55
|
+
const GenerativeUINodeContext = createContext(null);
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/generative-ui/catalog.ts
|
|
59
|
+
/**
|
|
60
|
+
* Experimental. Declares the components the model can render, the app state
|
|
61
|
+
* they read, and the functions they call.
|
|
62
|
+
*
|
|
63
|
+
* - A prop with the name of a top-level state key is bound to that state.
|
|
64
|
+
* - `bind: { prop: (state, props) => value }` binds a prop to a selector.
|
|
65
|
+
* - An event binds to the function with its name, else to the name without
|
|
66
|
+
* `on` (`onAddToCart` calls `addToCart`).
|
|
67
|
+
* - `writable: ["value"]` gives the component a `setValue` prop. See
|
|
68
|
+
* `GenerativeUIComponentDefinition.writable`.
|
|
69
|
+
*
|
|
70
|
+
* The model does not see bound props or matched events.
|
|
71
|
+
*
|
|
72
|
+
* @param config - `id`, then optional `extends`, `state`, `functions` and
|
|
73
|
+
* `overrides`, then `components`. Put `state` before `components`, so the selectors
|
|
74
|
+
* get typed state.
|
|
75
|
+
* @throws Error when a name comes from two places, an override names no
|
|
76
|
+
* component of the bases, `props` is not an object
|
|
77
|
+
* schema with a JSON Schema, a key is reserved or used
|
|
78
|
+
* twice on a component, an event matches two functions, an unmatched event
|
|
79
|
+
* has no `parameters`, a `bind` key is not a prop, a `writable` key is not
|
|
80
|
+
* a prop or is a bound prop, or a setter name is already a key of the
|
|
81
|
+
* component. Also throws when `parameterOrder` contains duplicate or unknown
|
|
82
|
+
* keys, or an ordered component declares integer-index keys whose JSON object
|
|
83
|
+
* enumeration order cannot be controlled.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* const ui = createGenerativeUI({
|
|
88
|
+
* id: "acme/store@1",
|
|
89
|
+
* state: { cart: cartSchema },
|
|
90
|
+
* functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
|
|
91
|
+
* components: {
|
|
92
|
+
* CartSummary: {
|
|
93
|
+
* component: CartSummary,
|
|
94
|
+
* props: z.object({ count: z.number() }),
|
|
95
|
+
* bind: { count: (state) => state.cart.count },
|
|
96
|
+
* },
|
|
97
|
+
* },
|
|
98
|
+
* });
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
function createGenerativeUI$1(config) {
|
|
102
|
+
return createGenerativeUI(config);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/generative-ui/accessibility.ts
|
|
107
|
+
/**
|
|
108
|
+
* Experimental. The ARIA attributes of the `accessibility` that the model
|
|
109
|
+
* gave the component being rendered, to spread on its root element. The
|
|
110
|
+
* standard components do this; a custom component does it itself:
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```tsx
|
|
114
|
+
* function Panel({ children }: { children?: ReactNode }) {
|
|
115
|
+
* const aria = useGenerativeUIAccessibility();
|
|
116
|
+
* return <section {...aria}>{children}</section>;
|
|
117
|
+
* }
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* Outside of generated UI it gives `{}`.
|
|
121
|
+
*/
|
|
122
|
+
function useGenerativeUIAccessibility() {
|
|
123
|
+
const accessibility = useContext(GenerativeUINodeContext)?.accessibility;
|
|
124
|
+
return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
//#endregion
|
|
128
|
+
export { useGenerativeUIAccessibility as a, createGenerativeUI$1 as c, GenerativeUIRuntimeContext as d, reportErrorSafely as f, useShallowStableRef as g, shallowEqual as h, readAccessibility as i, setterNameOf as l, useRequiredGenerativeUIRuntime as m, controlAria as n, wrapperAria as o, useGenerativeUIRuntime as p, namedRole as r, catalogIdsOf as s, accessibilityAttributes$1 as t, GenerativeUINodeContext as u };
|
|
129
|
+
//# sourceMappingURL=accessibility-BLK-gE0R.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accessibility-BLK-gE0R.mjs","names":["createGenerativeUI","createSharedGenerativeUI"],"sources":["../src/lib/shallow-stable-ref.ts","../src/generative-ui/runtime-context.ts","../src/generative-ui/catalog.ts","../src/generative-ui/accessibility.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport { ɵshallowEqualRecord } from \"@copilotkit/core\";\n\n// Reference-stability helpers, kept in their own leaf module (not in ./slots)\n// so that DOM-free consumers — e.g. CopilotChatConfigurationProvider, which is\n// re-exported from the lean `@copilotkit/react-core/headless` entry — reach\n// them without pulling in the slot rendering code (issue #4893).\n\n/**\n * Shallow equality comparison for objects: same own keys, each holding the\n * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n) {\n return ɵshallowEqualRecord(obj1, obj2);\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n","import { createContext, useContext } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { GenerativeUIUserEvent } from \"@copilotkit/shared\";\nimport type { GenerativeUIAccessibility } from \"./accessibility\";\nimport type { GenerativeUI } from \"./catalog\";\nimport type { GenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIErrorInfo,\n GenerativeUIInvokeResult,\n} from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUITheme } from \"@copilotkit/shared/generative-ui\";\n\nexport type { GenerativeUITheme };\n\nexport interface GenerativeUIErrorBoundaryConfig {\n /**\n * Replaces the host's fallback for a component that failed to render. It\n * is not used for invalid props, unknown types, cyclic references or a\n * failed surface: the host's `NodeFallback` shows those. If it throws,\n * the host's fallback stands in and the error is reported. `error` is\n * always an Error: a component that throws something else (a string,\n * `undefined`) gets an Error that describes it, with the value as its\n * `cause`.\n */\n fallback?: (props: {\n error: Error;\n retry: () => void;\n surfaceId: string;\n componentId: string;\n }) => ReactNode;\n /**\n * Called for render, props, operation, function and event failures. A\n * render or props failure that stays the same across new revisions of the\n * node or the surface is reported once, until the node or surface renders\n * again. A failed function or event is reported on every call.\n */\n onError?: (info: GenerativeUIErrorInfo) => void;\n}\n\ninterface GenerativeUIBaseConfig {\n /**\n * The result of `createGenerativeUI`: the components the model can render,\n * the app state they read and the functions they call.\n */\n ui: GenerativeUI;\n /**\n * The agents that get the generative UI. When omitted, every agent gets\n * it. Other agents get no envelope.\n */\n agentIds?: string[];\n /**\n * Web only. Values for the `--a2ui-*` CSS variables and the map style.\n * Top-level values apply in both modes. `dark` changes them in dark mode,\n * which is on under a `.dark` class, like the CopilotKit chat. React\n * Native ignores it.\n */\n theme?: GenerativeUITheme;\n /** Fallback UI and error reporting for generated UI. */\n errorBoundary?: GenerativeUIErrorBoundaryConfig;\n}\n\n/**\n * The tool transport: the model calls the `render_ui` tool, and the runtime\n * validates each operation before it streams it to the client.\n */\nexport interface GenerativeUIToolConfig extends GenerativeUIBaseConfig {\n /** Leave it out, or set \"tool\". */\n transport?: \"tool\";\n // Markdown-only options. `never` makes them a type error here, also when\n // `transport` is left out.\n sendContext?: never;\n includeCatalog?: never;\n}\n\n/**\n * The markdown transport: the model writes the operations in ```a2ui fences\n * in its reply. The client reads and validates them.\n */\nexport interface GenerativeUIMarkdownConfig extends GenerativeUIBaseConfig {\n transport: \"markdown\";\n /**\n * Send the component schema and the fence guideline as context entries.\n * Set `false` when the backend builds its own prompt from the envelope.\n * Default `true`.\n */\n sendContext?: boolean;\n /**\n * Send the component schemas in the envelope (`catalog.components`).\n * Default `true`.\n */\n includeCatalog?: boolean;\n}\n\n/**\n * Experimental. The `generativeUI` prop of `CopilotKitProvider`. Set\n * `transport: \"markdown\"` to get the markdown options.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider generativeUI={{ ui }} />\n * <CopilotKitProvider generativeUI={{ ui, transport: \"markdown\", sendContext: false }} />\n * ```\n */\nexport type GenerativeUIConfig =\n | GenerativeUIToolConfig\n | GenerativeUIMarkdownConfig;\n\nexport interface GenerativeUIRuntime {\n manager: GenerativeUISurfaceManager;\n dispatcher: GenerativeUIDispatcher;\n /** The generative UI given to the provider as `generativeUI={{ ui }}`. */\n ui: GenerativeUI;\n /** How the model sends operations. \"tool\" when the config leaves it out. */\n transport: \"tool\" | \"markdown\";\n /** The latest `generativeUI` config of the provider. */\n readonly config: GenerativeUIConfig;\n /**\n * The latest `theme`. The host's surface root gets it: on the web it sets\n * the CSS variables; the React Native root ignores it.\n */\n theme?: GenerativeUITheme;\n forwardEvent: (\n event: GenerativeUIUserEvent,\n agentId: string | undefined,\n ) => Promise<GenerativeUIInvokeResult>;\n reportError: (info: GenerativeUIErrorInfo) => void;\n readonly errorFallback?: GenerativeUIErrorBoundaryConfig[\"fallback\"];\n}\n\nexport const GenerativeUIRuntimeContext =\n createContext<GenerativeUIRuntime | null>(null);\n\nexport function useGenerativeUIRuntime(): GenerativeUIRuntime | null {\n return useContext(GenerativeUIRuntimeContext);\n}\n\nexport function useRequiredGenerativeUIRuntime(): GenerativeUIRuntime {\n const runtime = useContext(GenerativeUIRuntimeContext);\n if (!runtime) {\n throw new Error(\n \"Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.\",\n );\n }\n return runtime;\n}\n\nexport { reportErrorSafely } from \"@copilotkit/core/generative-ui\";\n\nexport interface GenerativeUINodeContextValue {\n surfaceKey: string;\n surfaceId: string;\n componentId: string;\n /** The resolved `accessibility` of the component envelope, if any. */\n accessibility?: GenerativeUIAccessibility;\n}\n\nexport const GenerativeUINodeContext =\n createContext<GenerativeUINodeContextValue | null>(null);\n","import type { ComponentType, ReactNode } from \"react\";\nimport { createGenerativeUI as createSharedGenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport type {\n AnyGenerativeUI,\n CreateGenerativeUIConfig as SharedCreateGenerativeUIConfig,\n GenerativeUI as SharedGenerativeUI,\n GenerativeUIBasesDefinitions,\n GenerativeUIComponentDefinition as SharedGenerativeUIComponentDefinition,\n GenerativeUIComponentProps as SharedGenerativeUIComponentProps,\n GenerativeUIDefinitions,\n GenerativeUIFunctionDefinition,\n GenerativeUIResultDefinitions,\n GenerativeUISchema,\n ResolvedGenerativeUIComponent as SharedResolvedGenerativeUIComponent,\n} from \"@copilotkit/shared/generative-ui\";\n\n// The catalog is framework-free and lives in `@copilotkit/shared/generative-ui`.\n// These types pin its component type to React components and its rendered\n// child type to `ReactNode`.\n\nexport {\n catalogIdsOf,\n componentCatalogIds,\n setterNameOf,\n} from \"@copilotkit/shared/generative-ui\";\nexport type {\n GenerativeUIComponentName,\n GenerativeUIDefinitionsOf,\n GenerativeUIEventDefinition,\n GenerativeUIEventInput,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionDefinition,\n GenerativeUIFunctionInput,\n GenerativeUIFunctionName,\n GenerativeUIFunctionsOf,\n GenerativeUISelector,\n GenerativeUISlotKind,\n GenerativeUIStateOf,\n PropsSchema,\n UnionToIntersection,\n} from \"@copilotkit/shared/generative-ui\";\n\n/** One component of a generative UI, as the renderer reads it. */\nexport type GenerativeUIComponentDefinition =\n SharedGenerativeUIComponentDefinition<ComponentType<any>>;\n\n/** A component after `createGenerativeUI` resolved its bindings. */\nexport type ResolvedGenerativeUIComponent = SharedResolvedGenerativeUIComponent<\n ComponentType<any>\n>;\n\n/**\n * Experimental. The result of `createGenerativeUI`: the components the model\n * can render, the app state they read, and the functions they call. Give it\n * to the provider (`generativeUI={{ ui }}`) and to the typed hooks.\n */\nexport type GenerativeUI<\n Definitions extends GenerativeUIDefinitions = GenerativeUIDefinitions,\n> = SharedGenerativeUI<Definitions, ComponentType<any>>;\n\n/**\n * Props that the renderer passes to a component:\n * `function CheckoutForm(props: GenerativeUIComponentProps<typeof ui, \"CheckoutForm\">)`.\n * Data props are the parsed `props` schema, bound props included. Event and\n * slot props are present only when they are bound or filled. Each writable\n * prop gets a setter (`value` gets `setValue`), which is always present.\n */\nexport type GenerativeUIComponentProps<\n UI extends AnyGenerativeUI,\n Name extends keyof NonNullable<UI[\"definitions\"]>[\"components\"] & string,\n> = SharedGenerativeUIComponentProps<UI, Name, ReactNode>;\n\n/** One new React component for each component of the bases that it names. */\ntype OverridesConfig<Bases extends readonly AnyGenerativeUI[]> = {\n [Name in keyof GenerativeUIBasesDefinitions<Bases>[\"components\"] & string]?: {\n component: ComponentType<\n GenerativeUIBasesDefinitions<Bases> extends infer Definitions extends\n GenerativeUIDefinitions\n ? GenerativeUIComponentProps<GenerativeUI<Definitions>, Name>\n : never\n >;\n };\n};\n\n/** The config of `createGenerativeUI`. */\nexport type CreateGenerativeUIConfig<\n Bases extends readonly AnyGenerativeUI[],\n State extends Record<string, GenerativeUISchema>,\n Functions extends Record<string, GenerativeUIFunctionDefinition>,\n Props extends Record<string, unknown>,\n Events extends Record<string, unknown>,\n Slots extends Record<string, unknown>,\n Writable extends Record<string, unknown>,\n> = SharedCreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable,\n OverridesConfig<Bases>\n>;\n\n/**\n * Experimental. Declares the components the model can render, the app state\n * they read, and the functions they call.\n *\n * - A prop with the name of a top-level state key is bound to that state.\n * - `bind: { prop: (state, props) => value }` binds a prop to a selector.\n * - An event binds to the function with its name, else to the name without\n * `on` (`onAddToCart` calls `addToCart`).\n * - `writable: [\"value\"]` gives the component a `setValue` prop. See\n * `GenerativeUIComponentDefinition.writable`.\n *\n * The model does not see bound props or matched events.\n *\n * @param config - `id`, then optional `extends`, `state`, `functions` and\n * `overrides`, then `components`. Put `state` before `components`, so the selectors\n * get typed state.\n * @throws Error when a name comes from two places, an override names no\n * component of the bases, `props` is not an object\n * schema with a JSON Schema, a key is reserved or used\n * twice on a component, an event matches two functions, an unmatched event\n * has no `parameters`, a `bind` key is not a prop, a `writable` key is not\n * a prop or is a bound prop, or a setter name is already a key of the\n * component. Also throws when `parameterOrder` contains duplicate or unknown\n * keys, or an ordered component declares integer-index keys whose JSON object\n * enumeration order cannot be controlled.\n *\n * @example\n * ```ts\n * const ui = createGenerativeUI({\n * id: \"acme/store@1\",\n * state: { cart: cartSchema },\n * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },\n * components: {\n * CartSummary: {\n * component: CartSummary,\n * props: z.object({ count: z.number() }),\n * bind: { count: (state) => state.cart.count },\n * },\n * },\n * });\n * ```\n */\nexport function createGenerativeUI<\n Bases extends readonly AnyGenerativeUI[] = [],\n State extends Record<string, GenerativeUISchema> = {},\n Functions extends Record<string, GenerativeUIFunctionDefinition> = {},\n Props extends Record<string, unknown> = {},\n Events extends Record<string, unknown> = {},\n Slots extends Record<string, unknown> = {},\n Writable extends Record<string, unknown> = {},\n>(\n config: CreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >,\n) {\n // The React config only narrows the shared one (React component types),\n // so the shared runtime builds the same UI.\n const build = createSharedGenerativeUI as (config: unknown) => unknown;\n return build(config) as GenerativeUI<\n GenerativeUIResultDefinitions<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >\n >;\n}\n","import { useContext, useMemo } from \"react\";\nimport { accessibilityAttributes } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUIAriaAttributes } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUINodeContext } from \"./runtime-context\";\n\n// The accessibility helpers are framework-free and live in\n// `@copilotkit/core/generative-ui`. The standard components import them\n// from here.\nexport {\n accessibilityAttributes,\n controlAria,\n namedRole,\n readAccessibility,\n wrapperAria,\n} from \"@copilotkit/core/generative-ui\";\nexport type {\n GenerativeUIAccessibility,\n GenerativeUIAriaAttributes,\n} from \"@copilotkit/core/generative-ui\";\n\n/**\n * Experimental. The ARIA attributes of the `accessibility` that the model\n * gave the component being rendered, to spread on its root element. The\n * standard components do this; a custom component does it itself:\n *\n * @example\n * ```tsx\n * function Panel({ children }: { children?: ReactNode }) {\n * const aria = useGenerativeUIAccessibility();\n * return <section {...aria}>{children}</section>;\n * }\n * ```\n *\n * Outside of generated UI it gives `{}`.\n */\nexport function useGenerativeUIAccessibility(): GenerativeUIAriaAttributes {\n const node = useContext(GenerativeUINodeContext);\n const accessibility = node?.accessibility;\n return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAgB,aACd,MACA,MACA;AACA,QAAO,oBAAoB,MAAM,KAAK;;;;;;AAOxC,SAAS,cAAc,KAA8C;AACnE,QACE,QAAQ,QACR,OAAO,QAAQ,YACf,OAAO,UAAU,SAAS,KAAK,IAAI,KAAK;;;;;;;;;;;;;;;AAiB5C,SAAgB,oBAAuB,OAAa;CAClD,MAAM,MAAM,OAAO,MAAM;AAGzB,KAAI,IAAI,YAAY,MAAO,QAAO,IAAI;AAGtC,KAAI,cAAc,IAAI,QAAQ,IAAI,cAAc,MAAM,EACpD;MAAI,aAAa,IAAI,SAAS,MAAM,CAAE,QAAO,IAAI;;AAInD,KAAI,UAAU;AACd,QAAO,IAAI;;;;;ACyEb,MAAa,6BACX,cAA0C,KAAK;AAEjD,SAAgB,yBAAqD;AACnE,QAAO,WAAW,2BAA2B;;AAG/C,SAAgB,iCAAsD;CACpE,MAAM,UAAU,WAAW,2BAA2B;AACtD,KAAI,CAAC,QACH,OAAM,IAAI,MACR,2NACD;AAEH,QAAO;;AAaT,MAAa,0BACX,cAAmD,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACZ1D,SAAgBA,qBASd,QASA;AAIA,QADcC,mBACD,OAAO;;;;;;;;;;;;;;;;;;;;ACrItB,SAAgB,+BAA2D;CAEzE,MAAM,gBADO,WAAW,wBAAwB,EACpB;AAC5B,QAAO,cAAc,wBAAwB,cAAc,EAAE,CAAC,cAAc,CAAC"}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __exportAll = (all, no_symbols) => {
|
|
9
|
+
let target = {};
|
|
10
|
+
for (var name in all) {
|
|
11
|
+
__defProp(target, name, {
|
|
12
|
+
get: all[name],
|
|
13
|
+
enumerable: true
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
if (!no_symbols) {
|
|
17
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
18
|
+
}
|
|
19
|
+
return target;
|
|
20
|
+
};
|
|
21
|
+
var __copyProps = (to, from, except, desc) => {
|
|
22
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
+
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
24
|
+
key = keys[i];
|
|
25
|
+
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
26
|
+
__defProp(to, key, {
|
|
27
|
+
get: ((k) => from[k]).bind(null, key),
|
|
28
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return to;
|
|
34
|
+
};
|
|
35
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
36
|
+
value: mod,
|
|
37
|
+
enumerable: true
|
|
38
|
+
}) : target, mod));
|
|
39
|
+
|
|
40
|
+
//#endregion
|
|
41
|
+
let _copilotkit_core = require("@copilotkit/core");
|
|
42
|
+
let react = require("react");
|
|
43
|
+
let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
|
|
44
|
+
let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
|
|
45
|
+
|
|
46
|
+
//#region src/lib/shallow-stable-ref.ts
|
|
47
|
+
/**
|
|
48
|
+
* Shallow equality comparison for objects: same own keys, each holding the
|
|
49
|
+
* same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
|
|
50
|
+
*/
|
|
51
|
+
function shallowEqual(obj1, obj2) {
|
|
52
|
+
return (0, _copilotkit_core.ɵshallowEqualRecord)(obj1, obj2);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
|
|
56
|
+
* class instances, and other exotic objects that happen to have typeof "object".
|
|
57
|
+
*/
|
|
58
|
+
function isPlainObject(obj) {
|
|
59
|
+
return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Returns the same reference as long as the value is shallowly equal to the
|
|
63
|
+
* previous render's value.
|
|
64
|
+
*
|
|
65
|
+
* - Identical references bail out immediately (O(1)).
|
|
66
|
+
* - Plain objects ({}) are shallow-compared key-by-key.
|
|
67
|
+
* - Arrays, Dates, class instances, functions, and primitives are compared by
|
|
68
|
+
* reference only — shallowEqual is never called on non-plain objects, which
|
|
69
|
+
* avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
|
|
70
|
+
*
|
|
71
|
+
* Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
|
|
72
|
+
* equality check isn't defeated by a new object reference on every render.
|
|
73
|
+
*/
|
|
74
|
+
function useShallowStableRef(value) {
|
|
75
|
+
const ref = (0, react.useRef)(value);
|
|
76
|
+
if (ref.current === value) return ref.current;
|
|
77
|
+
if (isPlainObject(ref.current) && isPlainObject(value)) {
|
|
78
|
+
if (shallowEqual(ref.current, value)) return ref.current;
|
|
79
|
+
}
|
|
80
|
+
ref.current = value;
|
|
81
|
+
return ref.current;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/generative-ui/runtime-context.ts
|
|
86
|
+
const GenerativeUIRuntimeContext = (0, react.createContext)(null);
|
|
87
|
+
function useGenerativeUIRuntime() {
|
|
88
|
+
return (0, react.useContext)(GenerativeUIRuntimeContext);
|
|
89
|
+
}
|
|
90
|
+
function useRequiredGenerativeUIRuntime() {
|
|
91
|
+
const runtime = (0, react.useContext)(GenerativeUIRuntimeContext);
|
|
92
|
+
if (!runtime) throw new Error("Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.");
|
|
93
|
+
return runtime;
|
|
94
|
+
}
|
|
95
|
+
const GenerativeUINodeContext = (0, react.createContext)(null);
|
|
96
|
+
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/generative-ui/catalog.ts
|
|
99
|
+
/**
|
|
100
|
+
* Experimental. Declares the components the model can render, the app state
|
|
101
|
+
* they read, and the functions they call.
|
|
102
|
+
*
|
|
103
|
+
* - A prop with the name of a top-level state key is bound to that state.
|
|
104
|
+
* - `bind: { prop: (state, props) => value }` binds a prop to a selector.
|
|
105
|
+
* - An event binds to the function with its name, else to the name without
|
|
106
|
+
* `on` (`onAddToCart` calls `addToCart`).
|
|
107
|
+
* - `writable: ["value"]` gives the component a `setValue` prop. See
|
|
108
|
+
* `GenerativeUIComponentDefinition.writable`.
|
|
109
|
+
*
|
|
110
|
+
* The model does not see bound props or matched events.
|
|
111
|
+
*
|
|
112
|
+
* @param config - `id`, then optional `extends`, `state`, `functions` and
|
|
113
|
+
* `overrides`, then `components`. Put `state` before `components`, so the selectors
|
|
114
|
+
* get typed state.
|
|
115
|
+
* @throws Error when a name comes from two places, an override names no
|
|
116
|
+
* component of the bases, `props` is not an object
|
|
117
|
+
* schema with a JSON Schema, a key is reserved or used
|
|
118
|
+
* twice on a component, an event matches two functions, an unmatched event
|
|
119
|
+
* has no `parameters`, a `bind` key is not a prop, a `writable` key is not
|
|
120
|
+
* a prop or is a bound prop, or a setter name is already a key of the
|
|
121
|
+
* component. Also throws when `parameterOrder` contains duplicate or unknown
|
|
122
|
+
* keys, or an ordered component declares integer-index keys whose JSON object
|
|
123
|
+
* enumeration order cannot be controlled.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* const ui = createGenerativeUI({
|
|
128
|
+
* id: "acme/store@1",
|
|
129
|
+
* state: { cart: cartSchema },
|
|
130
|
+
* functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
|
|
131
|
+
* components: {
|
|
132
|
+
* CartSummary: {
|
|
133
|
+
* component: CartSummary,
|
|
134
|
+
* props: z.object({ count: z.number() }),
|
|
135
|
+
* bind: { count: (state) => state.cart.count },
|
|
136
|
+
* },
|
|
137
|
+
* },
|
|
138
|
+
* });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
function createGenerativeUI(config) {
|
|
142
|
+
return (0, _copilotkit_shared_generative_ui.createGenerativeUI)(config);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/generative-ui/accessibility.ts
|
|
147
|
+
/**
|
|
148
|
+
* Experimental. The ARIA attributes of the `accessibility` that the model
|
|
149
|
+
* gave the component being rendered, to spread on its root element. The
|
|
150
|
+
* standard components do this; a custom component does it itself:
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```tsx
|
|
154
|
+
* function Panel({ children }: { children?: ReactNode }) {
|
|
155
|
+
* const aria = useGenerativeUIAccessibility();
|
|
156
|
+
* return <section {...aria}>{children}</section>;
|
|
157
|
+
* }
|
|
158
|
+
* ```
|
|
159
|
+
*
|
|
160
|
+
* Outside of generated UI it gives `{}`.
|
|
161
|
+
*/
|
|
162
|
+
function useGenerativeUIAccessibility() {
|
|
163
|
+
const accessibility = (0, react.useContext)(GenerativeUINodeContext)?.accessibility;
|
|
164
|
+
return (0, react.useMemo)(() => (0, _copilotkit_core_generative_ui.accessibilityAttributes)(accessibility), [accessibility]);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
//#endregion
|
|
168
|
+
Object.defineProperty(exports, 'GenerativeUINodeContext', {
|
|
169
|
+
enumerable: true,
|
|
170
|
+
get: function () {
|
|
171
|
+
return GenerativeUINodeContext;
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
Object.defineProperty(exports, 'GenerativeUIRuntimeContext', {
|
|
175
|
+
enumerable: true,
|
|
176
|
+
get: function () {
|
|
177
|
+
return GenerativeUIRuntimeContext;
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
Object.defineProperty(exports, '__exportAll', {
|
|
181
|
+
enumerable: true,
|
|
182
|
+
get: function () {
|
|
183
|
+
return __exportAll;
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
Object.defineProperty(exports, '__toESM', {
|
|
187
|
+
enumerable: true,
|
|
188
|
+
get: function () {
|
|
189
|
+
return __toESM;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
Object.defineProperty(exports, 'createGenerativeUI', {
|
|
193
|
+
enumerable: true,
|
|
194
|
+
get: function () {
|
|
195
|
+
return createGenerativeUI;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
Object.defineProperty(exports, 'shallowEqual', {
|
|
199
|
+
enumerable: true,
|
|
200
|
+
get: function () {
|
|
201
|
+
return shallowEqual;
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
Object.defineProperty(exports, 'useGenerativeUIAccessibility', {
|
|
205
|
+
enumerable: true,
|
|
206
|
+
get: function () {
|
|
207
|
+
return useGenerativeUIAccessibility;
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
Object.defineProperty(exports, 'useGenerativeUIRuntime', {
|
|
211
|
+
enumerable: true,
|
|
212
|
+
get: function () {
|
|
213
|
+
return useGenerativeUIRuntime;
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
Object.defineProperty(exports, 'useRequiredGenerativeUIRuntime', {
|
|
217
|
+
enumerable: true,
|
|
218
|
+
get: function () {
|
|
219
|
+
return useRequiredGenerativeUIRuntime;
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
Object.defineProperty(exports, 'useShallowStableRef', {
|
|
223
|
+
enumerable: true,
|
|
224
|
+
get: function () {
|
|
225
|
+
return useShallowStableRef;
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
//# sourceMappingURL=accessibility-GnodqxkH.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accessibility-GnodqxkH.cjs","names":[],"sources":["../src/lib/shallow-stable-ref.ts","../src/generative-ui/runtime-context.ts","../src/generative-ui/catalog.ts","../src/generative-ui/accessibility.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport { ɵshallowEqualRecord } from \"@copilotkit/core\";\n\n// Reference-stability helpers, kept in their own leaf module (not in ./slots)\n// so that DOM-free consumers — e.g. CopilotChatConfigurationProvider, which is\n// re-exported from the lean `@copilotkit/react-core/headless` entry — reach\n// them without pulling in the slot rendering code (issue #4893).\n\n/**\n * Shallow equality comparison for objects: same own keys, each holding the\n * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n) {\n return ɵshallowEqualRecord(obj1, obj2);\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n","import { createContext, useContext } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { GenerativeUIUserEvent } from \"@copilotkit/shared\";\nimport type { GenerativeUIAccessibility } from \"./accessibility\";\nimport type { GenerativeUI } from \"./catalog\";\nimport type { GenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIErrorInfo,\n GenerativeUIInvokeResult,\n} from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUITheme } from \"@copilotkit/shared/generative-ui\";\n\nexport type { GenerativeUITheme };\n\nexport interface GenerativeUIErrorBoundaryConfig {\n /**\n * Replaces the host's fallback for a component that failed to render. It\n * is not used for invalid props, unknown types, cyclic references or a\n * failed surface: the host's `NodeFallback` shows those. If it throws,\n * the host's fallback stands in and the error is reported. `error` is\n * always an Error: a component that throws something else (a string,\n * `undefined`) gets an Error that describes it, with the value as its\n * `cause`.\n */\n fallback?: (props: {\n error: Error;\n retry: () => void;\n surfaceId: string;\n componentId: string;\n }) => ReactNode;\n /**\n * Called for render, props, operation, function and event failures. A\n * render or props failure that stays the same across new revisions of the\n * node or the surface is reported once, until the node or surface renders\n * again. A failed function or event is reported on every call.\n */\n onError?: (info: GenerativeUIErrorInfo) => void;\n}\n\ninterface GenerativeUIBaseConfig {\n /**\n * The result of `createGenerativeUI`: the components the model can render,\n * the app state they read and the functions they call.\n */\n ui: GenerativeUI;\n /**\n * The agents that get the generative UI. When omitted, every agent gets\n * it. Other agents get no envelope.\n */\n agentIds?: string[];\n /**\n * Web only. Values for the `--a2ui-*` CSS variables and the map style.\n * Top-level values apply in both modes. `dark` changes them in dark mode,\n * which is on under a `.dark` class, like the CopilotKit chat. React\n * Native ignores it.\n */\n theme?: GenerativeUITheme;\n /** Fallback UI and error reporting for generated UI. */\n errorBoundary?: GenerativeUIErrorBoundaryConfig;\n}\n\n/**\n * The tool transport: the model calls the `render_ui` tool, and the runtime\n * validates each operation before it streams it to the client.\n */\nexport interface GenerativeUIToolConfig extends GenerativeUIBaseConfig {\n /** Leave it out, or set \"tool\". */\n transport?: \"tool\";\n // Markdown-only options. `never` makes them a type error here, also when\n // `transport` is left out.\n sendContext?: never;\n includeCatalog?: never;\n}\n\n/**\n * The markdown transport: the model writes the operations in ```a2ui fences\n * in its reply. The client reads and validates them.\n */\nexport interface GenerativeUIMarkdownConfig extends GenerativeUIBaseConfig {\n transport: \"markdown\";\n /**\n * Send the component schema and the fence guideline as context entries.\n * Set `false` when the backend builds its own prompt from the envelope.\n * Default `true`.\n */\n sendContext?: boolean;\n /**\n * Send the component schemas in the envelope (`catalog.components`).\n * Default `true`.\n */\n includeCatalog?: boolean;\n}\n\n/**\n * Experimental. The `generativeUI` prop of `CopilotKitProvider`. Set\n * `transport: \"markdown\"` to get the markdown options.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider generativeUI={{ ui }} />\n * <CopilotKitProvider generativeUI={{ ui, transport: \"markdown\", sendContext: false }} />\n * ```\n */\nexport type GenerativeUIConfig =\n | GenerativeUIToolConfig\n | GenerativeUIMarkdownConfig;\n\nexport interface GenerativeUIRuntime {\n manager: GenerativeUISurfaceManager;\n dispatcher: GenerativeUIDispatcher;\n /** The generative UI given to the provider as `generativeUI={{ ui }}`. */\n ui: GenerativeUI;\n /** How the model sends operations. \"tool\" when the config leaves it out. */\n transport: \"tool\" | \"markdown\";\n /** The latest `generativeUI` config of the provider. */\n readonly config: GenerativeUIConfig;\n /**\n * The latest `theme`. The host's surface root gets it: on the web it sets\n * the CSS variables; the React Native root ignores it.\n */\n theme?: GenerativeUITheme;\n forwardEvent: (\n event: GenerativeUIUserEvent,\n agentId: string | undefined,\n ) => Promise<GenerativeUIInvokeResult>;\n reportError: (info: GenerativeUIErrorInfo) => void;\n readonly errorFallback?: GenerativeUIErrorBoundaryConfig[\"fallback\"];\n}\n\nexport const GenerativeUIRuntimeContext =\n createContext<GenerativeUIRuntime | null>(null);\n\nexport function useGenerativeUIRuntime(): GenerativeUIRuntime | null {\n return useContext(GenerativeUIRuntimeContext);\n}\n\nexport function useRequiredGenerativeUIRuntime(): GenerativeUIRuntime {\n const runtime = useContext(GenerativeUIRuntimeContext);\n if (!runtime) {\n throw new Error(\n \"Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.\",\n );\n }\n return runtime;\n}\n\nexport { reportErrorSafely } from \"@copilotkit/core/generative-ui\";\n\nexport interface GenerativeUINodeContextValue {\n surfaceKey: string;\n surfaceId: string;\n componentId: string;\n /** The resolved `accessibility` of the component envelope, if any. */\n accessibility?: GenerativeUIAccessibility;\n}\n\nexport const GenerativeUINodeContext =\n createContext<GenerativeUINodeContextValue | null>(null);\n","import type { ComponentType, ReactNode } from \"react\";\nimport { createGenerativeUI as createSharedGenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport type {\n AnyGenerativeUI,\n CreateGenerativeUIConfig as SharedCreateGenerativeUIConfig,\n GenerativeUI as SharedGenerativeUI,\n GenerativeUIBasesDefinitions,\n GenerativeUIComponentDefinition as SharedGenerativeUIComponentDefinition,\n GenerativeUIComponentProps as SharedGenerativeUIComponentProps,\n GenerativeUIDefinitions,\n GenerativeUIFunctionDefinition,\n GenerativeUIResultDefinitions,\n GenerativeUISchema,\n ResolvedGenerativeUIComponent as SharedResolvedGenerativeUIComponent,\n} from \"@copilotkit/shared/generative-ui\";\n\n// The catalog is framework-free and lives in `@copilotkit/shared/generative-ui`.\n// These types pin its component type to React components and its rendered\n// child type to `ReactNode`.\n\nexport {\n catalogIdsOf,\n componentCatalogIds,\n setterNameOf,\n} from \"@copilotkit/shared/generative-ui\";\nexport type {\n GenerativeUIComponentName,\n GenerativeUIDefinitionsOf,\n GenerativeUIEventDefinition,\n GenerativeUIEventInput,\n GenerativeUIFunctionArgs,\n GenerativeUIFunctionDefinition,\n GenerativeUIFunctionInput,\n GenerativeUIFunctionName,\n GenerativeUIFunctionsOf,\n GenerativeUISelector,\n GenerativeUISlotKind,\n GenerativeUIStateOf,\n PropsSchema,\n UnionToIntersection,\n} from \"@copilotkit/shared/generative-ui\";\n\n/** One component of a generative UI, as the renderer reads it. */\nexport type GenerativeUIComponentDefinition =\n SharedGenerativeUIComponentDefinition<ComponentType<any>>;\n\n/** A component after `createGenerativeUI` resolved its bindings. */\nexport type ResolvedGenerativeUIComponent = SharedResolvedGenerativeUIComponent<\n ComponentType<any>\n>;\n\n/**\n * Experimental. The result of `createGenerativeUI`: the components the model\n * can render, the app state they read, and the functions they call. Give it\n * to the provider (`generativeUI={{ ui }}`) and to the typed hooks.\n */\nexport type GenerativeUI<\n Definitions extends GenerativeUIDefinitions = GenerativeUIDefinitions,\n> = SharedGenerativeUI<Definitions, ComponentType<any>>;\n\n/**\n * Props that the renderer passes to a component:\n * `function CheckoutForm(props: GenerativeUIComponentProps<typeof ui, \"CheckoutForm\">)`.\n * Data props are the parsed `props` schema, bound props included. Event and\n * slot props are present only when they are bound or filled. Each writable\n * prop gets a setter (`value` gets `setValue`), which is always present.\n */\nexport type GenerativeUIComponentProps<\n UI extends AnyGenerativeUI,\n Name extends keyof NonNullable<UI[\"definitions\"]>[\"components\"] & string,\n> = SharedGenerativeUIComponentProps<UI, Name, ReactNode>;\n\n/** One new React component for each component of the bases that it names. */\ntype OverridesConfig<Bases extends readonly AnyGenerativeUI[]> = {\n [Name in keyof GenerativeUIBasesDefinitions<Bases>[\"components\"] & string]?: {\n component: ComponentType<\n GenerativeUIBasesDefinitions<Bases> extends infer Definitions extends\n GenerativeUIDefinitions\n ? GenerativeUIComponentProps<GenerativeUI<Definitions>, Name>\n : never\n >;\n };\n};\n\n/** The config of `createGenerativeUI`. */\nexport type CreateGenerativeUIConfig<\n Bases extends readonly AnyGenerativeUI[],\n State extends Record<string, GenerativeUISchema>,\n Functions extends Record<string, GenerativeUIFunctionDefinition>,\n Props extends Record<string, unknown>,\n Events extends Record<string, unknown>,\n Slots extends Record<string, unknown>,\n Writable extends Record<string, unknown>,\n> = SharedCreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable,\n OverridesConfig<Bases>\n>;\n\n/**\n * Experimental. Declares the components the model can render, the app state\n * they read, and the functions they call.\n *\n * - A prop with the name of a top-level state key is bound to that state.\n * - `bind: { prop: (state, props) => value }` binds a prop to a selector.\n * - An event binds to the function with its name, else to the name without\n * `on` (`onAddToCart` calls `addToCart`).\n * - `writable: [\"value\"]` gives the component a `setValue` prop. See\n * `GenerativeUIComponentDefinition.writable`.\n *\n * The model does not see bound props or matched events.\n *\n * @param config - `id`, then optional `extends`, `state`, `functions` and\n * `overrides`, then `components`. Put `state` before `components`, so the selectors\n * get typed state.\n * @throws Error when a name comes from two places, an override names no\n * component of the bases, `props` is not an object\n * schema with a JSON Schema, a key is reserved or used\n * twice on a component, an event matches two functions, an unmatched event\n * has no `parameters`, a `bind` key is not a prop, a `writable` key is not\n * a prop or is a bound prop, or a setter name is already a key of the\n * component. Also throws when `parameterOrder` contains duplicate or unknown\n * keys, or an ordered component declares integer-index keys whose JSON object\n * enumeration order cannot be controlled.\n *\n * @example\n * ```ts\n * const ui = createGenerativeUI({\n * id: \"acme/store@1\",\n * state: { cart: cartSchema },\n * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },\n * components: {\n * CartSummary: {\n * component: CartSummary,\n * props: z.object({ count: z.number() }),\n * bind: { count: (state) => state.cart.count },\n * },\n * },\n * });\n * ```\n */\nexport function createGenerativeUI<\n Bases extends readonly AnyGenerativeUI[] = [],\n State extends Record<string, GenerativeUISchema> = {},\n Functions extends Record<string, GenerativeUIFunctionDefinition> = {},\n Props extends Record<string, unknown> = {},\n Events extends Record<string, unknown> = {},\n Slots extends Record<string, unknown> = {},\n Writable extends Record<string, unknown> = {},\n>(\n config: CreateGenerativeUIConfig<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >,\n) {\n // The React config only narrows the shared one (React component types),\n // so the shared runtime builds the same UI.\n const build = createSharedGenerativeUI as (config: unknown) => unknown;\n return build(config) as GenerativeUI<\n GenerativeUIResultDefinitions<\n Bases,\n State,\n Functions,\n Props,\n Events,\n Slots,\n Writable\n >\n >;\n}\n","import { useContext, useMemo } from \"react\";\nimport { accessibilityAttributes } from \"@copilotkit/core/generative-ui\";\nimport type { GenerativeUIAriaAttributes } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUINodeContext } from \"./runtime-context\";\n\n// The accessibility helpers are framework-free and live in\n// `@copilotkit/core/generative-ui`. The standard components import them\n// from here.\nexport {\n accessibilityAttributes,\n controlAria,\n namedRole,\n readAccessibility,\n wrapperAria,\n} from \"@copilotkit/core/generative-ui\";\nexport type {\n GenerativeUIAccessibility,\n GenerativeUIAriaAttributes,\n} from \"@copilotkit/core/generative-ui\";\n\n/**\n * Experimental. The ARIA attributes of the `accessibility` that the model\n * gave the component being rendered, to spread on its root element. The\n * standard components do this; a custom component does it itself:\n *\n * @example\n * ```tsx\n * function Panel({ children }: { children?: ReactNode }) {\n * const aria = useGenerativeUIAccessibility();\n * return <section {...aria}>{children}</section>;\n * }\n * ```\n *\n * Outside of generated UI it gives `{}`.\n */\nexport function useGenerativeUIAccessibility(): GenerativeUIAriaAttributes {\n const node = useContext(GenerativeUINodeContext);\n const accessibility = node?.accessibility;\n return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,SAAgB,aACd,MACA,MACA;AACA,kDAA2B,MAAM,KAAK;;;;;;AAOxC,SAAS,cAAc,KAA8C;AACnE,QACE,QAAQ,QACR,OAAO,QAAQ,YACf,OAAO,UAAU,SAAS,KAAK,IAAI,KAAK;;;;;;;;;;;;;;;AAiB5C,SAAgB,oBAAuB,OAAa;CAClD,MAAM,wBAAa,MAAM;AAGzB,KAAI,IAAI,YAAY,MAAO,QAAO,IAAI;AAGtC,KAAI,cAAc,IAAI,QAAQ,IAAI,cAAc,MAAM,EACpD;MAAI,aAAa,IAAI,SAAS,MAAM,CAAE,QAAO,IAAI;;AAInD,KAAI,UAAU;AACd,QAAO,IAAI;;;;;ACyEb,MAAa,sDAC+B,KAAK;AAEjD,SAAgB,yBAAqD;AACnE,8BAAkB,2BAA2B;;AAG/C,SAAgB,iCAAsD;CACpE,MAAM,gCAAqB,2BAA2B;AACtD,KAAI,CAAC,QACH,OAAM,IAAI,MACR,2NACD;AAEH,QAAO;;AAaT,MAAa,mDACwC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACZ1D,SAAgB,mBASd,QASA;AAIA,iEAAa,OAAO;;;;;;;;;;;;;;;;;;;;ACrItB,SAAgB,+BAA2D;CAEzE,MAAM,sCADkB,wBAAwB,EACpB;AAC5B,6FAA6C,cAAc,EAAE,CAAC,cAAc,CAAC"}
|