@langchain/react 0.1.0 → 0.1.2
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/LICENSE +21 -0
- package/dist/_virtual/_rolldown/runtime.cjs +7 -13
- package/dist/index.cjs +30 -31
- package/dist/index.js +1 -2
- package/dist/react-ui/client.cjs +4 -6
- package/dist/react-ui/client.cjs.map +1 -1
- package/dist/react-ui/client.js +1 -3
- package/dist/react-ui/client.js.map +1 -1
- package/dist/react-ui/index.cjs +4 -5
- package/dist/react-ui/index.cjs.map +1 -1
- package/dist/react-ui/index.js +1 -2
- package/dist/react-ui/index.js.map +1 -1
- package/dist/react-ui/server/index.cjs +4 -5
- package/dist/react-ui/server/index.js +1 -2
- package/dist/react-ui/server/server.cjs +2 -3
- package/dist/react-ui/server/server.cjs.map +1 -1
- package/dist/react-ui/server/server.js +1 -2
- package/dist/react-ui/server/server.js.map +1 -1
- package/dist/react-ui/types.cjs +1 -2
- package/dist/react-ui/types.cjs.map +1 -1
- package/dist/react-ui/types.js +1 -1
- package/dist/stream.cjs +4 -5
- package/dist/stream.cjs.map +1 -1
- package/dist/stream.custom.cjs +3 -5
- package/dist/stream.custom.cjs.map +1 -1
- package/dist/stream.custom.js +1 -3
- package/dist/stream.custom.js.map +1 -1
- package/dist/stream.js +1 -2
- package/dist/stream.js.map +1 -1
- package/dist/stream.lgp.cjs +3 -5
- package/dist/stream.lgp.cjs.map +1 -1
- package/dist/stream.lgp.js +1 -3
- package/dist/stream.lgp.js.map +1 -1
- package/dist/thread.cjs +2 -4
- package/dist/thread.cjs.map +1 -1
- package/dist/thread.js +1 -3
- package/dist/thread.js.map +1 -1
- package/package.json +40 -35
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 LangChain
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -6,16 +6,12 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
8
|
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
}
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
19
15
|
}
|
|
20
16
|
return to;
|
|
21
17
|
};
|
|
@@ -23,7 +19,5 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
23
19
|
value: mod,
|
|
24
20
|
enumerable: true
|
|
25
21
|
}) : target, mod));
|
|
26
|
-
|
|
27
22
|
//#endregion
|
|
28
|
-
|
|
29
|
-
exports.__toESM = __toESM;
|
|
23
|
+
exports.__toESM = __toESM;
|
package/dist/index.cjs
CHANGED
|
@@ -1,38 +1,37 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value:
|
|
2
|
-
|
|
3
|
-
require(
|
|
4
|
-
const require_stream = require(
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("./_virtual/_rolldown/runtime.cjs");
|
|
3
|
+
require("./stream.custom.cjs");
|
|
4
|
+
const require_stream = require("./stream.cjs");
|
|
5
5
|
let _langchain_langgraph_sdk_ui = require("@langchain/langgraph-sdk/ui");
|
|
6
|
-
|
|
7
6
|
exports.FetchStreamTransport = _langchain_langgraph_sdk_ui.FetchStreamTransport;
|
|
8
|
-
Object.defineProperty(exports,
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
Object.defineProperty(exports, "SubagentManager", {
|
|
8
|
+
enumerable: true,
|
|
9
|
+
get: function() {
|
|
10
|
+
return _langchain_langgraph_sdk_ui.SubagentManager;
|
|
11
|
+
}
|
|
13
12
|
});
|
|
14
|
-
Object.defineProperty(exports,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
Object.defineProperty(exports, "calculateDepthFromNamespace", {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function() {
|
|
16
|
+
return _langchain_langgraph_sdk_ui.calculateDepthFromNamespace;
|
|
17
|
+
}
|
|
19
18
|
});
|
|
20
|
-
Object.defineProperty(exports,
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
19
|
+
Object.defineProperty(exports, "extractParentIdFromNamespace", {
|
|
20
|
+
enumerable: true,
|
|
21
|
+
get: function() {
|
|
22
|
+
return _langchain_langgraph_sdk_ui.extractParentIdFromNamespace;
|
|
23
|
+
}
|
|
25
24
|
});
|
|
26
|
-
Object.defineProperty(exports,
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
Object.defineProperty(exports, "extractToolCallIdFromNamespace", {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
get: function() {
|
|
28
|
+
return _langchain_langgraph_sdk_ui.extractToolCallIdFromNamespace;
|
|
29
|
+
}
|
|
31
30
|
});
|
|
32
|
-
Object.defineProperty(exports,
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
31
|
+
Object.defineProperty(exports, "isSubagentNamespace", {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
get: function() {
|
|
34
|
+
return _langchain_langgraph_sdk_ui.isSubagentNamespace;
|
|
35
|
+
}
|
|
37
36
|
});
|
|
38
|
-
exports.useStream = require_stream.useStream;
|
|
37
|
+
exports.useStream = require_stream.useStream;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { FetchStreamTransport } from "./stream.custom.js";
|
|
2
2
|
import { useStream } from "./stream.js";
|
|
3
3
|
import { SubagentManager, calculateDepthFromNamespace, extractParentIdFromNamespace, extractToolCallIdFromNamespace, isSubagentNamespace } from "@langchain/langgraph-sdk/ui";
|
|
4
|
-
|
|
5
|
-
export { FetchStreamTransport, SubagentManager, calculateDepthFromNamespace, extractParentIdFromNamespace, extractToolCallIdFromNamespace, isSubagentNamespace, useStream };
|
|
4
|
+
export { FetchStreamTransport, SubagentManager, calculateDepthFromNamespace, extractParentIdFromNamespace, extractToolCallIdFromNamespace, isSubagentNamespace, useStream };
|
package/dist/react-ui/client.cjs
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
require('../index.cjs');
|
|
2
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
3
|
+
const require_stream = require("../stream.cjs");
|
|
4
|
+
require("../index.cjs");
|
|
6
5
|
let react = require("react");
|
|
7
6
|
react = require_runtime.__toESM(react);
|
|
8
7
|
let react_dom = require("react-dom");
|
|
9
8
|
react_dom = require_runtime.__toESM(react_dom);
|
|
10
9
|
let react_jsx_runtime = require("react/jsx-runtime");
|
|
11
10
|
react_jsx_runtime = require_runtime.__toESM(react_jsx_runtime);
|
|
12
|
-
|
|
13
11
|
//#region src/react-ui/client.tsx
|
|
14
12
|
const UseStreamContext = react.createContext(null);
|
|
15
13
|
function useStreamContext() {
|
|
@@ -129,10 +127,10 @@ function bootstrapUiContext() {
|
|
|
129
127
|
throw new Error(`Unknown module...: ${name}`);
|
|
130
128
|
};
|
|
131
129
|
}
|
|
132
|
-
|
|
133
130
|
//#endregion
|
|
134
131
|
exports.LoadExternalComponent = LoadExternalComponent;
|
|
135
132
|
exports.bootstrapUiContext = bootstrapUiContext;
|
|
136
133
|
exports.experimental_loadShare = experimental_loadShare;
|
|
137
134
|
exports.useStreamContext = useStreamContext;
|
|
135
|
+
|
|
138
136
|
//# sourceMappingURL=client.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["React","ReactDOM","JsxRuntime"],"sources":["../../src/react-ui/client.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport * as JsxRuntime from \"react/jsx-runtime\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { useStream } from \"../index.js\";\nimport type { UIMessage } from \"./types.js\";\nimport type { UseStream } from \"../types.js\";\n\nconst UseStreamContext = React.createContext<{\n stream: ReturnType<typeof useStream>;\n meta: unknown;\n}>(null!);\n\ntype GetMetaType<Bag extends BagTemplate> = Bag extends { MetaType: unknown }\n ? Bag[\"MetaType\"]\n : unknown;\n\ninterface UseStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> extends UseStream<StateType, Bag> {\n meta?: GetMetaType<Bag>;\n}\n\nexport function useStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(): UseStreamContext<StateType, Bag> {\n const ctx = React.useContext(UseStreamContext);\n if (!ctx) {\n throw new Error(\n \"useStreamContext must be used within a LoadExternalComponent\",\n );\n }\n\n return new Proxy(ctx, {\n get(target, prop: keyof UseStreamContext<StateType, Bag>) {\n if (prop === \"meta\") return target.meta;\n return target.stream[prop as keyof typeof target.stream];\n },\n }) as unknown as UseStreamContext<StateType, Bag>;\n}\n\ninterface ComponentTarget {\n comp: React.FunctionComponent | React.ComponentClass;\n target: HTMLElement;\n}\n\nclass ComponentStore {\n private cache: Record<string, ComponentTarget> = {};\n\n private boundCache: Record<\n string,\n {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => ComponentTarget | undefined;\n }\n > = {};\n\n private callbacks: Record<\n string,\n ((\n comp: React.FunctionComponent | React.ComponentClass,\n el: HTMLElement,\n ) => void)[]\n > = {};\n\n respond(\n shadowRootId: string,\n comp: React.FunctionComponent | React.ComponentClass,\n targetElement: HTMLElement,\n ) {\n this.cache[shadowRootId] = { comp, target: targetElement };\n this.callbacks[shadowRootId]?.forEach((c) => c(comp, targetElement));\n }\n\n getBoundStore(shadowRootId: string) {\n this.boundCache[shadowRootId] ??= {\n subscribe: (onStoreChange: () => void) => {\n this.callbacks[shadowRootId] ??= [];\n this.callbacks[shadowRootId].push(onStoreChange);\n return () => {\n this.callbacks[shadowRootId] = this.callbacks[shadowRootId].filter(\n (c) => c !== onStoreChange,\n );\n };\n },\n getSnapshot: () => this.cache[shadowRootId],\n };\n\n return this.boundCache[shadowRootId];\n }\n}\n\nconst COMPONENT_STORE = new ComponentStore();\nconst EXT_STORE_SYMBOL = Symbol.for(\"LGUI_EXT_STORE\");\nconst REQUIRE_SYMBOL = Symbol.for(\"LGUI_REQUIRE\");\nconst REQUIRE_EXTRA_SYMBOL = Symbol.for(\"LGUI_REQUIRE_EXTRA\");\n\ninterface LoadExternalComponentProps extends Pick<\n React.HTMLAttributes<HTMLDivElement>,\n \"style\" | \"className\"\n> {\n /** Stream of the assistant */\n stream: ReturnType<typeof useStream>;\n\n /** Namespace of UI components. Defaults to assistant ID. */\n namespace?: string;\n\n /** UI message to be rendered */\n message: UIMessage;\n\n /** Additional context to be passed to the child component */\n meta?: unknown;\n\n /** Fallback to be rendered when the component is loading */\n fallback?: React.ReactNode | Record<string, React.ReactNode>;\n\n /**\n * Map of components that can be rendered directly without fetching the UI code\n * from the server.\n */\n components?: Record<string, React.FunctionComponent | React.ComponentClass>;\n}\n\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n value != null && typeof value === \"object\" && Symbol.iterator in value;\n\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n value != null &&\n typeof value === \"object\" &&\n \"then\" in value &&\n typeof value.then === \"function\";\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n if (React.isValidElement(value)) return true;\n if (value == null) return true;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (isIterable(value)) return true;\n if (isPromise(value)) return true;\n\n return false;\n};\n\nexport function LoadExternalComponent({\n stream,\n namespace,\n message,\n meta,\n fallback,\n components,\n ...props\n}: LoadExternalComponentProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const id = React.useId();\n const shadowRootId = `child-shadow-${id}`;\n\n const store = React.useMemo(\n () => COMPONENT_STORE.getBoundStore(shadowRootId),\n [shadowRootId],\n );\n const state = React.useSyncExternalStore(store.subscribe, store.getSnapshot);\n\n const clientComponent = components?.[message.name];\n const hasClientComponent = clientComponent != null;\n\n let fallbackComponent = null;\n if (isReactNode(fallback)) {\n fallbackComponent = fallback;\n } else if (typeof fallback === \"object\" && fallback != null) {\n fallbackComponent = fallback?.[message.name];\n }\n\n const uiNamespace = namespace ?? stream.assistantId;\n const uiClient = stream.client[\"~ui\"];\n React.useEffect(() => {\n if (hasClientComponent) return;\n void uiClient.getComponent(uiNamespace, message.name).then((html) => {\n const dom = ref.current;\n if (!dom) return;\n const root = dom.shadowRoot ?? dom.attachShadow({ mode: \"open\" });\n const fragment = document\n .createRange()\n .createContextualFragment(\n html.replace(\"{{shadowRootId}}\", shadowRootId),\n );\n root.appendChild(fragment);\n });\n }, [uiClient, uiNamespace, message.name, shadowRootId, hasClientComponent]);\n\n if (hasClientComponent) {\n return (\n <UseStreamContext.Provider value={{ stream, meta }}>\n {React.createElement(clientComponent, message.props)}\n </UseStreamContext.Provider>\n );\n }\n\n return (\n <>\n <div id={shadowRootId} ref={ref} {...props} />\n\n <UseStreamContext.Provider value={{ stream, meta }}>\n {state?.target != null\n ? ReactDOM.createPortal(\n React.createElement(state.comp, message.props),\n state.target,\n )\n : fallbackComponent}\n </UseStreamContext.Provider>\n </>\n );\n}\n\ndeclare global {\n interface Window {\n [EXT_STORE_SYMBOL]: ComponentStore;\n [REQUIRE_SYMBOL]: (name: string) => unknown;\n [REQUIRE_EXTRA_SYMBOL]: Record<string, unknown>;\n }\n}\n\nexport function experimental_loadShare(name: string, module: unknown) {\n if (typeof window === \"undefined\") return;\n\n window[REQUIRE_EXTRA_SYMBOL] ??= {};\n window[REQUIRE_EXTRA_SYMBOL][name] = module;\n}\n\nexport function bootstrapUiContext() {\n if (typeof window === \"undefined\") {\n return;\n }\n\n window[EXT_STORE_SYMBOL] = COMPONENT_STORE;\n window[REQUIRE_SYMBOL] = (name: string) => {\n if (name === \"react\") return React;\n if (name === \"react-dom\") return ReactDOM;\n if (name === \"react/jsx-runtime\") return JsxRuntime;\n if (name === \"@langchain/langgraph-sdk/react\") return { useStream };\n if (name === \"@langchain/langgraph-sdk/react-ui\") {\n return {\n useStreamContext,\n LoadExternalComponent: () => {\n throw new Error(\"Nesting LoadExternalComponent is not supported\");\n },\n };\n }\n\n if (\n window[REQUIRE_EXTRA_SYMBOL] != null &&\n typeof window[REQUIRE_EXTRA_SYMBOL] === \"object\" &&\n name in window[REQUIRE_EXTRA_SYMBOL]\n ) {\n return window[REQUIRE_EXTRA_SYMBOL][name];\n }\n\n throw new Error(`Unknown module...: ${name}`);\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAM,mBAAmBA,MAAM,cAG5B,KAAM;AAaT,SAAgB,mBAGsB;CACpC,MAAM,MAAMA,MAAM,WAAW,iBAAiB;AAC9C,KAAI,CAAC,IACH,OAAM,IAAI,MACR,+DACD;AAGH,QAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAA8C;AACxD,MAAI,SAAS,OAAQ,QAAO,OAAO;AACnC,SAAO,OAAO,OAAO;IAExB,CAAC;;AAQJ,IAAM,iBAAN,MAAqB;CACnB,AAAQ,QAAyC,EAAE;CAEnD,AAAQ,aAMJ,EAAE;CAEN,AAAQ,YAMJ,EAAE;CAEN,QACE,cACA,MACA,eACA;AACA,OAAK,MAAM,gBAAgB;GAAE;GAAM,QAAQ;GAAe;AAC1D,OAAK,UAAU,eAAe,SAAS,MAAM,EAAE,MAAM,cAAc,CAAC;;CAGtE,cAAc,cAAsB;AAClC,OAAK,WAAW,kBAAkB;GAChC,YAAY,kBAA8B;AACxC,SAAK,UAAU,kBAAkB,EAAE;AACnC,SAAK,UAAU,cAAc,KAAK,cAAc;AAChD,iBAAa;AACX,UAAK,UAAU,gBAAgB,KAAK,UAAU,cAAc,QACzD,MAAM,MAAM,cACd;;;GAGL,mBAAmB,KAAK,MAAM;GAC/B;AAED,SAAO,KAAK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,"file":"client.cjs","names":["React","ReactDOM","JsxRuntime"],"sources":["../../src/react-ui/client.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport * as JsxRuntime from \"react/jsx-runtime\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { useStream } from \"../index.js\";\nimport type { UIMessage } from \"./types.js\";\nimport type { UseStream } from \"../types.js\";\n\nconst UseStreamContext = React.createContext<{\n stream: ReturnType<typeof useStream>;\n meta: unknown;\n}>(null!);\n\ntype GetMetaType<Bag extends BagTemplate> = Bag extends { MetaType: unknown }\n ? Bag[\"MetaType\"]\n : unknown;\n\ninterface UseStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> extends UseStream<StateType, Bag> {\n meta?: GetMetaType<Bag>;\n}\n\nexport function useStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(): UseStreamContext<StateType, Bag> {\n const ctx = React.useContext(UseStreamContext);\n if (!ctx) {\n throw new Error(\n \"useStreamContext must be used within a LoadExternalComponent\",\n );\n }\n\n return new Proxy(ctx, {\n get(target, prop: keyof UseStreamContext<StateType, Bag>) {\n if (prop === \"meta\") return target.meta;\n return target.stream[prop as keyof typeof target.stream];\n },\n }) as unknown as UseStreamContext<StateType, Bag>;\n}\n\ninterface ComponentTarget {\n comp: React.FunctionComponent | React.ComponentClass;\n target: HTMLElement;\n}\n\nclass ComponentStore {\n private cache: Record<string, ComponentTarget> = {};\n\n private boundCache: Record<\n string,\n {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => ComponentTarget | undefined;\n }\n > = {};\n\n private callbacks: Record<\n string,\n ((\n comp: React.FunctionComponent | React.ComponentClass,\n el: HTMLElement,\n ) => void)[]\n > = {};\n\n respond(\n shadowRootId: string,\n comp: React.FunctionComponent | React.ComponentClass,\n targetElement: HTMLElement,\n ) {\n this.cache[shadowRootId] = { comp, target: targetElement };\n this.callbacks[shadowRootId]?.forEach((c) => c(comp, targetElement));\n }\n\n getBoundStore(shadowRootId: string) {\n this.boundCache[shadowRootId] ??= {\n subscribe: (onStoreChange: () => void) => {\n this.callbacks[shadowRootId] ??= [];\n this.callbacks[shadowRootId].push(onStoreChange);\n return () => {\n this.callbacks[shadowRootId] = this.callbacks[shadowRootId].filter(\n (c) => c !== onStoreChange,\n );\n };\n },\n getSnapshot: () => this.cache[shadowRootId],\n };\n\n return this.boundCache[shadowRootId];\n }\n}\n\nconst COMPONENT_STORE = new ComponentStore();\nconst EXT_STORE_SYMBOL = Symbol.for(\"LGUI_EXT_STORE\");\nconst REQUIRE_SYMBOL = Symbol.for(\"LGUI_REQUIRE\");\nconst REQUIRE_EXTRA_SYMBOL = Symbol.for(\"LGUI_REQUIRE_EXTRA\");\n\ninterface LoadExternalComponentProps extends Pick<\n React.HTMLAttributes<HTMLDivElement>,\n \"style\" | \"className\"\n> {\n /** Stream of the assistant */\n stream: ReturnType<typeof useStream>;\n\n /** Namespace of UI components. Defaults to assistant ID. */\n namespace?: string;\n\n /** UI message to be rendered */\n message: UIMessage;\n\n /** Additional context to be passed to the child component */\n meta?: unknown;\n\n /** Fallback to be rendered when the component is loading */\n fallback?: React.ReactNode | Record<string, React.ReactNode>;\n\n /**\n * Map of components that can be rendered directly without fetching the UI code\n * from the server.\n */\n components?: Record<string, React.FunctionComponent | React.ComponentClass>;\n}\n\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n value != null && typeof value === \"object\" && Symbol.iterator in value;\n\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n value != null &&\n typeof value === \"object\" &&\n \"then\" in value &&\n typeof value.then === \"function\";\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n if (React.isValidElement(value)) return true;\n if (value == null) return true;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (isIterable(value)) return true;\n if (isPromise(value)) return true;\n\n return false;\n};\n\nexport function LoadExternalComponent({\n stream,\n namespace,\n message,\n meta,\n fallback,\n components,\n ...props\n}: LoadExternalComponentProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const id = React.useId();\n const shadowRootId = `child-shadow-${id}`;\n\n const store = React.useMemo(\n () => COMPONENT_STORE.getBoundStore(shadowRootId),\n [shadowRootId],\n );\n const state = React.useSyncExternalStore(store.subscribe, store.getSnapshot);\n\n const clientComponent = components?.[message.name];\n const hasClientComponent = clientComponent != null;\n\n let fallbackComponent = null;\n if (isReactNode(fallback)) {\n fallbackComponent = fallback;\n } else if (typeof fallback === \"object\" && fallback != null) {\n fallbackComponent = fallback?.[message.name];\n }\n\n const uiNamespace = namespace ?? stream.assistantId;\n const uiClient = stream.client[\"~ui\"];\n React.useEffect(() => {\n if (hasClientComponent) return;\n void uiClient.getComponent(uiNamespace, message.name).then((html) => {\n const dom = ref.current;\n if (!dom) return;\n const root = dom.shadowRoot ?? dom.attachShadow({ mode: \"open\" });\n const fragment = document\n .createRange()\n .createContextualFragment(\n html.replace(\"{{shadowRootId}}\", shadowRootId),\n );\n root.appendChild(fragment);\n });\n }, [uiClient, uiNamespace, message.name, shadowRootId, hasClientComponent]);\n\n if (hasClientComponent) {\n return (\n <UseStreamContext.Provider value={{ stream, meta }}>\n {React.createElement(clientComponent, message.props)}\n </UseStreamContext.Provider>\n );\n }\n\n return (\n <>\n <div id={shadowRootId} ref={ref} {...props} />\n\n <UseStreamContext.Provider value={{ stream, meta }}>\n {state?.target != null\n ? ReactDOM.createPortal(\n React.createElement(state.comp, message.props),\n state.target,\n )\n : fallbackComponent}\n </UseStreamContext.Provider>\n </>\n );\n}\n\ndeclare global {\n interface Window {\n [EXT_STORE_SYMBOL]: ComponentStore;\n [REQUIRE_SYMBOL]: (name: string) => unknown;\n [REQUIRE_EXTRA_SYMBOL]: Record<string, unknown>;\n }\n}\n\nexport function experimental_loadShare(name: string, module: unknown) {\n if (typeof window === \"undefined\") return;\n\n window[REQUIRE_EXTRA_SYMBOL] ??= {};\n window[REQUIRE_EXTRA_SYMBOL][name] = module;\n}\n\nexport function bootstrapUiContext() {\n if (typeof window === \"undefined\") {\n return;\n }\n\n window[EXT_STORE_SYMBOL] = COMPONENT_STORE;\n window[REQUIRE_SYMBOL] = (name: string) => {\n if (name === \"react\") return React;\n if (name === \"react-dom\") return ReactDOM;\n if (name === \"react/jsx-runtime\") return JsxRuntime;\n if (name === \"@langchain/langgraph-sdk/react\") return { useStream };\n if (name === \"@langchain/langgraph-sdk/react-ui\") {\n return {\n useStreamContext,\n LoadExternalComponent: () => {\n throw new Error(\"Nesting LoadExternalComponent is not supported\");\n },\n };\n }\n\n if (\n window[REQUIRE_EXTRA_SYMBOL] != null &&\n typeof window[REQUIRE_EXTRA_SYMBOL] === \"object\" &&\n name in window[REQUIRE_EXTRA_SYMBOL]\n ) {\n return window[REQUIRE_EXTRA_SYMBOL][name];\n }\n\n throw new Error(`Unknown module...: ${name}`);\n };\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAM,mBAAmBA,MAAM,cAG5B,KAAM;AAaT,SAAgB,mBAGsB;CACpC,MAAM,MAAMA,MAAM,WAAW,iBAAiB;AAC9C,KAAI,CAAC,IACH,OAAM,IAAI,MACR,+DACD;AAGH,QAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAA8C;AACxD,MAAI,SAAS,OAAQ,QAAO,OAAO;AACnC,SAAO,OAAO,OAAO;IAExB,CAAC;;AAQJ,IAAM,iBAAN,MAAqB;CACnB,QAAiD,EAAE;CAEnD,aAMI,EAAE;CAEN,YAMI,EAAE;CAEN,QACE,cACA,MACA,eACA;AACA,OAAK,MAAM,gBAAgB;GAAE;GAAM,QAAQ;GAAe;AAC1D,OAAK,UAAU,eAAe,SAAS,MAAM,EAAE,MAAM,cAAc,CAAC;;CAGtE,cAAc,cAAsB;AAClC,OAAK,WAAW,kBAAkB;GAChC,YAAY,kBAA8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7B,MAAI,SAAS,YAAa,QAAOC;AACjC,MAAI,SAAS,oBAAqB,QAAOC;AACzC,MAAI,SAAS,iCAAkC,QAAO,EAAE,WAAA,eAAA,WAAW;AACnE,MAAI,SAAS,oCACX,QAAO;GACL;GACA,6BAA6B;AAC3B,UAAM,IAAI,MAAM,iDAAiD;;GAEpE;AAGH,MACE,OAAO,yBAAyB,QAChC,OAAO,OAAO,0BAA0B,YACxC,QAAQ,OAAO,sBAEf,QAAO,OAAO,sBAAsB;AAGtC,QAAM,IAAI,MAAM,sBAAsB,OAAO"}
|
package/dist/react-ui/client.js
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
3
2
|
import { useStream } from "../stream.js";
|
|
4
3
|
import "../index.js";
|
|
5
4
|
import * as React from "react";
|
|
6
5
|
import * as ReactDOM from "react-dom";
|
|
7
6
|
import * as JsxRuntime from "react/jsx-runtime";
|
|
8
7
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
9
|
-
|
|
10
8
|
//#region src/react-ui/client.tsx
|
|
11
9
|
const UseStreamContext = React.createContext(null);
|
|
12
10
|
function useStreamContext() {
|
|
@@ -126,7 +124,7 @@ function bootstrapUiContext() {
|
|
|
126
124
|
throw new Error(`Unknown module...: ${name}`);
|
|
127
125
|
};
|
|
128
126
|
}
|
|
129
|
-
|
|
130
127
|
//#endregion
|
|
131
128
|
export { LoadExternalComponent, bootstrapUiContext, experimental_loadShare, useStreamContext };
|
|
129
|
+
|
|
132
130
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/react-ui/client.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport * as JsxRuntime from \"react/jsx-runtime\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { useStream } from \"../index.js\";\nimport type { UIMessage } from \"./types.js\";\nimport type { UseStream } from \"../types.js\";\n\nconst UseStreamContext = React.createContext<{\n stream: ReturnType<typeof useStream>;\n meta: unknown;\n}>(null!);\n\ntype GetMetaType<Bag extends BagTemplate> = Bag extends { MetaType: unknown }\n ? Bag[\"MetaType\"]\n : unknown;\n\ninterface UseStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> extends UseStream<StateType, Bag> {\n meta?: GetMetaType<Bag>;\n}\n\nexport function useStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(): UseStreamContext<StateType, Bag> {\n const ctx = React.useContext(UseStreamContext);\n if (!ctx) {\n throw new Error(\n \"useStreamContext must be used within a LoadExternalComponent\",\n );\n }\n\n return new Proxy(ctx, {\n get(target, prop: keyof UseStreamContext<StateType, Bag>) {\n if (prop === \"meta\") return target.meta;\n return target.stream[prop as keyof typeof target.stream];\n },\n }) as unknown as UseStreamContext<StateType, Bag>;\n}\n\ninterface ComponentTarget {\n comp: React.FunctionComponent | React.ComponentClass;\n target: HTMLElement;\n}\n\nclass ComponentStore {\n private cache: Record<string, ComponentTarget> = {};\n\n private boundCache: Record<\n string,\n {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => ComponentTarget | undefined;\n }\n > = {};\n\n private callbacks: Record<\n string,\n ((\n comp: React.FunctionComponent | React.ComponentClass,\n el: HTMLElement,\n ) => void)[]\n > = {};\n\n respond(\n shadowRootId: string,\n comp: React.FunctionComponent | React.ComponentClass,\n targetElement: HTMLElement,\n ) {\n this.cache[shadowRootId] = { comp, target: targetElement };\n this.callbacks[shadowRootId]?.forEach((c) => c(comp, targetElement));\n }\n\n getBoundStore(shadowRootId: string) {\n this.boundCache[shadowRootId] ??= {\n subscribe: (onStoreChange: () => void) => {\n this.callbacks[shadowRootId] ??= [];\n this.callbacks[shadowRootId].push(onStoreChange);\n return () => {\n this.callbacks[shadowRootId] = this.callbacks[shadowRootId].filter(\n (c) => c !== onStoreChange,\n );\n };\n },\n getSnapshot: () => this.cache[shadowRootId],\n };\n\n return this.boundCache[shadowRootId];\n }\n}\n\nconst COMPONENT_STORE = new ComponentStore();\nconst EXT_STORE_SYMBOL = Symbol.for(\"LGUI_EXT_STORE\");\nconst REQUIRE_SYMBOL = Symbol.for(\"LGUI_REQUIRE\");\nconst REQUIRE_EXTRA_SYMBOL = Symbol.for(\"LGUI_REQUIRE_EXTRA\");\n\ninterface LoadExternalComponentProps extends Pick<\n React.HTMLAttributes<HTMLDivElement>,\n \"style\" | \"className\"\n> {\n /** Stream of the assistant */\n stream: ReturnType<typeof useStream>;\n\n /** Namespace of UI components. Defaults to assistant ID. */\n namespace?: string;\n\n /** UI message to be rendered */\n message: UIMessage;\n\n /** Additional context to be passed to the child component */\n meta?: unknown;\n\n /** Fallback to be rendered when the component is loading */\n fallback?: React.ReactNode | Record<string, React.ReactNode>;\n\n /**\n * Map of components that can be rendered directly without fetching the UI code\n * from the server.\n */\n components?: Record<string, React.FunctionComponent | React.ComponentClass>;\n}\n\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n value != null && typeof value === \"object\" && Symbol.iterator in value;\n\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n value != null &&\n typeof value === \"object\" &&\n \"then\" in value &&\n typeof value.then === \"function\";\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n if (React.isValidElement(value)) return true;\n if (value == null) return true;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (isIterable(value)) return true;\n if (isPromise(value)) return true;\n\n return false;\n};\n\nexport function LoadExternalComponent({\n stream,\n namespace,\n message,\n meta,\n fallback,\n components,\n ...props\n}: LoadExternalComponentProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const id = React.useId();\n const shadowRootId = `child-shadow-${id}`;\n\n const store = React.useMemo(\n () => COMPONENT_STORE.getBoundStore(shadowRootId),\n [shadowRootId],\n );\n const state = React.useSyncExternalStore(store.subscribe, store.getSnapshot);\n\n const clientComponent = components?.[message.name];\n const hasClientComponent = clientComponent != null;\n\n let fallbackComponent = null;\n if (isReactNode(fallback)) {\n fallbackComponent = fallback;\n } else if (typeof fallback === \"object\" && fallback != null) {\n fallbackComponent = fallback?.[message.name];\n }\n\n const uiNamespace = namespace ?? stream.assistantId;\n const uiClient = stream.client[\"~ui\"];\n React.useEffect(() => {\n if (hasClientComponent) return;\n void uiClient.getComponent(uiNamespace, message.name).then((html) => {\n const dom = ref.current;\n if (!dom) return;\n const root = dom.shadowRoot ?? dom.attachShadow({ mode: \"open\" });\n const fragment = document\n .createRange()\n .createContextualFragment(\n html.replace(\"{{shadowRootId}}\", shadowRootId),\n );\n root.appendChild(fragment);\n });\n }, [uiClient, uiNamespace, message.name, shadowRootId, hasClientComponent]);\n\n if (hasClientComponent) {\n return (\n <UseStreamContext.Provider value={{ stream, meta }}>\n {React.createElement(clientComponent, message.props)}\n </UseStreamContext.Provider>\n );\n }\n\n return (\n <>\n <div id={shadowRootId} ref={ref} {...props} />\n\n <UseStreamContext.Provider value={{ stream, meta }}>\n {state?.target != null\n ? ReactDOM.createPortal(\n React.createElement(state.comp, message.props),\n state.target,\n )\n : fallbackComponent}\n </UseStreamContext.Provider>\n </>\n );\n}\n\ndeclare global {\n interface Window {\n [EXT_STORE_SYMBOL]: ComponentStore;\n [REQUIRE_SYMBOL]: (name: string) => unknown;\n [REQUIRE_EXTRA_SYMBOL]: Record<string, unknown>;\n }\n}\n\nexport function experimental_loadShare(name: string, module: unknown) {\n if (typeof window === \"undefined\") return;\n\n window[REQUIRE_EXTRA_SYMBOL] ??= {};\n window[REQUIRE_EXTRA_SYMBOL][name] = module;\n}\n\nexport function bootstrapUiContext() {\n if (typeof window === \"undefined\") {\n return;\n }\n\n window[EXT_STORE_SYMBOL] = COMPONENT_STORE;\n window[REQUIRE_SYMBOL] = (name: string) => {\n if (name === \"react\") return React;\n if (name === \"react-dom\") return ReactDOM;\n if (name === \"react/jsx-runtime\") return JsxRuntime;\n if (name === \"@langchain/langgraph-sdk/react\") return { useStream };\n if (name === \"@langchain/langgraph-sdk/react-ui\") {\n return {\n useStreamContext,\n LoadExternalComponent: () => {\n throw new Error(\"Nesting LoadExternalComponent is not supported\");\n },\n };\n }\n\n if (\n window[REQUIRE_EXTRA_SYMBOL] != null &&\n typeof window[REQUIRE_EXTRA_SYMBOL] === \"object\" &&\n name in window[REQUIRE_EXTRA_SYMBOL]\n ) {\n return window[REQUIRE_EXTRA_SYMBOL][name];\n }\n\n throw new Error(`Unknown module...: ${name}`);\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,mBAAmB,MAAM,cAG5B,KAAM;AAaT,SAAgB,mBAGsB;CACpC,MAAM,MAAM,MAAM,WAAW,iBAAiB;AAC9C,KAAI,CAAC,IACH,OAAM,IAAI,MACR,+DACD;AAGH,QAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAA8C;AACxD,MAAI,SAAS,OAAQ,QAAO,OAAO;AACnC,SAAO,OAAO,OAAO;IAExB,CAAC;;AAQJ,IAAM,iBAAN,MAAqB;CACnB,AAAQ,QAAyC,EAAE;CAEnD,AAAQ,aAMJ,EAAE;CAEN,AAAQ,YAMJ,EAAE;CAEN,QACE,cACA,MACA,eACA;AACA,OAAK,MAAM,gBAAgB;GAAE;GAAM,QAAQ;GAAe;AAC1D,OAAK,UAAU,eAAe,SAAS,MAAM,EAAE,MAAM,cAAc,CAAC;;CAGtE,cAAc,cAAsB;AAClC,OAAK,WAAW,kBAAkB;GAChC,YAAY,kBAA8B;AACxC,SAAK,UAAU,kBAAkB,EAAE;AACnC,SAAK,UAAU,cAAc,KAAK,cAAc;AAChD,iBAAa;AACX,UAAK,UAAU,gBAAgB,KAAK,UAAU,cAAc,QACzD,MAAM,MAAM,cACd;;;GAGL,mBAAmB,KAAK,MAAM;GAC/B;AAED,SAAO,KAAK,WAAW;;;AAI3B,MAAM,k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sx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport * as JsxRuntime from \"react/jsx-runtime\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { useStream } from \"../index.js\";\nimport type { UIMessage } from \"./types.js\";\nimport type { UseStream } from \"../types.js\";\n\nconst UseStreamContext = React.createContext<{\n stream: ReturnType<typeof useStream>;\n meta: unknown;\n}>(null!);\n\ntype GetMetaType<Bag extends BagTemplate> = Bag extends { MetaType: unknown }\n ? Bag[\"MetaType\"]\n : unknown;\n\ninterface UseStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n> extends UseStream<StateType, Bag> {\n meta?: GetMetaType<Bag>;\n}\n\nexport function useStreamContext<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(): UseStreamContext<StateType, Bag> {\n const ctx = React.useContext(UseStreamContext);\n if (!ctx) {\n throw new Error(\n \"useStreamContext must be used within a LoadExternalComponent\",\n );\n }\n\n return new Proxy(ctx, {\n get(target, prop: keyof UseStreamContext<StateType, Bag>) {\n if (prop === \"meta\") return target.meta;\n return target.stream[prop as keyof typeof target.stream];\n },\n }) as unknown as UseStreamContext<StateType, Bag>;\n}\n\ninterface ComponentTarget {\n comp: React.FunctionComponent | React.ComponentClass;\n target: HTMLElement;\n}\n\nclass ComponentStore {\n private cache: Record<string, ComponentTarget> = {};\n\n private boundCache: Record<\n string,\n {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => ComponentTarget | undefined;\n }\n > = {};\n\n private callbacks: Record<\n string,\n ((\n comp: React.FunctionComponent | React.ComponentClass,\n el: HTMLElement,\n ) => void)[]\n > = {};\n\n respond(\n shadowRootId: string,\n comp: React.FunctionComponent | React.ComponentClass,\n targetElement: HTMLElement,\n ) {\n this.cache[shadowRootId] = { comp, target: targetElement };\n this.callbacks[shadowRootId]?.forEach((c) => c(comp, targetElement));\n }\n\n getBoundStore(shadowRootId: string) {\n this.boundCache[shadowRootId] ??= {\n subscribe: (onStoreChange: () => void) => {\n this.callbacks[shadowRootId] ??= [];\n this.callbacks[shadowRootId].push(onStoreChange);\n return () => {\n this.callbacks[shadowRootId] = this.callbacks[shadowRootId].filter(\n (c) => c !== onStoreChange,\n );\n };\n },\n getSnapshot: () => this.cache[shadowRootId],\n };\n\n return this.boundCache[shadowRootId];\n }\n}\n\nconst COMPONENT_STORE = new ComponentStore();\nconst EXT_STORE_SYMBOL = Symbol.for(\"LGUI_EXT_STORE\");\nconst REQUIRE_SYMBOL = Symbol.for(\"LGUI_REQUIRE\");\nconst REQUIRE_EXTRA_SYMBOL = Symbol.for(\"LGUI_REQUIRE_EXTRA\");\n\ninterface LoadExternalComponentProps extends Pick<\n React.HTMLAttributes<HTMLDivElement>,\n \"style\" | \"className\"\n> {\n /** Stream of the assistant */\n stream: ReturnType<typeof useStream>;\n\n /** Namespace of UI components. Defaults to assistant ID. */\n namespace?: string;\n\n /** UI message to be rendered */\n message: UIMessage;\n\n /** Additional context to be passed to the child component */\n meta?: unknown;\n\n /** Fallback to be rendered when the component is loading */\n fallback?: React.ReactNode | Record<string, React.ReactNode>;\n\n /**\n * Map of components that can be rendered directly without fetching the UI code\n * from the server.\n */\n components?: Record<string, React.FunctionComponent | React.ComponentClass>;\n}\n\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n value != null && typeof value === \"object\" && Symbol.iterator in value;\n\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n value != null &&\n typeof value === \"object\" &&\n \"then\" in value &&\n typeof value.then === \"function\";\n\nconst isReactNode = (value: unknown): value is React.ReactNode => {\n if (React.isValidElement(value)) return true;\n if (value == null) return true;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (isIterable(value)) return true;\n if (isPromise(value)) return true;\n\n return false;\n};\n\nexport function LoadExternalComponent({\n stream,\n namespace,\n message,\n meta,\n fallback,\n components,\n ...props\n}: LoadExternalComponentProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const id = React.useId();\n const shadowRootId = `child-shadow-${id}`;\n\n const store = React.useMemo(\n () => COMPONENT_STORE.getBoundStore(shadowRootId),\n [shadowRootId],\n );\n const state = React.useSyncExternalStore(store.subscribe, store.getSnapshot);\n\n const clientComponent = components?.[message.name];\n const hasClientComponent = clientComponent != null;\n\n let fallbackComponent = null;\n if (isReactNode(fallback)) {\n fallbackComponent = fallback;\n } else if (typeof fallback === \"object\" && fallback != null) {\n fallbackComponent = fallback?.[message.name];\n }\n\n const uiNamespace = namespace ?? stream.assistantId;\n const uiClient = stream.client[\"~ui\"];\n React.useEffect(() => {\n if (hasClientComponent) return;\n void uiClient.getComponent(uiNamespace, message.name).then((html) => {\n const dom = ref.current;\n if (!dom) return;\n const root = dom.shadowRoot ?? dom.attachShadow({ mode: \"open\" });\n const fragment = document\n .createRange()\n .createContextualFragment(\n html.replace(\"{{shadowRootId}}\", shadowRootId),\n );\n root.appendChild(fragment);\n });\n }, [uiClient, uiNamespace, message.name, shadowRootId, hasClientComponent]);\n\n if (hasClientComponent) {\n return (\n <UseStreamContext.Provider value={{ stream, meta }}>\n {React.createElement(clientComponent, message.props)}\n </UseStreamContext.Provider>\n );\n }\n\n return (\n <>\n <div id={shadowRootId} ref={ref} {...props} />\n\n <UseStreamContext.Provider value={{ stream, meta }}>\n {state?.target != null\n ? ReactDOM.createPortal(\n React.createElement(state.comp, message.props),\n state.target,\n )\n : fallbackComponent}\n </UseStreamContext.Provider>\n </>\n );\n}\n\ndeclare global {\n interface Window {\n [EXT_STORE_SYMBOL]: ComponentStore;\n [REQUIRE_SYMBOL]: (name: string) => unknown;\n [REQUIRE_EXTRA_SYMBOL]: Record<string, unknown>;\n }\n}\n\nexport function experimental_loadShare(name: string, module: unknown) {\n if (typeof window === \"undefined\") return;\n\n window[REQUIRE_EXTRA_SYMBOL] ??= {};\n window[REQUIRE_EXTRA_SYMBOL][name] = module;\n}\n\nexport function bootstrapUiContext() {\n if (typeof window === \"undefined\") {\n return;\n }\n\n window[EXT_STORE_SYMBOL] = COMPONENT_STORE;\n window[REQUIRE_SYMBOL] = (name: string) => {\n if (name === \"react\") return React;\n if (name === \"react-dom\") return ReactDOM;\n if (name === \"react/jsx-runtime\") return JsxRuntime;\n if (name === \"@langchain/langgraph-sdk/react\") return { useStream };\n if (name === \"@langchain/langgraph-sdk/react-ui\") {\n return {\n useStreamContext,\n LoadExternalComponent: () => {\n throw new Error(\"Nesting LoadExternalComponent is not supported\");\n },\n };\n }\n\n if (\n window[REQUIRE_EXTRA_SYMBOL] != null &&\n typeof window[REQUIRE_EXTRA_SYMBOL] === \"object\" &&\n name in window[REQUIRE_EXTRA_SYMBOL]\n ) {\n return window[REQUIRE_EXTRA_SYMBOL][name];\n }\n\n throw new Error(`Unknown module...: ${name}`);\n };\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,mBAAmB,MAAM,cAG5B,KAAM;AAaT,SAAgB,mBAGsB;CACpC,MAAM,MAAM,MAAM,WAAW,iBAAiB;AAC9C,KAAI,CAAC,IACH,OAAM,IAAI,MACR,+DACD;AAGH,QAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,MAA8C;AACxD,MAAI,SAAS,OAAQ,QAAO,OAAO;AACnC,SAAO,OAAO,OAAO;IAExB,CAAC;;AAQJ,IAAM,iBAAN,MAAqB;CACnB,QAAiD,EAAE;CAEnD,aAMI,EAAE;CAEN,YAMI,EAAE;CAEN,QACE,cACA,MACA,eACA;AACA,OAAK,MAAM,gBAAgB;GAAE;GAAM,QAAQ;GAAe;AAC1D,OAAK,UAAU,eAAe,SAAS,MAAM,EAAE,MAAM,cAAc,CAAC;;CAGtE,cAAc,cAAsB;AAClC,OAAK,WAAW,kBAAkB;GAChC,YAAY,kBAA8B;AACxC,SAAK,UAAU,kBAAkB,EAAE;AACnC,SAAK,UAAU,cAAc,KAAK,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B,UAAM,IAAI,MAAM,iDAAiD;;GAEpE;AAGH,MACE,OAAO,yBAAyB,QAChC,OAAO,OAAO,0BAA0B,YACxC,QAAQ,OAAO,sBAEf,QAAO,OAAO,sBAAsB;AAGtC,QAAM,IAAI,MAAM,sBAAsB,OAAO"}
|
package/dist/react-ui/index.cjs
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value:
|
|
2
|
-
const require_client = require(
|
|
3
|
-
const require_types = require(
|
|
4
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_client = require("./client.cjs");
|
|
3
|
+
const require_types = require("./types.cjs");
|
|
5
4
|
//#region src/react-ui/index.ts
|
|
6
5
|
require_client.bootstrapUiContext();
|
|
7
|
-
|
|
8
6
|
//#endregion
|
|
9
7
|
exports.LoadExternalComponent = require_client.LoadExternalComponent;
|
|
10
8
|
exports.experimental_loadShare = require_client.experimental_loadShare;
|
|
@@ -12,4 +10,5 @@ exports.isRemoveUIMessage = require_types.isRemoveUIMessage;
|
|
|
12
10
|
exports.isUIMessage = require_types.isUIMessage;
|
|
13
11
|
exports.uiMessageReducer = require_types.uiMessageReducer;
|
|
14
12
|
exports.useStreamContext = require_client.useStreamContext;
|
|
13
|
+
|
|
15
14
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["bootstrapUiContext"],"sources":["../../src/react-ui/index.ts"],"sourcesContent":["import { bootstrapUiContext } from \"./client.js\";\n\nbootstrapUiContext();\n\nexport {\n useStreamContext,\n LoadExternalComponent,\n experimental_loadShare,\n} from \"./client.js\";\nexport {\n uiMessageReducer,\n isUIMessage,\n isRemoveUIMessage,\n type UIMessage,\n type RemoveUIMessage,\n} from \"./types.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["bootstrapUiContext"],"sources":["../../src/react-ui/index.ts"],"sourcesContent":["import { bootstrapUiContext } from \"./client.js\";\n\nbootstrapUiContext();\n\nexport {\n useStreamContext,\n LoadExternalComponent,\n experimental_loadShare,\n} from \"./client.js\";\nexport {\n uiMessageReducer,\n isUIMessage,\n isRemoveUIMessage,\n type UIMessage,\n type RemoveUIMessage,\n} from \"./types.js\";\n"],"mappings":";;;;AAEAA,eAAAA,oBAAoB"}
|
package/dist/react-ui/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { LoadExternalComponent, bootstrapUiContext, experimental_loadShare, useStreamContext } from "./client.js";
|
|
2
2
|
import { isRemoveUIMessage, isUIMessage, uiMessageReducer } from "./types.js";
|
|
3
|
-
|
|
4
3
|
//#region src/react-ui/index.ts
|
|
5
4
|
bootstrapUiContext();
|
|
6
|
-
|
|
7
5
|
//#endregion
|
|
8
6
|
export { LoadExternalComponent, experimental_loadShare, isRemoveUIMessage, isUIMessage, uiMessageReducer, useStreamContext };
|
|
7
|
+
|
|
9
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/react-ui/index.ts"],"sourcesContent":["import { bootstrapUiContext } from \"./client.js\";\n\nbootstrapUiContext();\n\nexport {\n useStreamContext,\n LoadExternalComponent,\n experimental_loadShare,\n} from \"./client.js\";\nexport {\n uiMessageReducer,\n isUIMessage,\n isRemoveUIMessage,\n type UIMessage,\n type RemoveUIMessage,\n} from \"./types.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/react-ui/index.ts"],"sourcesContent":["import { bootstrapUiContext } from \"./client.js\";\n\nbootstrapUiContext();\n\nexport {\n useStreamContext,\n LoadExternalComponent,\n experimental_loadShare,\n} from \"./client.js\";\nexport {\n uiMessageReducer,\n isUIMessage,\n isRemoveUIMessage,\n type UIMessage,\n type RemoveUIMessage,\n} from \"./types.js\";\n"],"mappings":";;;AAEA,oBAAoB"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value:
|
|
2
|
-
const require_types = require(
|
|
3
|
-
const require_server = require(
|
|
4
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_types = require("../types.cjs");
|
|
3
|
+
const require_server = require("./server.cjs");
|
|
5
4
|
exports.typedUi = require_server.typedUi;
|
|
6
|
-
exports.uiMessageReducer = require_types.uiMessageReducer;
|
|
5
|
+
exports.uiMessageReducer = require_types.uiMessageReducer;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
require("../../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
let uuid = require("uuid");
|
|
3
|
-
|
|
4
3
|
//#region src/react-ui/server/server.ts
|
|
5
4
|
/**
|
|
6
5
|
* Helper to send and persist UI messages. Accepts a map of component names to React components
|
|
@@ -51,7 +50,7 @@ const typedUi = (config, options) => {
|
|
|
51
50
|
items
|
|
52
51
|
};
|
|
53
52
|
};
|
|
54
|
-
|
|
55
53
|
//#endregion
|
|
56
54
|
exports.typedUi = typedUi;
|
|
55
|
+
|
|
57
56
|
//# sourceMappingURL=server.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":[],"sources":["../../../src/react-ui/server/server.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport type { ComponentPropsWithoutRef, ElementType } from \"react\";\nimport type { RemoveUIMessage, UIMessage } from \"../types.js\";\n\ninterface MessageLike {\n id?: string;\n}\n\n/**\n * Helper to send and persist UI messages. Accepts a map of component names to React components\n * as type argument to provide type safety. Will also write to the `options?.stateKey` state.\n *\n * @param config LangGraphRunnableConfig\n * @param options\n * @returns\n */\nexport const typedUi = <Decl extends Record<string, ElementType>>(\n config: {\n writer?: (chunk: unknown) => void;\n runId?: string;\n metadata?: Record<string, unknown>;\n tags?: string[];\n runName?: string;\n configurable?: {\n __pregel_send?: (writes_: [string, unknown][]) => void;\n [key: string]: unknown;\n };\n },\n options?: {\n /** The key to write the UI messages to. Defaults to `ui`. */\n stateKey?: string;\n },\n) => {\n type PropMap = { [K in keyof Decl]: ComponentPropsWithoutRef<Decl[K]> };\n const items: (UIMessage | RemoveUIMessage)[] = [];\n const stateKey = options?.stateKey ?? \"ui\";\n\n const runId = (config.metadata?.run_id as string | undefined) ?? config.runId;\n if (!runId) throw new Error(\"run_id is required\");\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K];\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K]>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options: { message?: MessageLike; merge: true },\n ): UIMessage<K, Partial<PropMap[K]>>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K] | Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K] | Partial<PropMap[K]>> {\n const evt: UIMessage<K, PropMap[K] | Partial<PropMap[K]>> = {\n type: \"ui\" as const,\n id: message?.id ?? uuidv4(),\n name: message?.name,\n props: message?.props,\n metadata: {\n merge: options?.merge || undefined,\n run_id: runId,\n tags: config.tags,\n name: config.runName,\n ...message?.metadata,\n ...(options?.message ? { message_id: options.message.id } : null),\n },\n };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n }\n\n const handleDelete = (id: string): RemoveUIMessage => {\n const evt: RemoveUIMessage = { type: \"remove-ui\", id };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n };\n\n return { push: handlePush, delete: handleDelete, items };\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.cjs","names":[],"sources":["../../../src/react-ui/server/server.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport type { ComponentPropsWithoutRef, ElementType } from \"react\";\nimport type { RemoveUIMessage, UIMessage } from \"../types.js\";\n\ninterface MessageLike {\n id?: string;\n}\n\n/**\n * Helper to send and persist UI messages. Accepts a map of component names to React components\n * as type argument to provide type safety. Will also write to the `options?.stateKey` state.\n *\n * @param config LangGraphRunnableConfig\n * @param options\n * @returns\n */\nexport const typedUi = <Decl extends Record<string, ElementType>>(\n config: {\n writer?: (chunk: unknown) => void;\n runId?: string;\n metadata?: Record<string, unknown>;\n tags?: string[];\n runName?: string;\n configurable?: {\n __pregel_send?: (writes_: [string, unknown][]) => void;\n [key: string]: unknown;\n };\n },\n options?: {\n /** The key to write the UI messages to. Defaults to `ui`. */\n stateKey?: string;\n },\n) => {\n type PropMap = { [K in keyof Decl]: ComponentPropsWithoutRef<Decl[K]> };\n const items: (UIMessage | RemoveUIMessage)[] = [];\n const stateKey = options?.stateKey ?? \"ui\";\n\n const runId = (config.metadata?.run_id as string | undefined) ?? config.runId;\n if (!runId) throw new Error(\"run_id is required\");\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K];\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K]>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options: { message?: MessageLike; merge: true },\n ): UIMessage<K, Partial<PropMap[K]>>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K] | Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K] | Partial<PropMap[K]>> {\n const evt: UIMessage<K, PropMap[K] | Partial<PropMap[K]>> = {\n type: \"ui\" as const,\n id: message?.id ?? uuidv4(),\n name: message?.name,\n props: message?.props,\n metadata: {\n merge: options?.merge || undefined,\n run_id: runId,\n tags: config.tags,\n name: config.runName,\n ...message?.metadata,\n ...(options?.message ? { message_id: options.message.id } : null),\n },\n };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n }\n\n const handleDelete = (id: string): RemoveUIMessage => {\n const evt: RemoveUIMessage = { type: \"remove-ui\", id };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n };\n\n return { push: handlePush, delete: handleDelete, items };\n};\n"],"mappings":";;;;;;;;;;;AAgBA,MAAa,WACX,QAWA,YAIG;CAEH,MAAM,QAAyC,EAAE;CACjD,MAAM,WAAW,SAAS,YAAY;CAEtC,MAAM,QAAS,OAAO,UAAU,UAAiC,OAAO;AACxE,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,qBAAqB;CAsBjD,SAAS,WACP,SAMA,SACgD;EAChD,MAAM,MAAsD;GAC1D,MAAM;GACN,IAAI,SAAS,OAAA,GAAA,KAAA,KAAc;GAC3B,MAAM,SAAS;GACf,OAAO,SAAS;GAChB,UAAU;IACR,OAAO,SAAS,SAAS,KAAA;IACzB,QAAQ;IACR,MAAM,OAAO;IACb,MAAM,OAAO;IACb,GAAG,SAAS;IACZ,GAAI,SAAS,UAAU,EAAE,YAAY,QAAQ,QAAQ,IAAI,GAAG;IAC7D;GACF;AACD,QAAM,KAAK,IAAI;AACf,SAAO,SAAS,IAAI;AACpB,SAAO,cAAc,gBAAgB,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC;AACvD,SAAO;;CAGT,MAAM,gBAAgB,OAAgC;EACpD,MAAM,MAAuB;GAAE,MAAM;GAAa;GAAI;AACtD,QAAM,KAAK,IAAI;AACf,SAAO,SAAS,IAAI;AACpB,SAAO,cAAc,gBAAgB,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC;AACvD,SAAO;;AAGT,QAAO;EAAE,MAAM;EAAY,QAAQ;EAAc;EAAO"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { v4 } from "uuid";
|
|
2
|
-
|
|
3
2
|
//#region src/react-ui/server/server.ts
|
|
4
3
|
/**
|
|
5
4
|
* Helper to send and persist UI messages. Accepts a map of component names to React components
|
|
@@ -50,7 +49,7 @@ const typedUi = (config, options) => {
|
|
|
50
49
|
items
|
|
51
50
|
};
|
|
52
51
|
};
|
|
53
|
-
|
|
54
52
|
//#endregion
|
|
55
53
|
export { typedUi };
|
|
54
|
+
|
|
56
55
|
//# sourceMappingURL=server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["uuidv4"],"sources":["../../../src/react-ui/server/server.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport type { ComponentPropsWithoutRef, ElementType } from \"react\";\nimport type { RemoveUIMessage, UIMessage } from \"../types.js\";\n\ninterface MessageLike {\n id?: string;\n}\n\n/**\n * Helper to send and persist UI messages. Accepts a map of component names to React components\n * as type argument to provide type safety. Will also write to the `options?.stateKey` state.\n *\n * @param config LangGraphRunnableConfig\n * @param options\n * @returns\n */\nexport const typedUi = <Decl extends Record<string, ElementType>>(\n config: {\n writer?: (chunk: unknown) => void;\n runId?: string;\n metadata?: Record<string, unknown>;\n tags?: string[];\n runName?: string;\n configurable?: {\n __pregel_send?: (writes_: [string, unknown][]) => void;\n [key: string]: unknown;\n };\n },\n options?: {\n /** The key to write the UI messages to. Defaults to `ui`. */\n stateKey?: string;\n },\n) => {\n type PropMap = { [K in keyof Decl]: ComponentPropsWithoutRef<Decl[K]> };\n const items: (UIMessage | RemoveUIMessage)[] = [];\n const stateKey = options?.stateKey ?? \"ui\";\n\n const runId = (config.metadata?.run_id as string | undefined) ?? config.runId;\n if (!runId) throw new Error(\"run_id is required\");\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K];\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K]>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options: { message?: MessageLike; merge: true },\n ): UIMessage<K, Partial<PropMap[K]>>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K] | Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K] | Partial<PropMap[K]>> {\n const evt: UIMessage<K, PropMap[K] | Partial<PropMap[K]>> = {\n type: \"ui\" as const,\n id: message?.id ?? uuidv4(),\n name: message?.name,\n props: message?.props,\n metadata: {\n merge: options?.merge || undefined,\n run_id: runId,\n tags: config.tags,\n name: config.runName,\n ...message?.metadata,\n ...(options?.message ? { message_id: options.message.id } : null),\n },\n };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n }\n\n const handleDelete = (id: string): RemoveUIMessage => {\n const evt: RemoveUIMessage = { type: \"remove-ui\", id };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n };\n\n return { push: handlePush, delete: handleDelete, items };\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.js","names":["uuidv4"],"sources":["../../../src/react-ui/server/server.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport type { ComponentPropsWithoutRef, ElementType } from \"react\";\nimport type { RemoveUIMessage, UIMessage } from \"../types.js\";\n\ninterface MessageLike {\n id?: string;\n}\n\n/**\n * Helper to send and persist UI messages. Accepts a map of component names to React components\n * as type argument to provide type safety. Will also write to the `options?.stateKey` state.\n *\n * @param config LangGraphRunnableConfig\n * @param options\n * @returns\n */\nexport const typedUi = <Decl extends Record<string, ElementType>>(\n config: {\n writer?: (chunk: unknown) => void;\n runId?: string;\n metadata?: Record<string, unknown>;\n tags?: string[];\n runName?: string;\n configurable?: {\n __pregel_send?: (writes_: [string, unknown][]) => void;\n [key: string]: unknown;\n };\n },\n options?: {\n /** The key to write the UI messages to. Defaults to `ui`. */\n stateKey?: string;\n },\n) => {\n type PropMap = { [K in keyof Decl]: ComponentPropsWithoutRef<Decl[K]> };\n const items: (UIMessage | RemoveUIMessage)[] = [];\n const stateKey = options?.stateKey ?? \"ui\";\n\n const runId = (config.metadata?.run_id as string | undefined) ?? config.runId;\n if (!runId) throw new Error(\"run_id is required\");\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K];\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K]>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options: { message?: MessageLike; merge: true },\n ): UIMessage<K, Partial<PropMap[K]>>;\n\n function handlePush<K extends keyof PropMap & string>(\n message: {\n id?: string;\n name: K;\n props: PropMap[K] | Partial<PropMap[K]>;\n metadata?: Record<string, unknown>;\n },\n options?: { message?: MessageLike; merge?: boolean },\n ): UIMessage<K, PropMap[K] | Partial<PropMap[K]>> {\n const evt: UIMessage<K, PropMap[K] | Partial<PropMap[K]>> = {\n type: \"ui\" as const,\n id: message?.id ?? uuidv4(),\n name: message?.name,\n props: message?.props,\n metadata: {\n merge: options?.merge || undefined,\n run_id: runId,\n tags: config.tags,\n name: config.runName,\n ...message?.metadata,\n ...(options?.message ? { message_id: options.message.id } : null),\n },\n };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n }\n\n const handleDelete = (id: string): RemoveUIMessage => {\n const evt: RemoveUIMessage = { type: \"remove-ui\", id };\n items.push(evt);\n config.writer?.(evt);\n config.configurable?.__pregel_send?.([[stateKey, evt]]);\n return evt;\n };\n\n return { push: handlePush, delete: handleDelete, items };\n};\n"],"mappings":";;;;;;;;;;AAgBA,MAAa,WACX,QAWA,YAIG;CAEH,MAAM,QAAyC,EAAE;CACjD,MAAM,WAAW,SAAS,YAAY;CAEtC,MAAM,QAAS,OAAO,UAAU,UAAiC,OAAO;AACxE,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,qBAAqB;CAsBjD,SAAS,WACP,SAMA,SACgD;EAChD,MAAM,MAAsD;GAC1D,MAAM;GACN,IAAI,SAAS,MAAMA,IAAQ;GAC3B,MAAM,SAAS;GACf,OAAO,SAAS;GAChB,UAAU;IACR,OAAO,SAAS,SAAS,KAAA;IACzB,QAAQ;IACR,MAAM,OAAO;IACb,MAAM,OAAO;IACb,GAAG,SAAS;IACZ,GAAI,SAAS,UAAU,EAAE,YAAY,QAAQ,QAAQ,IAAI,GAAG;IAC7D;GACF;AACD,QAAM,KAAK,IAAI;AACf,SAAO,SAAS,IAAI;AACpB,SAAO,cAAc,gBAAgB,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC;AACvD,SAAO;;CAGT,MAAM,gBAAgB,OAAgC;EACpD,MAAM,MAAuB;GAAE,MAAM;GAAa;GAAI;AACtD,QAAM,KAAK,IAAI;AACf,SAAO,SAAS,IAAI;AACpB,SAAO,cAAc,gBAAgB,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC;AACvD,SAAO;;AAGT,QAAO;EAAE,MAAM;EAAY,QAAQ;EAAc;EAAO"}
|
package/dist/react-ui/types.cjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
//#region src/react-ui/types.ts
|
|
3
2
|
function isUIMessage(message) {
|
|
4
3
|
if (typeof message !== "object" || message == null) return false;
|
|
@@ -30,9 +29,9 @@ function uiMessageReducer(state, update) {
|
|
|
30
29
|
}
|
|
31
30
|
return newState;
|
|
32
31
|
}
|
|
33
|
-
|
|
34
32
|
//#endregion
|
|
35
33
|
exports.isRemoveUIMessage = isRemoveUIMessage;
|
|
36
34
|
exports.isUIMessage = isUIMessage;
|
|
37
35
|
exports.uiMessageReducer = uiMessageReducer;
|
|
36
|
+
|
|
38
37
|
//# sourceMappingURL=types.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","names":[],"sources":["../../src/react-ui/types.ts"],"sourcesContent":["export interface UIMessage<\n TName extends string = string,\n TProps extends Record<string, unknown> = Record<string, unknown>,\n> {\n type: \"ui\";\n\n id: string;\n name: TName;\n props: TProps;\n metadata?: {\n merge?: boolean;\n run_id?: string;\n name?: string;\n tags?: string[];\n message_id?: string;\n [key: string]: unknown;\n };\n}\n\nexport interface RemoveUIMessage {\n type: \"remove-ui\";\n id: string;\n}\n\nexport function isUIMessage(message: unknown): message is UIMessage {\n if (typeof message !== \"object\" || message == null) return false;\n if (!(\"type\" in message)) return false;\n return message.type === \"ui\";\n}\n\nexport function isRemoveUIMessage(\n message: unknown,\n): message is RemoveUIMessage {\n if (typeof message !== \"object\" || message == null) return false;\n if (!(\"type\" in message)) return false;\n return message.type === \"remove-ui\";\n}\n\nexport function uiMessageReducer(\n state: UIMessage[],\n update: UIMessage | RemoveUIMessage | (UIMessage | RemoveUIMessage)[],\n) {\n const events = Array.isArray(update) ? update : [update];\n let newState = state.slice();\n\n for (const event of events) {\n if (event.type === \"remove-ui\") {\n newState = newState.filter((ui) => ui.id !== event.id);\n continue;\n }\n\n const index = state.findIndex((ui) => ui.id === event.id);\n if (index !== -1) {\n newState[index] =\n typeof event.metadata === \"object\" &&\n event.metadata != null &&\n event.metadata.merge\n ? { ...event, props: { ...state[index].props, ...event.props } }\n : event;\n } else {\n newState.push(event);\n }\n }\n\n return newState;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.cjs","names":[],"sources":["../../src/react-ui/types.ts"],"sourcesContent":["export interface UIMessage<\n TName extends string = string,\n TProps extends Record<string, unknown> = Record<string, unknown>,\n> {\n type: \"ui\";\n\n id: string;\n name: TName;\n props: TProps;\n metadata?: {\n merge?: boolean;\n run_id?: string;\n name?: string;\n tags?: string[];\n message_id?: string;\n [key: string]: unknown;\n };\n}\n\nexport interface RemoveUIMessage {\n type: \"remove-ui\";\n id: string;\n}\n\nexport function isUIMessage(message: unknown): message is UIMessage {\n if (typeof message !== \"object\" || message == null) return false;\n if (!(\"type\" in message)) return false;\n return message.type === \"ui\";\n}\n\nexport function isRemoveUIMessage(\n message: unknown,\n): message is RemoveUIMessage {\n if (typeof message !== \"object\" || message == null) return false;\n if (!(\"type\" in message)) return false;\n return message.type === \"remove-ui\";\n}\n\nexport function uiMessageReducer(\n state: UIMessage[],\n update: UIMessage | RemoveUIMessage | (UIMessage | RemoveUIMessage)[],\n) {\n const events = Array.isArray(update) ? update : [update];\n let newState = state.slice();\n\n for (const event of events) {\n if (event.type === \"remove-ui\") {\n newState = newState.filter((ui) => ui.id !== event.id);\n continue;\n }\n\n const index = state.findIndex((ui) => ui.id === event.id);\n if (index !== -1) {\n newState[index] =\n typeof event.metadata === \"object\" &&\n event.metadata != null &&\n event.metadata.merge\n ? { ...event, props: { ...state[index].props, ...event.props } }\n : event;\n } else {\n newState.push(event);\n }\n }\n\n return newState;\n}\n"],"mappings":";AAwBA,SAAgB,YAAY,SAAwC;AAClE,KAAI,OAAO,YAAY,YAAY,WAAW,KAAM,QAAO;AAC3D,KAAI,EAAE,UAAU,SAAU,QAAO;AACjC,QAAO,QAAQ,SAAS;;AAG1B,SAAgB,kBACd,SAC4B;AAC5B,KAAI,OAAO,YAAY,YAAY,WAAW,KAAM,QAAO;AAC3D,KAAI,EAAE,UAAU,SAAU,QAAO;AACjC,QAAO,QAAQ,SAAS;;AAG1B,SAAgB,iBACd,OACA,QACA;CACA,MAAM,SAAS,MAAM,QAAQ,OAAO,GAAG,SAAS,CAAC,OAAO;CACxD,IAAI,WAAW,MAAM,OAAO;AAE5B,MAAK,MAAM,SAAS,QAAQ;AAC1B,MAAI,MAAM,SAAS,aAAa;AAC9B,cAAW,SAAS,QAAQ,OAAO,GAAG,OAAO,MAAM,GAAG;AACtD;;EAGF,MAAM,QAAQ,MAAM,WAAW,OAAO,GAAG,OAAO,MAAM,GAAG;AACzD,MAAI,UAAU,GACZ,UAAS,SACP,OAAO,MAAM,aAAa,YAC1B,MAAM,YAAY,QAClB,MAAM,SAAS,QACX;GAAE,GAAG;GAAO,OAAO;IAAE,GAAG,MAAM,OAAO;IAAO,GAAG,MAAM;IAAO;GAAE,GAC9D;MAEN,UAAS,KAAK,MAAM;;AAIxB,QAAO"}
|
package/dist/react-ui/types.js
CHANGED
package/dist/stream.cjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
const require_stream_lgp = require(
|
|
3
|
-
const require_stream_custom = require(
|
|
1
|
+
require("./_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
const require_stream_lgp = require("./stream.lgp.cjs");
|
|
3
|
+
const require_stream_custom = require("./stream.custom.cjs");
|
|
4
4
|
let react = require("react");
|
|
5
|
-
|
|
6
5
|
//#region src/stream.tsx
|
|
7
6
|
function isCustomOptions(options) {
|
|
8
7
|
return "transport" in options;
|
|
@@ -12,7 +11,7 @@ function useStream(options) {
|
|
|
12
11
|
if (isCustom) return require_stream_custom.useStreamCustom(options);
|
|
13
12
|
return require_stream_lgp.useStreamLGP(options);
|
|
14
13
|
}
|
|
15
|
-
|
|
16
14
|
//#endregion
|
|
17
15
|
exports.useStream = useStream;
|
|
16
|
+
|
|
18
17
|
//# sourceMappingURL=stream.cjs.map
|
package/dist/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","names":["useStreamCustom","useStreamLGP"],"sources":["../src/stream.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type {\n BaseMessage,\n ToolMessage as CoreToolMessage,\n AIMessage as CoreAIMessage,\n} from \"@langchain/core/messages\";\nimport type {\n BagTemplate,\n ToolCallWithResult,\n DefaultToolCall,\n} from \"@langchain/langgraph-sdk\";\nimport type {\n UseStreamOptions,\n AcceptBaseMessages,\n ResolveStreamInterface,\n ResolveStreamOptions,\n InferBag,\n InferStateType,\n MessageMetadata,\n SubagentStreamInterface,\n} from \"@langchain/langgraph-sdk/ui\";\nimport { useStreamLGP } from \"./stream.lgp.js\";\nimport { useStreamCustom } from \"./stream.custom.js\";\nimport type { UseStreamCustomOptions } from \"./types.js\";\n\nfunction isCustomOptions<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options:\n | UseStreamOptions<StateType, Bag>\n | UseStreamCustomOptions<StateType, Bag>,\n): options is UseStreamCustomOptions<StateType, Bag> {\n return \"transport\" in options;\n}\n\ntype ClassToolCallWithResult<T> =\n T extends ToolCallWithResult<infer TC, unknown, unknown>\n ? ToolCallWithResult<TC, CoreToolMessage, CoreAIMessage>\n : T;\n\nexport type ClassSubagentStreamInterface<\n StateType = Record<string, unknown>,\n ToolCall = DefaultToolCall,\n SubagentName extends string = string,\n> = Omit<\n SubagentStreamInterface<StateType, ToolCall, SubagentName>,\n \"messages\"\n> & {\n messages: BaseMessage[];\n};\n\n/**\n * Maps a stream interface to use @langchain/core BaseMessage class instances\n * instead of plain Message objects for the `messages` property, and remaps\n * tool call types to use @langchain/core message classes.\n */\ntype WithClassMessages<T> = Omit<\n T,\n | \"messages\"\n | \"getMessagesMetadata\"\n | \"toolCalls\"\n | \"getToolCalls\"\n | \"submit\"\n | \"subagents\"\n | \"activeSubagents\"\n | \"getSubagent\"\n | \"getSubagentsByType\"\n | \"getSubagentsByMessage\"\n> & {\n messages: BaseMessage[];\n getMessagesMetadata: (\n message: BaseMessage,\n index?: number,\n ) => MessageMetadata<Record<string, unknown>> | undefined;\n} & (\"submit\" extends keyof T\n ? {\n submit: T extends {\n submit: (values: infer V, options?: infer O) => infer Ret;\n }\n ? (\n values:\n | AcceptBaseMessages<Exclude<V, null | undefined>>\n | null\n | undefined,\n options?: O,\n ) => Ret\n : never;\n }\n : unknown) &\n (\"toolCalls\" extends keyof T\n ? {\n toolCalls: T extends { toolCalls: (infer TC)[] }\n ? ClassToolCallWithResult<TC>[]\n : never;\n }\n : unknown) &\n (\"getToolCalls\" extends keyof T\n ? {\n getToolCalls: T extends {\n getToolCalls: (message: infer _M) => (infer TC)[];\n }\n ? (message: CoreAIMessage) => ClassToolCallWithResult<TC>[]\n : never;\n }\n : unknown) &\n (\"subagents\" extends keyof T\n ? {\n subagents: T extends {\n subagents: Map<\n string,\n SubagentStreamInterface<infer S, infer TC, infer N>\n >;\n }\n ? Map<string, ClassSubagentStreamInterface<S, TC, N>>\n : never;\n activeSubagents: T extends {\n activeSubagents: SubagentStreamInterface<\n infer S,\n infer TC,\n infer N\n >[];\n }\n ? ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n getSubagent: T extends {\n getSubagent: (\n id: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N> | undefined;\n }\n ? (\n toolCallId: string,\n ) => ClassSubagentStreamInterface<S, TC, N> | undefined\n : never;\n getSubagentsByType: T extends {\n getSubagentsByType: (\n type: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N>[];\n }\n ? (type: string) => ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n getSubagentsByMessage: T extends {\n getSubagentsByMessage: (\n id: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N>[];\n }\n ? (messageId: string) => ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n }\n : unknown);\n\n/**\n * A React hook that provides seamless integration with LangGraph streaming capabilities.\n *\n * The `useStream` hook handles all the complexities of streaming, state management, and branching logic,\n * letting you focus on building great chat experiences. It provides automatic state management for\n * messages, interrupts, loading states, subagent streams, and errors.\n *\n * ## Usage with ReactAgent (recommended for createAgent users)\n *\n * When using `createAgent` from `@langchain/langgraph`, you can pass `typeof agent` as the\n * type parameter to automatically infer tool call types:\n *\n * @example\n * ```typescript\n * // In your agent file (e.g., agent.ts)\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async ({ location }) => `Weather in ${location}`,\n * { name: \"get_weather\", schema: z.object({ location: z.string() }) }\n * );\n *\n * export const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * });\n *\n * // In your React component\n * import { agent } from \"./agent\";\n *\n * function Chat() {\n * // Tool calls are automatically typed from the agent's tools!\n * const stream = useStream<typeof agent>({\n * assistantId: \"agent\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.toolCalls[0].call.name is typed as \"get_weather\"\n * // stream.toolCalls[0].call.args is typed as { location: string }\n * }\n * ```\n *\n * ## Usage with StateGraph (for custom LangGraph applications)\n *\n * When building custom graphs with `StateGraph`, embed your tool call types directly\n * in your state's messages property using `Message<MyToolCalls>`:\n *\n * @example\n * ```typescript\n * import { Message } from \"@langchain/langgraph-sdk\";\n *\n * // Define your tool call types as a discriminated union\n * type MyToolCalls =\n * | { name: \"search\"; args: { query: string }; id?: string }\n * | { name: \"calculate\"; args: { expression: string }; id?: string };\n *\n * // Embed tool call types in your state's messages\n * interface MyGraphState {\n * messages: Message<MyToolCalls>[];\n * context?: string;\n * }\n *\n * function Chat() {\n * const stream = useStream<MyGraphState>({\n * assistantId: \"my-graph\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.values is typed as MyGraphState\n * // stream.toolCalls[0].call.name is typed as \"search\" | \"calculate\"\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With additional type configuration (interrupts, configurable)\n * interface MyGraphState {\n * messages: Message<MyToolCalls>[];\n * }\n *\n * function Chat() {\n * const stream = useStream<MyGraphState, {\n * InterruptType: { question: string };\n * ConfigurableType: { userId: string };\n * }>({\n * assistantId: \"my-graph\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.interrupt is typed as { question: string } | undefined\n * }\n * ```\n *\n * ## Usage with Deep Agents (subagent streaming, experimental)\n *\n * For agents that spawn subagents (nested graphs), use `filterSubagentMessages`\n * to keep the main message stream clean while tracking subagent activity separately:\n *\n * @example\n * ```typescript\n * import { useStream, SubagentStream } from \"@langchain/langgraph-sdk/react\";\n * import type { agent } from \"./agent\";\n *\n * function DeepAgentChat() {\n * const stream = useStream<typeof agent>({\n * assistantId: \"deepagent\",\n * apiUrl: \"http://localhost:2024\",\n * // Filter subagent messages from main stream\n * filterSubagentMessages: true,\n * });\n *\n * const handleSubmit = (content: string) => {\n * stream.submit(\n * { messages: [{ content, type: \"human\" }] },\n * { streamSubgraphs: true } // Enable subgraph streaming\n * );\n * };\n *\n * // Access subagent streams via stream.subagents (Map<string, SubagentStream>)\n * const subagentList = [...stream.subagents.values()];\n *\n * return (\n * <div>\n * {stream.messages.map((msg) => <Message key={msg.id} message={msg} />)}\n *\n * {subagentList.map((subagent) => (\n * <SubagentCard\n * key={subagent.id}\n * status={subagent.status} // \"pending\" | \"running\" | \"complete\" | \"error\"\n * messages={subagent.messages}\n * toolCalls={subagent.toolCalls}\n * />\n * ))}\n * </div>\n * );\n * }\n * ```\n *\n * @template T Either a ReactAgent type (with `~agentTypes`) or a state type (`Record<string, unknown>`)\n * @template Bag Type configuration bag containing:\n * - `ConfigurableType`: Type for the `config.configurable` property\n * - `InterruptType`: Type for interrupt values\n * - `CustomEventType`: Type for custom events\n * - `UpdateType`: Type for the submit function updates\n *\n * @see {@link https://docs.langchain.com/langgraph-platform/use-stream-react | LangGraph React Integration Guide}\n */\nexport function useStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: ResolveStreamOptions<T, InferBag<T, Bag>>,\n): WithClassMessages<ResolveStreamInterface<T, InferBag<T, Bag>>>;\n\n/**\n * A React hook that provides seamless integration with LangGraph streaming capabilities.\n *\n * The `useStream` hook handles all the complexities of streaming, state management, and branching logic,\n * letting you focus on building great chat experiences. It provides automatic state management for\n * messages, interrupts, loading states, and errors.\n *\n * @template T Either a ReactAgent type (with `~agentTypes`) or a state type (`Record<string, unknown>`)\n * @template Bag Type configuration bag containing:\n * - `ConfigurableType`: Type for the `config.configurable` property\n * - `InterruptType`: Type for interrupt values\n * - `CustomEventType`: Type for custom events\n * - `UpdateType`: Type for the submit function updates\n *\n * @see {@link https://docs.langchain.com/langgraph-platform/use-stream-react | LangGraph React Integration Guide}\n */\nexport function useStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: UseStreamCustomOptions<InferStateType<T>, InferBag<T, Bag>>,\n): WithClassMessages<ResolveStreamInterface<T, InferBag<T, Bag>>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useStream(options: any): any {\n // Store this in useState to make sure we're not changing the implementation in re-renders\n const [isCustom] = useState(isCustomOptions(options));\n\n if (isCustom) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStreamCustom(options);\n }\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStreamLGP(options);\n}\n"],"mappings":";;;;;;AAyBA,SAAS,gBAIP,SAGmD;AACnD,QAAO,eAAe;;AAySxB,SAAgB,UAAU,SAAmB;CAE3C,MAAM,CAAC,gCAAqB,gBAAgB,QAAQ,CAAC;AAErD,KAAI,SAEF,QAAOA,sCAAgB,QAAQ;AAIjC,QAAOC,gCAAa,QAAQ"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","names":["useStreamCustom","useStreamLGP"],"sources":["../src/stream.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type {\n BaseMessage,\n ToolMessage as CoreToolMessage,\n AIMessage as CoreAIMessage,\n} from \"@langchain/core/messages\";\nimport type {\n BagTemplate,\n ToolCallWithResult,\n DefaultToolCall,\n} from \"@langchain/langgraph-sdk\";\nimport type {\n UseStreamOptions,\n AcceptBaseMessages,\n ResolveStreamInterface,\n ResolveStreamOptions,\n InferBag,\n InferStateType,\n MessageMetadata,\n SubagentStreamInterface,\n} from \"@langchain/langgraph-sdk/ui\";\nimport { useStreamLGP } from \"./stream.lgp.js\";\nimport { useStreamCustom } from \"./stream.custom.js\";\nimport type { UseStreamCustomOptions } from \"./types.js\";\n\nfunction isCustomOptions<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options:\n | UseStreamOptions<StateType, Bag>\n | UseStreamCustomOptions<StateType, Bag>,\n): options is UseStreamCustomOptions<StateType, Bag> {\n return \"transport\" in options;\n}\n\ntype ClassToolCallWithResult<T> =\n T extends ToolCallWithResult<infer TC, unknown, unknown>\n ? ToolCallWithResult<TC, CoreToolMessage, CoreAIMessage>\n : T;\n\nexport type ClassSubagentStreamInterface<\n StateType = Record<string, unknown>,\n ToolCall = DefaultToolCall,\n SubagentName extends string = string,\n> = Omit<\n SubagentStreamInterface<StateType, ToolCall, SubagentName>,\n \"messages\"\n> & {\n messages: BaseMessage[];\n};\n\n/**\n * Maps a stream interface to use @langchain/core BaseMessage class instances\n * instead of plain Message objects for the `messages` property, and remaps\n * tool call types to use @langchain/core message classes.\n */\ntype WithClassMessages<T> = Omit<\n T,\n | \"messages\"\n | \"getMessagesMetadata\"\n | \"toolCalls\"\n | \"getToolCalls\"\n | \"submit\"\n | \"subagents\"\n | \"activeSubagents\"\n | \"getSubagent\"\n | \"getSubagentsByType\"\n | \"getSubagentsByMessage\"\n> & {\n messages: BaseMessage[];\n getMessagesMetadata: (\n message: BaseMessage,\n index?: number,\n ) => MessageMetadata<Record<string, unknown>> | undefined;\n} & (\"submit\" extends keyof T\n ? {\n submit: T extends {\n submit: (values: infer V, options?: infer O) => infer Ret;\n }\n ? (\n values:\n | AcceptBaseMessages<Exclude<V, null | undefined>>\n | null\n | undefined,\n options?: O,\n ) => Ret\n : never;\n }\n : unknown) &\n (\"toolCalls\" extends keyof T\n ? {\n toolCalls: T extends { toolCalls: (infer TC)[] }\n ? ClassToolCallWithResult<TC>[]\n : never;\n }\n : unknown) &\n (\"getToolCalls\" extends keyof T\n ? {\n getToolCalls: T extends {\n getToolCalls: (message: infer _M) => (infer TC)[];\n }\n ? (message: CoreAIMessage) => ClassToolCallWithResult<TC>[]\n : never;\n }\n : unknown) &\n (\"subagents\" extends keyof T\n ? {\n subagents: T extends {\n subagents: Map<\n string,\n SubagentStreamInterface<infer S, infer TC, infer N>\n >;\n }\n ? Map<string, ClassSubagentStreamInterface<S, TC, N>>\n : never;\n activeSubagents: T extends {\n activeSubagents: SubagentStreamInterface<\n infer S,\n infer TC,\n infer N\n >[];\n }\n ? ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n getSubagent: T extends {\n getSubagent: (\n id: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N> | undefined;\n }\n ? (\n toolCallId: string,\n ) => ClassSubagentStreamInterface<S, TC, N> | undefined\n : never;\n getSubagentsByType: T extends {\n getSubagentsByType: (\n type: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N>[];\n }\n ? (type: string) => ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n getSubagentsByMessage: T extends {\n getSubagentsByMessage: (\n id: string,\n ) => SubagentStreamInterface<infer S, infer TC, infer N>[];\n }\n ? (messageId: string) => ClassSubagentStreamInterface<S, TC, N>[]\n : never;\n }\n : unknown);\n\n/**\n * A React hook that provides seamless integration with LangGraph streaming capabilities.\n *\n * The `useStream` hook handles all the complexities of streaming, state management, and branching logic,\n * letting you focus on building great chat experiences. It provides automatic state management for\n * messages, interrupts, loading states, subagent streams, and errors.\n *\n * ## Usage with ReactAgent (recommended for createAgent users)\n *\n * When using `createAgent` from `@langchain/langgraph`, you can pass `typeof agent` as the\n * type parameter to automatically infer tool call types:\n *\n * @example\n * ```typescript\n * // In your agent file (e.g., agent.ts)\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async ({ location }) => `Weather in ${location}`,\n * { name: \"get_weather\", schema: z.object({ location: z.string() }) }\n * );\n *\n * export const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather],\n * });\n *\n * // In your React component\n * import { agent } from \"./agent\";\n *\n * function Chat() {\n * // Tool calls are automatically typed from the agent's tools!\n * const stream = useStream<typeof agent>({\n * assistantId: \"agent\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.toolCalls[0].call.name is typed as \"get_weather\"\n * // stream.toolCalls[0].call.args is typed as { location: string }\n * }\n * ```\n *\n * ## Usage with StateGraph (for custom LangGraph applications)\n *\n * When building custom graphs with `StateGraph`, embed your tool call types directly\n * in your state's messages property using `Message<MyToolCalls>`:\n *\n * @example\n * ```typescript\n * import { Message } from \"@langchain/langgraph-sdk\";\n *\n * // Define your tool call types as a discriminated union\n * type MyToolCalls =\n * | { name: \"search\"; args: { query: string }; id?: string }\n * | { name: \"calculate\"; args: { expression: string }; id?: string };\n *\n * // Embed tool call types in your state's messages\n * interface MyGraphState {\n * messages: Message<MyToolCalls>[];\n * context?: string;\n * }\n *\n * function Chat() {\n * const stream = useStream<MyGraphState>({\n * assistantId: \"my-graph\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.values is typed as MyGraphState\n * // stream.toolCalls[0].call.name is typed as \"search\" | \"calculate\"\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With additional type configuration (interrupts, configurable)\n * interface MyGraphState {\n * messages: Message<MyToolCalls>[];\n * }\n *\n * function Chat() {\n * const stream = useStream<MyGraphState, {\n * InterruptType: { question: string };\n * ConfigurableType: { userId: string };\n * }>({\n * assistantId: \"my-graph\",\n * apiUrl: \"http://localhost:2024\",\n * });\n *\n * // stream.interrupt is typed as { question: string } | undefined\n * }\n * ```\n *\n * ## Usage with Deep Agents (subagent streaming, experimental)\n *\n * For agents that spawn subagents (nested graphs), use `filterSubagentMessages`\n * to keep the main message stream clean while tracking subagent activity separately:\n *\n * @example\n * ```typescript\n * import { useStream, SubagentStream } from \"@langchain/langgraph-sdk/react\";\n * import type { agent } from \"./agent\";\n *\n * function DeepAgentChat() {\n * const stream = useStream<typeof agent>({\n * assistantId: \"deepagent\",\n * apiUrl: \"http://localhost:2024\",\n * // Filter subagent messages from main stream\n * filterSubagentMessages: true,\n * });\n *\n * const handleSubmit = (content: string) => {\n * stream.submit(\n * { messages: [{ content, type: \"human\" }] },\n * { streamSubgraphs: true } // Enable subgraph streaming\n * );\n * };\n *\n * // Access subagent streams via stream.subagents (Map<string, SubagentStream>)\n * const subagentList = [...stream.subagents.values()];\n *\n * return (\n * <div>\n * {stream.messages.map((msg) => <Message key={msg.id} message={msg} />)}\n *\n * {subagentList.map((subagent) => (\n * <SubagentCard\n * key={subagent.id}\n * status={subagent.status} // \"pending\" | \"running\" | \"complete\" | \"error\"\n * messages={subagent.messages}\n * toolCalls={subagent.toolCalls}\n * />\n * ))}\n * </div>\n * );\n * }\n * ```\n *\n * @template T Either a ReactAgent type (with `~agentTypes`) or a state type (`Record<string, unknown>`)\n * @template Bag Type configuration bag containing:\n * - `ConfigurableType`: Type for the `config.configurable` property\n * - `InterruptType`: Type for interrupt values\n * - `CustomEventType`: Type for custom events\n * - `UpdateType`: Type for the submit function updates\n *\n * @see {@link https://docs.langchain.com/langgraph-platform/use-stream-react | LangGraph React Integration Guide}\n */\nexport function useStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: ResolveStreamOptions<T, InferBag<T, Bag>>,\n): WithClassMessages<ResolveStreamInterface<T, InferBag<T, Bag>>>;\n\n/**\n * A React hook that provides seamless integration with LangGraph streaming capabilities.\n *\n * The `useStream` hook handles all the complexities of streaming, state management, and branching logic,\n * letting you focus on building great chat experiences. It provides automatic state management for\n * messages, interrupts, loading states, and errors.\n *\n * @template T Either a ReactAgent type (with `~agentTypes`) or a state type (`Record<string, unknown>`)\n * @template Bag Type configuration bag containing:\n * - `ConfigurableType`: Type for the `config.configurable` property\n * - `InterruptType`: Type for interrupt values\n * - `CustomEventType`: Type for custom events\n * - `UpdateType`: Type for the submit function updates\n *\n * @see {@link https://docs.langchain.com/langgraph-platform/use-stream-react | LangGraph React Integration Guide}\n */\nexport function useStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options: UseStreamCustomOptions<InferStateType<T>, InferBag<T, Bag>>,\n): WithClassMessages<ResolveStreamInterface<T, InferBag<T, Bag>>>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useStream(options: any): any {\n // Store this in useState to make sure we're not changing the implementation in re-renders\n const [isCustom] = useState(isCustomOptions(options));\n\n if (isCustom) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStreamCustom(options);\n }\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useStreamLGP(options);\n}\n"],"mappings":";;;;;AAyBA,SAAS,gBAIP,SAGmD;AACnD,QAAO,eAAe;;AAySxB,SAAgB,UAAU,SAAmB;CAE3C,MAAM,CAAC,aAAA,GAAA,MAAA,UAAqB,gBAAgB,QAAQ,CAAC;AAErD,KAAI,SAEF,QAAOA,sBAAAA,gBAAgB,QAAQ;AAIjC,QAAOC,mBAAAA,aAAa,QAAQ"}
|
package/dist/stream.custom.cjs
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
const require_thread = require('./thread.cjs');
|
|
2
|
+
require("./_virtual/_rolldown/runtime.cjs");
|
|
3
|
+
const require_thread = require("./thread.cjs");
|
|
5
4
|
let react = require("react");
|
|
6
5
|
let _langchain_langgraph_sdk_ui = require("@langchain/langgraph-sdk/ui");
|
|
7
6
|
let _langchain_langgraph_sdk_utils = require("@langchain/langgraph-sdk/utils");
|
|
8
|
-
|
|
9
7
|
//#region src/stream.custom.tsx
|
|
10
8
|
function useStreamCustom(options) {
|
|
11
9
|
const [messageManager] = (0, react.useState)(() => new _langchain_langgraph_sdk_ui.MessageTupleManager());
|
|
@@ -170,7 +168,7 @@ function useStreamCustom(options) {
|
|
|
170
168
|
}
|
|
171
169
|
};
|
|
172
170
|
}
|
|
173
|
-
|
|
174
171
|
//#endregion
|
|
175
172
|
exports.useStreamCustom = useStreamCustom;
|
|
173
|
+
|
|
176
174
|
//# sourceMappingURL=stream.custom.cjs.map
|