@talqing/react 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +170 -0
  3. package/dist/cjs/images.d.ts +17 -0
  4. package/dist/cjs/images.d.ts.map +1 -0
  5. package/dist/cjs/images.js +68 -0
  6. package/dist/cjs/images.js.map +1 -0
  7. package/dist/cjs/index.d.ts +10 -0
  8. package/dist/cjs/index.d.ts.map +1 -0
  9. package/dist/cjs/index.js +64 -0
  10. package/dist/cjs/index.js.map +1 -0
  11. package/dist/cjs/media.d.ts +20 -0
  12. package/dist/cjs/media.d.ts.map +1 -0
  13. package/dist/cjs/media.js +46 -0
  14. package/dist/cjs/media.js.map +1 -0
  15. package/dist/cjs/package.json +3 -0
  16. package/dist/cjs/rpc.d.ts +17 -0
  17. package/dist/cjs/rpc.d.ts.map +1 -0
  18. package/dist/cjs/rpc.js +48 -0
  19. package/dist/cjs/rpc.js.map +1 -0
  20. package/dist/cjs/session.d.ts +77 -0
  21. package/dist/cjs/session.d.ts.map +1 -0
  22. package/dist/cjs/session.js +55 -0
  23. package/dist/cjs/session.js.map +1 -0
  24. package/dist/cjs/userdata.d.ts +10 -0
  25. package/dist/cjs/userdata.d.ts.map +1 -0
  26. package/dist/cjs/userdata.js +24 -0
  27. package/dist/cjs/userdata.js.map +1 -0
  28. package/dist/esm/images.d.ts +17 -0
  29. package/dist/esm/images.d.ts.map +1 -0
  30. package/dist/esm/images.js +65 -0
  31. package/dist/esm/images.js.map +1 -0
  32. package/dist/esm/index.d.ts +10 -0
  33. package/dist/esm/index.d.ts.map +1 -0
  34. package/dist/esm/index.js +35 -0
  35. package/dist/esm/index.js.map +1 -0
  36. package/dist/esm/media.d.ts +20 -0
  37. package/dist/esm/media.d.ts.map +1 -0
  38. package/dist/esm/media.js +42 -0
  39. package/dist/esm/media.js.map +1 -0
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/rpc.d.ts +17 -0
  42. package/dist/esm/rpc.d.ts.map +1 -0
  43. package/dist/esm/rpc.js +44 -0
  44. package/dist/esm/rpc.js.map +1 -0
  45. package/dist/esm/session.d.ts +77 -0
  46. package/dist/esm/session.d.ts.map +1 -0
  47. package/dist/esm/session.js +50 -0
  48. package/dist/esm/session.js.map +1 -0
  49. package/dist/esm/userdata.d.ts +10 -0
  50. package/dist/esm/userdata.d.ts.map +1 -0
  51. package/dist/esm/userdata.js +21 -0
  52. package/dist/esm/userdata.js.map +1 -0
  53. package/package.json +73 -0
  54. package/src/images.ts +97 -0
  55. package/src/index.ts +58 -0
  56. package/src/media.ts +77 -0
  57. package/src/rpc.ts +61 -0
  58. package/src/session.tsx +148 -0
  59. package/src/userdata.ts +27 -0
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@talqing/react",
3
+ "version": "0.4.0",
4
+ "description": "React bindings for Talqing web calls: the session, images, screen share, userdata and frontend RPC.",
5
+ "license": "MIT",
6
+ "homepage": "https://talqing.com",
7
+ "bugs": {
8
+ "email": "hello@talqing.com"
9
+ },
10
+ "keywords": [
11
+ "talqing",
12
+ "ai",
13
+ "agents",
14
+ "voice",
15
+ "video",
16
+ "livekit",
17
+ "react"
18
+ ],
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "main": "./dist/cjs/index.js",
22
+ "module": "./dist/esm/index.js",
23
+ "types": "./dist/cjs/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "import": {
27
+ "types": "./dist/esm/index.d.ts",
28
+ "default": "./dist/esm/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/cjs/index.d.ts",
32
+ "default": "./dist/cjs/index.js"
33
+ }
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "src",
40
+ "README.md"
41
+ ],
42
+ "engines": {
43
+ "node": ">=20"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node ../../scripts/dist-markers.mjs",
50
+ "dev": "tsc -w -p tsconfig.json",
51
+ "typecheck": "tsc --noEmit -p tsconfig.typecheck.json",
52
+ "prepublishOnly": "npm run build"
53
+ },
54
+ "dependencies": {},
55
+ "peerDependencies": {
56
+ "@livekit/components-react": "^2.9.21",
57
+ "@talqing/client": "^0.4.0",
58
+ "@talqing/sdk": "^0.4.0",
59
+ "livekit-client": "^2.19.1",
60
+ "react": "^18.3.1 || ^19.0.0",
61
+ "react-dom": "^18.3.1 || ^19.0.0"
62
+ },
63
+ "devDependencies": {
64
+ "@livekit/components-react": "^2.9.21",
65
+ "@talqing/client": "^0.4.0",
66
+ "@talqing/sdk": "^0.4.0",
67
+ "@types/react": "^19.0.0",
68
+ "livekit-client": "^2.19.1",
69
+ "react": "^19.0.0",
70
+ "react-dom": "^19.0.0",
71
+ "typescript": "~5.9.3"
72
+ }
73
+ }
package/src/images.ts ADDED
@@ -0,0 +1,97 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ import type { Room } from "livekit-client";
5
+ import {
6
+ onTalqingImageResult,
7
+ sendTalqingImage,
8
+ TALQING_IMAGE_ACK_TIMEOUT_MS,
9
+ type TalqingSentImage,
10
+ } from "@talqing/client";
11
+
12
+ /** Send images to the agent on this call, and follow what became of each.
13
+ *
14
+ * `send` resolves once the bytes are on their way; the outcome arrives on the
15
+ * returned list, which is what a thumbnail should render.
16
+ *
17
+ * Takes the `Room` rather than reading it from the session context: a byte
18
+ * stream and an RPC handler are room-level things, and passing the room keeps
19
+ * this usable from a surface that manages its own connection —
20
+ * `useTalqingConnection().room` inside a provider, or the Room you built. */
21
+ export function useTalqingImages(room: Room | null | undefined) {
22
+ const [sent, setSent] = useState<TalqingSentImage[]>([]);
23
+ const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
24
+
25
+ const settle = useCallback((streamId: string, patch: Partial<TalqingSentImage>) => {
26
+ const timer = timers.current.get(streamId);
27
+ if (timer) {
28
+ clearTimeout(timer);
29
+ timers.current.delete(streamId);
30
+ }
31
+ setSent((images) =>
32
+ images.map((image) => (image.streamId === streamId ? { ...image, ...patch } : image)),
33
+ );
34
+ }, []);
35
+
36
+ useEffect(() => {
37
+ if (!room) return;
38
+ return onTalqingImageResult(room, ({ streamId, ok, error }) =>
39
+ settle(streamId, { status: ok ? "sent" : "failed", error }),
40
+ );
41
+ }, [room, settle]);
42
+
43
+ const pending = timers.current;
44
+ useEffect(
45
+ () => () => {
46
+ pending.forEach(clearTimeout);
47
+ pending.clear();
48
+ },
49
+ [pending],
50
+ );
51
+
52
+ /* Each thumbnail is an object URL over the downscaled blob, and each pins that
53
+ blob in memory until it is revoked. This hook is mounted per call, so
54
+ without this every call's images would be held for the life of the tab. */
55
+ const previews = useRef<string[]>([]);
56
+ useEffect(
57
+ () => () => {
58
+ previews.current.forEach(URL.revokeObjectURL);
59
+ previews.current = [];
60
+ },
61
+ [],
62
+ );
63
+
64
+ const send = useCallback(
65
+ async (file: File): Promise<TalqingSentImage> => {
66
+ if (!room) throw new Error("the call is not connected");
67
+ const image = await sendTalqingImage(room, file);
68
+ previews.current.push(image.previewUrl);
69
+ setSent((images) => [...images, image]);
70
+ timers.current.set(
71
+ image.streamId,
72
+ setTimeout(
73
+ () =>
74
+ settle(image.streamId, {
75
+ status: "unknown",
76
+ // Four states, not two: the one people forget is the agent going
77
+ // away mid-upload, where no ack is ever coming.
78
+ error: "we did not hear back — the agent may not have received it",
79
+ }),
80
+ TALQING_IMAGE_ACK_TIMEOUT_MS,
81
+ ),
82
+ );
83
+ return image;
84
+ },
85
+ [room, settle],
86
+ );
87
+
88
+ const clear = useCallback(() => {
89
+ setSent((images) => {
90
+ images.forEach((image) => URL.revokeObjectURL(image.previewUrl));
91
+ previews.current = [];
92
+ return [];
93
+ });
94
+ }, []);
95
+
96
+ return { send, sent, clear };
97
+ }
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ /* React bindings for the Talqing call protocol.
2
+ *
3
+ * Thin by design. Everything here is either the call lifecycle (`useTalqingSession`
4
+ * and the auth union it takes) or a hook over something `@talqing/client` does to
5
+ * a `Room`. Nothing here wraps LiveKit to rename it: the layer only ever ADDS, so
6
+ * anything LiveKit can do you can do — take `useTalqingConnection().room` and use
7
+ * `livekit-client` directly. We never remove a capability to make our own surface
8
+ * look tidier, which is also why `livekit-client` and `@livekit/components-react`
9
+ * are peer dependencies: the `Room` we hand you is the same class your own
10
+ * imports and `instanceof` resolve to.
11
+ */
12
+
13
+ export {
14
+ TalqingSessionProvider,
15
+ useTalqingConnection,
16
+ useTalqingSession,
17
+ } from "./session.js";
18
+ export type {
19
+ TalqingCallOptions,
20
+ TalqingSession,
21
+ TalqingSessionOptions,
22
+ } from "./session.js";
23
+
24
+ export { useTalqingUserdata } from "./userdata.js";
25
+ export { useTalqingImages } from "./images.js";
26
+ export { useTalqingFrontendRpcs, useTalqingRpcHandlers } from "./rpc.js";
27
+ export { useTalqingAvatarTrack, useTalqingScreenShare } from "./media.js";
28
+
29
+ /* All of `@talqing/client`, so one install and one import cover a web call.
30
+ * Everything there works against any `Room`, with or without React — the token
31
+ * source, the userdata and image and frontend-RPC calls, and the measured
32
+ * capture constants. Re-exported wholesale rather than as a curated list
33
+ * because the whole package is meant to be reachable from here, and a list
34
+ * would quietly fall behind it. */
35
+ export * from "@talqing/client";
36
+
37
+ /* LiveKit's own, re-exported UNDER THEIR OWN NAMES so a tenant installs one
38
+ * package and imports one name.
39
+ *
40
+ * Re-exporting is not wrapping: there is no surface of ours here to drift, and
41
+ * nothing is subtracted — `useAgent` is the ten-state discriminated union
42
+ * LiveKit ships, with every derived boolean, every action and
43
+ * `failureReasons` intact. Keeping LiveKit's names is the point: a
44
+ * `useTalqing`-prefixed alias would claim these as ours and hide where to read
45
+ * their documentation. Import them from `@livekit/components-react` instead if
46
+ * you prefer — it is the same module. */
47
+ export {
48
+ useAgent,
49
+ useSessionMessages,
50
+ VideoTrack,
51
+ } from "@livekit/components-react";
52
+ export type {
53
+ AgentState,
54
+ ReceivedMessage,
55
+ TrackReference,
56
+ UseAgentReturn,
57
+ UseSessionReturn,
58
+ } from "@livekit/components-react";
package/src/media.ts ADDED
@@ -0,0 +1,77 @@
1
+ "use client";
2
+
3
+ import { useMemo } from "react";
4
+ import { ParticipantKind, Track, type RemoteParticipant } from "livekit-client";
5
+ import {
6
+ useParticipantTracks,
7
+ useRemoteParticipants,
8
+ useTrackToggle,
9
+ useVoiceAssistant,
10
+ type TrackReference,
11
+ } from "@livekit/components-react";
12
+ import {
13
+ TALQING_SCREEN_SHARE_CAPTURE,
14
+ TALQING_SCREEN_SHARE_PUBLISH,
15
+ } from "@talqing/client";
16
+
17
+ /** Share the caller's screen with the agent, on the settings that keep it
18
+ * legible — see `TALQING_SCREEN_SHARE_CAPTURE` for why each one is what it is. */
19
+ export function useTalqingScreenShare() {
20
+ const { toggle, enabled, pending } = useTrackToggle({
21
+ source: Track.Source.ScreenShare,
22
+ captureOptions: TALQING_SCREEN_SHARE_CAPTURE,
23
+ publishOptions: TALQING_SCREEN_SHARE_PUBLISH,
24
+ });
25
+ return useMemo(
26
+ () => ({
27
+ /** Whether a screen is being shared right now. */
28
+ enabled,
29
+ /** True while the browser picker is open or the track is publishing. */
30
+ pending,
31
+ /** Opens the browser's share picker. Must be called from a user gesture. */
32
+ start: () => toggle(true),
33
+ /** Stops sharing. The agent is told it can no longer see on the next turn. */
34
+ stop: () => toggle(false),
35
+ }),
36
+ [enabled, pending, toggle],
37
+ );
38
+ }
39
+
40
+ /** The video track to render for a video agent.
41
+ *
42
+ * Prefers the avatar worker's camera — the worker publishes on the agent's
43
+ * behalf, which is how it is identified — and falls back through the worker's
44
+ * screen share and then the agent's own tracks. */
45
+ export function useTalqingAvatarTrack(): TrackReference | undefined {
46
+ const { agent } = useVoiceAssistant();
47
+ const remoteParticipants = useRemoteParticipants();
48
+ const worker = remoteParticipants.find(
49
+ (participant: RemoteParticipant) =>
50
+ participant.kind === ParticipantKind.AGENT &&
51
+ participant.attributes["lk.publish_on_behalf"] === agent?.identity,
52
+ );
53
+
54
+ const agentTracks = useParticipantTracks(
55
+ [Track.Source.Camera, Track.Source.ScreenShare],
56
+ agent?.identity,
57
+ );
58
+ const workerTracks = useParticipantTracks(
59
+ [Track.Source.Camera, Track.Source.ScreenShare],
60
+ worker?.identity,
61
+ );
62
+
63
+ return (
64
+ workerTracks.find(
65
+ (track: TrackReference) => track.source === Track.Source.Camera,
66
+ ) ??
67
+ workerTracks.find(
68
+ (track: TrackReference) => track.source === Track.Source.ScreenShare,
69
+ ) ??
70
+ agentTracks.find(
71
+ (track: TrackReference) => track.source === Track.Source.Camera,
72
+ ) ??
73
+ agentTracks.find(
74
+ (track: TrackReference) => track.source === Track.Source.ScreenShare,
75
+ )
76
+ );
77
+ }
package/src/rpc.ts ADDED
@@ -0,0 +1,61 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useState } from "react";
4
+ import {
5
+ registerTalqingRpcHandlers,
6
+ type JsonValue,
7
+ type TalqingRpcHandlers,
8
+ type TalqingRpcInvocation,
9
+ } from "@talqing/client";
10
+ import { useTalqingConnection } from "./session.js";
11
+
12
+ /** Handle the agent's `frontend_rpc` calls into this page.
13
+ *
14
+ * Registration waits for the room to connect and is undone on unmount. Pass
15
+ * `enabled: false` to hold off. */
16
+ export function useTalqingRpcHandlers(handlers: TalqingRpcHandlers, enabled = true) {
17
+ const { room, isConnected } = useTalqingConnection();
18
+
19
+ useEffect(() => {
20
+ if (!enabled || !room || !isConnected) return;
21
+ return registerTalqingRpcHandlers(room, handlers);
22
+ }, [enabled, handlers, isConnected, room]);
23
+ }
24
+
25
+ /** The declarative alternative: register nothing, render what arrived.
26
+ *
27
+ * Keeps the latest payload per method name and always answers the agent "ok". */
28
+ export function useTalqingFrontendRpcs(enabled = true) {
29
+ const [actions, setActions] = useState<
30
+ Record<string, { payload?: JsonValue; at: number }>
31
+ >({});
32
+
33
+ const handlers = useMemo<TalqingRpcHandlers>(
34
+ () => ({
35
+ "*": async (data: TalqingRpcInvocation) => {
36
+ const payload = JSON.parse(data.payload || "{}") as JsonValue;
37
+ const method = String((payload as { method?: string }).method || "");
38
+ if (method) {
39
+ setActions(
40
+ (current: Record<string, { payload?: JsonValue; at: number }>) => ({
41
+ ...current,
42
+ [method]: {
43
+ payload: (payload as { payload?: JsonValue }).payload,
44
+ at: Date.now(),
45
+ },
46
+ }),
47
+ );
48
+ }
49
+ return "ok";
50
+ },
51
+ }),
52
+ [],
53
+ );
54
+
55
+ useTalqingRpcHandlers(handlers, enabled);
56
+
57
+ return {
58
+ actions,
59
+ clear: () => setActions({}),
60
+ };
61
+ }
@@ -0,0 +1,148 @@
1
+ "use client";
2
+
3
+ import React, { useCallback, useMemo, useState } from "react";
4
+ import { Room, type RoomOptions } from "livekit-client";
5
+ import {
6
+ RoomAudioRenderer,
7
+ SessionProvider,
8
+ useSession,
9
+ useSessionContext,
10
+ type UseSessionReturn,
11
+ } from "@livekit/components-react";
12
+ import {
13
+ createTalqingTokenSource,
14
+ TALQING_AUDIO_CAPTURE_DEFAULTS,
15
+ type TalqingCallCredentials,
16
+ } from "@talqing/client";
17
+ import type { TalqingClient, TokenRequest } from "@talqing/sdk";
18
+
19
+ /** Everything about one web call except which agent runs it. Wire-shaped, like
20
+ * every other request type in this SDK. */
21
+ export type TalqingCallOptions = Omit<TokenRequest, "agent_id">;
22
+
23
+ /* Three ways to authorize one call, and exactly one of them per call.
24
+ *
25
+ * The branches are mutually exclusive by construction rather than by a runtime
26
+ * precedence rule: every branch declares every other branch's fields as
27
+ * `?: never`, so passing two is a type error at the call site.
28
+ *
29
+ * The first two are what a tenant ships. `POST /v1/calls/token` needs the EDITOR
30
+ * role, and a Talqing credential that can mint a call token can also create and
31
+ * delete agents, read every transcript and spend the workspace's credits — so it
32
+ * belongs on your server and nowhere near a browser. Your server mints; the
33
+ * browser receives two strings and joins.
34
+ *
35
+ * That is not only about the credential. `contact_key` decides WHOSE history the
36
+ * call resumes, and `userdata` is merged onto that person's record. A browser
37
+ * that chooses its own would be choosing whose past conversation to continue.
38
+ * On these two branches it never can: those fields never leave your backend.
39
+ */
40
+ type TalqingCallAuth =
41
+ /** Your server called `POST /v1/calls/token` and forwarded these two fields. */
42
+ | {
43
+ token: TalqingCallCredentials;
44
+ fetchToken?: never;
45
+ client?: never;
46
+ agentId?: never;
47
+ callOptions?: never;
48
+ }
49
+ /** Your endpoint mints one. Called once, when the call starts. */
50
+ | {
51
+ fetchToken: () => Promise<TalqingCallCredentials>;
52
+ token?: never;
53
+ client?: never;
54
+ agentId?: never;
55
+ callOptions?: never;
56
+ }
57
+ /** Mint from the browser with a `TalqingClient` that already holds a
58
+ * credential. **Trusted first-party surfaces only** — an app that is
59
+ * same-origin with the API and signed in as a real editor, which is what our
60
+ * own dashboard is. If you are embedding a call widget for your customers,
61
+ * this is not your branch. */
62
+ | {
63
+ client: TalqingClient;
64
+ agentId: string | null;
65
+ /** `contact_key`, `userdata`, `vars` and the per-call agent selection.
66
+ * Only on this branch: on the other two the server passes them when it
67
+ * mints, which is what keeps a browser from choosing whose history to
68
+ * resume. */
69
+ callOptions?: TalqingCallOptions;
70
+ token?: never;
71
+ fetchToken?: never;
72
+ };
73
+
74
+ export type TalqingSessionOptions = TalqingCallAuth & { roomOptions?: RoomOptions };
75
+
76
+ /** LiveKit's session, plus what resolving this call's plan complained about. */
77
+ export type TalqingSession = UseSessionReturn & {
78
+ /** An unreachable team member, a handoff into an agent that records when this
79
+ * one does not — resolved against state at CALL time, so it is not the list
80
+ * publishing returned. Empty until the token is minted.
81
+ *
82
+ * Populated on the `client` branch, which is the one where this browser is
83
+ * what minted. On the two server-minted branches your own server received
84
+ * them in the token response and this stays empty. */
85
+ warnings: string[];
86
+ };
87
+
88
+ /** One session, one call — `start()` it when this mounts and `end()` it on the
89
+ * way out, the lifecycle LiveKit's own session docs describe. A second call is
90
+ * a second mount, so give the component holding this a `key` that changes per
91
+ * call. Starting a finished session again would rejoin the room the last call
92
+ * used, which the API refuses. */
93
+ export function useTalqingSession(options: TalqingSessionOptions): TalqingSession {
94
+ const { token, fetchToken, client, agentId, callOptions, roomOptions } = options;
95
+ const [warnings, setWarnings] = useState<string[]>([]);
96
+
97
+ // Reads every branch's fields so the dependency list is the same length on
98
+ // each; all but one are `undefined` on any given call.
99
+ const mint = useCallback(async (): Promise<TalqingCallCredentials> => {
100
+ if (token) return token;
101
+ if (fetchToken) return await fetchToken();
102
+ if (!client) throw new Error("useTalqingSession needs one of token, fetchToken or client");
103
+ const minted = await client.calls.token({
104
+ tokenRequest: { ...callOptions, agent_id: agentId ?? null },
105
+ });
106
+ setWarnings(minted.warnings);
107
+ return { server_url: minted.server_url, participant_token: minted.participant_token };
108
+ }, [token, fetchToken, client, agentId, callOptions]);
109
+
110
+ const tokenSource = useMemo(() => createTalqingTokenSource(mint), [mint]);
111
+ const room = useMemo(
112
+ () =>
113
+ new Room({ audioCaptureDefaults: TALQING_AUDIO_CAPTURE_DEFAULTS, ...roomOptions }),
114
+ [roomOptions],
115
+ );
116
+ const session = useSession(tokenSource, { room });
117
+ return useMemo(() => ({ ...session, warnings }), [session, warnings]);
118
+ }
119
+
120
+ export function TalqingSessionProvider({
121
+ session,
122
+ children,
123
+ audio = true,
124
+ }: {
125
+ session: TalqingSession;
126
+ children: React.ReactNode;
127
+ audio?: boolean;
128
+ }) {
129
+ return (
130
+ <SessionProvider session={session}>
131
+ {children}
132
+ {audio ? <RoomAudioRenderer /> : null}
133
+ </SessionProvider>
134
+ );
135
+ }
136
+
137
+ /** The call itself, read from context — and `room`, which is the supported way
138
+ * down to raw `livekit-client` for anything this layer does not cover. */
139
+ export function useTalqingConnection() {
140
+ const ctx = useSessionContext();
141
+ return {
142
+ isConnected: ctx.isConnected,
143
+ connectionState: ctx.connectionState,
144
+ room: ctx.room,
145
+ start: ctx.start,
146
+ end: ctx.end,
147
+ };
148
+ }
@@ -0,0 +1,27 @@
1
+ "use client";
2
+
3
+ import { useMemo } from "react";
4
+ import {
5
+ getTalqingUserdata,
6
+ setTalqingUserdata,
7
+ type JsonObject,
8
+ } from "@talqing/client";
9
+ import { useTalqingConnection } from "./session.js";
10
+
11
+ /** Read and write the live session's userdata from inside a provider. */
12
+ export function useTalqingUserdata() {
13
+ const { room } = useTalqingConnection();
14
+ return useMemo(
15
+ () => ({
16
+ get: (keys?: string[], responseTimeout?: number) => {
17
+ if (!room) throw new Error("room is not connected");
18
+ return getTalqingUserdata(room, keys, responseTimeout);
19
+ },
20
+ set: (patch: JsonObject, responseTimeout?: number) => {
21
+ if (!room) throw new Error("room is not connected");
22
+ return setTalqingUserdata(room, patch, responseTimeout);
23
+ },
24
+ }),
25
+ [room],
26
+ );
27
+ }