@sts-ai/sdk 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,196 @@
1
- # Temporary Holding Version
1
+ # @sts-ai/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Every sts-ai service on **your own website, in your own design**: Chat AI, Voice AI, Form, Tour
4
+ and your business details. The package gives you state and actions only; your designer draws
5
+ every button, pop-up, orb and form, so nothing clashes with your site. Works with **React**,
6
+ **Vue / Nuxt** and **plain JavaScript**. Voice (LiveKit) is included.
7
+
8
+ ## Setup: one command
9
+
10
+ Run this inside your website's folder and approve once in the browser:
11
+
12
+ ```bash
13
+ npx @sts-ai/cli init
14
+ ```
15
+
16
+ It makes your website's key behind the scenes, allows your domain, installs this package and
17
+ wires it into your site (Next.js: `app/layout.tsx`; Nuxt: `plugins/sts-ai.client.ts`). Which
18
+ services show (Chat, Voice, Form, Tour) is switched in the sts-ai app, not in code.
19
+
20
+ <details>
21
+ <summary>By hand instead</summary>
22
+
23
+ ```bash
24
+ npm install @sts-ai/sdk
25
+ ```
26
+
27
+ React / Next.js:
28
+
29
+ ```tsx
30
+ import { StsProvider } from '@sts-ai/sdk/react'
31
+
32
+ <StsProvider apiBase="https://sudotechserve.com" siteKey={process.env.NEXT_PUBLIC_STS_SITE_KEY!}>
33
+ {children}
34
+ </StsProvider>
35
+ ```
36
+
37
+ Vue / Nuxt (`plugins/sts-ai.client.ts`):
38
+
39
+ ```ts
40
+ import { createStsPlugin } from '@sts-ai/sdk/vue'
41
+
42
+ export default defineNuxtPlugin((nuxtApp) => {
43
+ nuxtApp.vueApp.use(createStsPlugin({ apiBase: 'https://sudotechserve.com', siteKey: 'sts_pk_live_…' }))
44
+ })
45
+ ```
46
+
47
+ The site key is publishable (it only works on the website URLs you allow), so it is fine in
48
+ client code.
49
+ </details>
50
+
51
+ ## Example: your own pop-up button with Chat AI
52
+
53
+ ```tsx
54
+ 'use client'
55
+ import { useState } from 'react'
56
+ import { useStsChat } from '@sts-ai/sdk/react'
57
+
58
+ export function ChatBubble() {
59
+ const [open, setOpen] = useState(false)
60
+ const [text, setText] = useState('')
61
+ const { available, greeting, suggestions, messages, send, status } = useStsChat()
62
+ if (!available) return null
63
+
64
+ return (
65
+ <>
66
+ <button className="my-fab" onClick={() => setOpen(!open)}>Chat</button>
67
+ {open && (
68
+ <div className="my-popup">
69
+ <p>{greeting}</p>
70
+ {messages.map((m) => <p key={m.id} className={m.role}>{m.content}</p>)}
71
+ {messages.length === 0 && suggestions.map((s) => <button key={s} onClick={() => send(s)}>{s}</button>)}
72
+ <form onSubmit={(e) => { e.preventDefault(); send(text); setText('') }}>
73
+ <input value={text} onChange={(e) => setText(e.target.value)} />
74
+ <button disabled={status === 'thinking'}>Send</button>
75
+ </form>
76
+ </div>
77
+ )}
78
+ </>
79
+ )
80
+ }
81
+ ```
82
+
83
+ ## Hooks
84
+
85
+ | Hook | Returns |
86
+ |---|---|
87
+ | `useStsChat()` | `available, greeting, suggestions, documentRequests, messages, send(text), attach(file, documentId?), reset(), status, error` |
88
+ | `useStsSpeak()` | `state ('idle' \| 'connecting' \| 'live' \| 'ended' \| 'error'), start(), stop(), isAgentSpeaking, muted, setMuted(bool), captions, agentLevel, error` |
89
+ | `useStsForm()` | `form, values, setValue(id, v), consent, setConsent, submit(), status, message, fieldError` |
90
+ | `useStsWizard()` | `ready, start(), follow(), play(step), unlock(), savedSound(), rememberSound('on' \| 'off'), stop(), playing, speaking, step, stepIndex, caption, muted, setMuted` |
91
+
92
+ ### Chat: the attach button
93
+
94
+ When the chat assistant is set to ask for documents (AI agents → chat assistant → Documents),
95
+ `documentRequests` is not empty. Show your own attach button and pass the file to `attach()`.
96
+ The file goes to the business's Google Drive and the assistant confirms it arrived.
97
+
98
+ ```tsx
99
+ const { documentRequests, attach } = useStsChat()
100
+ {documentRequests.length > 0 && (
101
+ <input type="file" accept="application/pdf,image/*" onChange={(e) => e.target.files?.[0] && attach(e.target.files[0])} />
102
+ )}
103
+ ```
104
+
105
+ ### Voice: mute, captions and the sound level
106
+
107
+ `setMuted(true)` mutes the visitor's microphone. `captions` holds the last lines of the call
108
+ (`speaker: 'agent' | 'visitor'`, `final` once a line is complete). `agentLevel` goes from 0 to 1
109
+ about ten times a second: use it to animate an orb or bars.
110
+
111
+ ### Tour that follows the visitor's scroll
112
+
113
+ `start()` lets the tour lead: it scrolls to each section and narrates it. `follow()` lets the
114
+ visitor lead: nothing scrolls, and each `[data-sts-step]` section speaks once when it reaches the
115
+ middle of the screen. Browsers need one click before sound, so call `follow()` from your
116
+ "Sound on" button the first time, and save the answer with `rememberSound()`:
117
+
118
+ ```tsx
119
+ const tour = useStsWizard()
120
+ useEffect(() => {
121
+ if (tour.ready && tour.savedSound() === 'off') { tour.setMuted(true); tour.follow() }
122
+ }, [tour.ready])
123
+ <button onClick={() => { tour.rememberSound('on'); tour.follow() }}>Sound on</button>
124
+ ```
125
+
126
+ On a site that changes pages without reloading, call `follow()` again after each page change.
127
+ | `useStsBusiness()` | `business { name, description, profile }` |
128
+ | `useStsAnswers()` | `answers [{ question, answer }], ready, error`: the business's own answers, for an FAQ block |
129
+ | `useStsReviews()` | `reviews [{ name, rating, text, date }], ready, error`: reviews the business chose to show |
130
+ | `useStsInfo()` | business name + which services are on |
131
+
132
+ ### Wizard on your page
133
+
134
+ Tag sections, then style the active one:
135
+
136
+ ```html
137
+ <section data-sts-step="pricing">…</section>
138
+ <style>[data-sts-active] { outline: 2px solid #6366f1; }</style>
139
+ ```
140
+
141
+ Steps whose section isn't on the page are skipped. Audio needs a click to start (browser rule), so call `start()` from a button.
142
+
143
+ ## Vue / Nuxt
144
+
145
+ The same services as composables; every value is a ref.
146
+
147
+ ```vue
148
+ <script setup lang="ts">
149
+ import { useStsSpeak } from '@sts-ai/sdk/vue'
150
+ const { state, start, stop, agentLevel } = useStsSpeak()
151
+ </script>
152
+
153
+ <template>
154
+ <!-- your own orb: it grows with the AI's voice -->
155
+ <button class="orb" :style="{ transform: `scale(${1 + agentLevel * 0.4})` }" @click="state === 'live' ? stop() : start()">
156
+ {{ state === 'live' ? 'End call' : 'Talk to us' }}
157
+ </button>
158
+ </template>
159
+ ```
160
+
161
+ `useStsChat()`, `useStsSpeak()`, `useStsForm()`, `useStsWizard()`, `useStsBusiness()`,
162
+ `useStsAnswers()`, `useStsReviews()` and `useStsInfo()` return the same fields as the React hooks.
163
+
164
+ ## Tour from your own events
165
+
166
+ Play one step whenever your page wants, by its id or its `data-sts-step` name:
167
+
168
+ ```ts
169
+ const tour = useStsWizard() // React or Vue
170
+ button.addEventListener('click', () => tour.unlock()) // one click first: browsers need it for sound
171
+ window.addEventListener('pricing-open', () => tour.play('pricing'))
172
+ ```
173
+
174
+ ## Without a framework
175
+
176
+ ```ts
177
+ import { createSts, createChat, createVoice, createForm, createWizardPlayer } from '@sts-ai/sdk'
178
+
179
+ const sts = createSts({ apiBase: 'https://sudotechserve.com', siteKey: 'sts_pk_live_…' })
180
+
181
+ const chat = createChat(sts)
182
+ chat.subscribe((state) => renderMessages(state.messages)) // your own chat box
183
+ await chat.send('Hi!')
184
+
185
+ const voice = createVoice(sts)
186
+ voice.subscribe((state) => orb.style.setProperty('--level', String(state.agentLevel)))
187
+ orbButton.addEventListener('click', () => voice.start())
188
+
189
+ const { services } = await sts.info()
190
+ const tour = createWizardPlayer(await sts.wizard.load(services.wizards[0].slug))
191
+ document.addEventListener('scroll-into-pricing', () => tour.play('pricing'))
192
+ ```
193
+
194
+ ## Security
195
+
196
+ The site key is publishable: it only works from the website URLs you allow. The SDK swaps it for a 15-minute session token, and every call is rate-limited with daily caps per business.
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Framework-free controllers for each service. They hold the state (messages, call state,
3
+ * form values) and tell you when it changes, so any UI can use them: React and Vue wrap them,
4
+ * and plain JavaScript can call them straight from `window.addEventListener`.
5
+ *
6
+ * const chat = createChat(sts)
7
+ * chat.subscribe((state) => render(state.messages))
8
+ * await chat.send('Hi!')
9
+ */
10
+ import type { StsClient } from './core.js';
11
+ import { type StsChatLinks, type StsForm, type StsFormAnswer } from './types.js';
12
+ type Listener<T> = (state: T) => void;
13
+ export type StsChatMessage = {
14
+ id: string;
15
+ role: 'user' | 'assistant';
16
+ content: string;
17
+ links?: StsChatLinks;
18
+ };
19
+ export type StsChatState = {
20
+ messages: StsChatMessage[];
21
+ status: 'idle' | 'thinking' | 'error';
22
+ error: string | null;
23
+ };
24
+ /** Chat AI as a service: your floating button, pop-up or page draws it; this keeps the conversation. */
25
+ export declare function createChat(sts: StsClient): {
26
+ readonly state: StsChatState;
27
+ subscribe: (listener: Listener<StsChatState>) => () => void;
28
+ send: (text: string) => Promise<void>;
29
+ attach: (file: File, documentId?: string) => Promise<void>;
30
+ reset: () => void;
31
+ };
32
+ export type StsChatController = ReturnType<typeof createChat>;
33
+ /** One line of live captions. `final` is false while the words are still coming in. */
34
+ export type StsCaption = {
35
+ id: string;
36
+ speaker: 'agent' | 'visitor';
37
+ text: string;
38
+ final: boolean;
39
+ };
40
+ export type StsVoiceState = {
41
+ state: 'idle' | 'connecting' | 'live' | 'ended' | 'error';
42
+ isAgentSpeaking: boolean;
43
+ muted: boolean;
44
+ captions: StsCaption[];
45
+ /** The AI's voice loudness, 0 to 1, about ten times a second: drive an orb or bars with it. */
46
+ agentLevel: number;
47
+ error: string | null;
48
+ };
49
+ /**
50
+ * Voice AI as a service: a real-time call with the business's AI over WebRTC (LiveKit is
51
+ * included). Your orb, call button and captions are yours; call `start()` from a click.
52
+ */
53
+ export declare function createVoice(sts: StsClient): {
54
+ readonly state: StsVoiceState;
55
+ subscribe: (listener: Listener<StsVoiceState>) => () => void;
56
+ start: (participantName?: string) => Promise<void>;
57
+ stop: () => Promise<void>;
58
+ setMuted: (value: boolean) => Promise<void>;
59
+ };
60
+ export type StsVoiceController = ReturnType<typeof createVoice>;
61
+ export type StsFormState = {
62
+ form: StsForm | null;
63
+ values: Record<string, StsFormAnswer>;
64
+ consent: boolean;
65
+ status: 'loading' | 'ready' | 'submitting' | 'success' | 'error' | 'unavailable';
66
+ message: string | null;
67
+ /** The field the server refused, to highlight it. */
68
+ fieldError: string | null;
69
+ };
70
+ /** The business's form as a service: your fields and layout, its questions and its inbox. */
71
+ export declare function createForm(sts: StsClient): {
72
+ readonly state: StsFormState;
73
+ subscribe: (listener: Listener<StsFormState>) => () => void;
74
+ setValue: (fieldId: string, value: StsFormAnswer) => void;
75
+ setConsent: (consent: boolean) => void;
76
+ submit: () => Promise<void>;
77
+ };
78
+ export type StsFormController = ReturnType<typeof createForm>;
79
+ export {};
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Framework-free controllers for each service. They hold the state (messages, call state,
3
+ * form values) and tell you when it changes, so any UI can use them: React and Vue wrap them,
4
+ * and plain JavaScript can call them straight from `window.addEventListener`.
5
+ *
6
+ * const chat = createChat(sts)
7
+ * chat.subscribe((state) => render(state.messages))
8
+ * await chat.send('Hi!')
9
+ */
10
+ import { StsError } from './types.js';
11
+ /** A tiny observable value: `get()`, `subscribe(fn)` (called now and on every change). */
12
+ function store(initial) {
13
+ let state = initial;
14
+ const listeners = new Set();
15
+ return {
16
+ get: () => state,
17
+ set(patch) {
18
+ const next = typeof patch === 'function' ? patch(state) : patch;
19
+ state = { ...state, ...next };
20
+ listeners.forEach((listener) => listener(state));
21
+ },
22
+ subscribe(listener) {
23
+ listeners.add(listener);
24
+ listener(state);
25
+ return () => {
26
+ listeners.delete(listener);
27
+ };
28
+ },
29
+ };
30
+ }
31
+ const errorMessage = (error) => (error instanceof Error ? error.message : 'Something went wrong');
32
+ /** Chat AI as a service: your floating button, pop-up or page draws it; this keeps the conversation. */
33
+ export function createChat(sts) {
34
+ const state = store({ messages: [], status: 'idle', error: null });
35
+ let counter = 0;
36
+ const nextId = () => `m${(counter += 1)}`;
37
+ async function send(text) {
38
+ const message = text.trim();
39
+ if (!message || state.get().status === 'thinking')
40
+ return;
41
+ state.set((s) => ({ messages: [...s.messages, { id: nextId(), role: 'user', content: message }], status: 'thinking', error: null }));
42
+ try {
43
+ const result = await sts.chat.send(message);
44
+ state.set((s) => ({
45
+ messages: [...s.messages, { id: nextId(), role: 'assistant', content: result.reply, links: result.links }],
46
+ status: 'idle',
47
+ }));
48
+ }
49
+ catch (error) {
50
+ state.set({ status: 'error', error: errorMessage(error) });
51
+ }
52
+ }
53
+ /** Sends a file the assistant asked for (Drive), then tells the assistant it arrived. */
54
+ async function attach(file, documentId) {
55
+ if (state.get().status === 'thinking')
56
+ return;
57
+ state.set({ status: 'thinking', error: null });
58
+ try {
59
+ const uploaded = await sts.chat.attach(file, documentId);
60
+ state.set({ status: 'idle' });
61
+ await send(uploaded.message);
62
+ }
63
+ catch (error) {
64
+ state.set({ status: 'error', error: errorMessage(error) });
65
+ }
66
+ }
67
+ return {
68
+ get state() {
69
+ return state.get();
70
+ },
71
+ subscribe: state.subscribe,
72
+ send,
73
+ attach,
74
+ reset: () => state.set({ messages: [], status: 'idle', error: null }),
75
+ };
76
+ }
77
+ const MAX_CAPTIONS = 20;
78
+ const LEVEL_INTERVAL_MS = 100;
79
+ /**
80
+ * Voice AI as a service: a real-time call with the business's AI over WebRTC (LiveKit is
81
+ * included). Your orb, call button and captions are yours; call `start()` from a click.
82
+ */
83
+ export function createVoice(sts) {
84
+ const state = store({ state: 'idle', isAgentSpeaking: false, muted: false, captions: [], agentLevel: 0, error: null });
85
+ let room = null;
86
+ let callTimer = null;
87
+ let levelTimer = null;
88
+ let audioEls = [];
89
+ function upsertCaption(caption) {
90
+ state.set((s) => {
91
+ const index = s.captions.findIndex((item) => item.id === caption.id);
92
+ const next = index >= 0 ? s.captions.map((item, i) => (i === index ? caption : item)) : [...s.captions, caption];
93
+ return { captions: next.slice(-MAX_CAPTIONS) };
94
+ });
95
+ }
96
+ async function stop() {
97
+ if (callTimer)
98
+ clearTimeout(callTimer);
99
+ if (levelTimer)
100
+ clearInterval(levelTimer);
101
+ callTimer = null;
102
+ levelTimer = null;
103
+ const current = room;
104
+ room = null;
105
+ audioEls.forEach((el) => el.remove());
106
+ audioEls = [];
107
+ state.set((s) => ({ isAgentSpeaking: false, agentLevel: 0, muted: false, state: s.state === 'error' ? 'error' : 'ended' }));
108
+ if (current)
109
+ await current.disconnect();
110
+ }
111
+ async function start(participantName) {
112
+ if (room || state.get().state === 'connecting')
113
+ return;
114
+ state.set({ state: 'connecting', error: null, captions: [] });
115
+ try {
116
+ const [{ Room, RoomEvent, Track }, details] = await Promise.all([import('livekit-client'), sts.speak.connect(participantName)]);
117
+ const next = new Room();
118
+ next.on(RoomEvent.TrackSubscribed, (track) => {
119
+ if (track.kind !== Track.Kind.Audio)
120
+ return;
121
+ const element = track.attach();
122
+ element.style.display = 'none';
123
+ document.body.appendChild(element);
124
+ audioEls.push(element);
125
+ });
126
+ next.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
127
+ state.set({ isAgentSpeaking: speakers.some((speaker) => speaker.identity !== next.localParticipant.identity) });
128
+ });
129
+ next.on(RoomEvent.Disconnected, () => void stop());
130
+ // The voice agent publishes what both sides say on the "lk.transcription" text stream.
131
+ next.registerTextStreamHandler('lk.transcription', async (reader, participant) => {
132
+ const attributes = reader.info.attributes ?? {};
133
+ const id = attributes['lk.segment_id'] || reader.info.id;
134
+ const speaker = participant.identity === next.localParticipant.identity ? 'visitor' : 'agent';
135
+ let text = '';
136
+ for await (const chunk of reader) {
137
+ text += chunk;
138
+ upsertCaption({ id, speaker, text, final: false });
139
+ }
140
+ upsertCaption({ id, speaker, text, final: true });
141
+ });
142
+ await next.connect(details.serverUrl, details.participantToken);
143
+ await next.localParticipant.setMicrophoneEnabled(true);
144
+ room = next;
145
+ levelTimer = setInterval(() => {
146
+ const agent = [...next.remoteParticipants.values()][0];
147
+ state.set({ agentLevel: agent ? Math.min(1, agent.audioLevel) : 0 });
148
+ }, LEVEL_INTERVAL_MS);
149
+ state.set({ state: 'live' });
150
+ callTimer = setTimeout(() => void stop(), details.maxCallMinutes * 60000);
151
+ }
152
+ catch (error) {
153
+ state.set({ state: 'error', error: errorMessage(error) });
154
+ await stop();
155
+ }
156
+ }
157
+ /** Mutes or unmutes the visitor's microphone during a call. */
158
+ async function setMuted(value) {
159
+ if (!room)
160
+ return;
161
+ await room.localParticipant.setMicrophoneEnabled(!value);
162
+ state.set({ muted: value });
163
+ }
164
+ return {
165
+ get state() {
166
+ return state.get();
167
+ },
168
+ subscribe: state.subscribe,
169
+ start,
170
+ stop,
171
+ setMuted,
172
+ };
173
+ }
174
+ /** The business's form as a service: your fields and layout, its questions and its inbox. */
175
+ export function createForm(sts) {
176
+ const state = store({ form: null, values: {}, consent: false, status: 'loading', message: null, fieldError: null });
177
+ void sts.form
178
+ .schema()
179
+ .then((form) => state.set({ form, status: 'ready' }))
180
+ .catch((error) => state.set({
181
+ status: error instanceof StsError && error.code === 'SERVICE_DISABLED' ? 'unavailable' : 'error',
182
+ message: errorMessage(error),
183
+ }));
184
+ async function submit() {
185
+ const { values, consent } = state.get();
186
+ state.set({ status: 'submitting', fieldError: null });
187
+ try {
188
+ const message = await sts.form.submit(values, consent);
189
+ state.set({ status: 'success', message, values: {}, consent: false });
190
+ }
191
+ catch (error) {
192
+ state.set({ status: 'error', message: errorMessage(error), fieldError: error instanceof StsError ? error.fieldId : null });
193
+ }
194
+ }
195
+ return {
196
+ get state() {
197
+ return state.get();
198
+ },
199
+ subscribe: state.subscribe,
200
+ setValue: (fieldId, value) => state.set((s) => ({ values: { ...s.values, [fieldId]: value } })),
201
+ setConsent: (consent) => state.set({ consent }),
202
+ submit,
203
+ };
204
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { type StsAnswer, type StsReview, type StsBusiness, type StsChatReply, type StsChatUpload, type StsForm, type StsFormAnswer, type StsOptions, type StsSessionInfo, type StsSpeakConnection, type StsWizard } from './types.js';
2
+ /**
3
+ * Framework-agnostic STS-AI client. One instance per site.
4
+ * Handles the site-key → session exchange and refreshes the session before it expires.
5
+ */
6
+ export declare function createSts(options: StsOptions): {
7
+ apiBase: string;
8
+ /** Business name + which services are on. Cached for the session. */
9
+ info(): Promise<StsSessionInfo>;
10
+ chat: {
11
+ send(message: string): Promise<StsChatReply>;
12
+ /**
13
+ * Sends a document the chat asked for (PDF or photo, up to 10 MB) to the business's Google
14
+ * Drive. `documentId` is the id from `services.chat.documentRequests`, when you know it.
15
+ * Pass the returned `message` to `send()` so the assistant can confirm it arrived.
16
+ */
17
+ attach(file: File, documentId?: string): Promise<StsChatUpload>;
18
+ };
19
+ speak: {
20
+ /** LiveKit credentials for a new call. Use with `livekit-client` (the React hook does this for you). */
21
+ connect(participantName?: string): Promise<StsSpeakConnection>;
22
+ };
23
+ form: {
24
+ schema(): Promise<StsForm>;
25
+ submit(values: Record<string, StsFormAnswer>, consent: boolean): Promise<string>;
26
+ };
27
+ wizard: {
28
+ load(slug: string): Promise<StsWizard>;
29
+ };
30
+ business: {
31
+ get(): Promise<StsBusiness>;
32
+ /** The business's own answers to what customers ask most, for an FAQ block. */
33
+ answers(): Promise<StsAnswer[]>;
34
+ /** Reviews the business chose to show, newest first. */
35
+ reviews(): Promise<StsReview[]>;
36
+ };
37
+ };
38
+ export type StsClient = ReturnType<typeof createSts>;
package/dist/core.js ADDED
@@ -0,0 +1,126 @@
1
+ import { StsError, } from './types.js';
2
+ const SESSION_HEADER = 'X-Sts-Session';
3
+ const SITE_KEY_HEADER = 'X-Sts-Site-Key';
4
+ const REFRESH_MARGIN_MS = 60000;
5
+ const SESSION_ERRORS = new Set(['SESSION_REQUIRED', 'SESSION_INVALID', 'SESSION_EXPIRED']);
6
+ async function readJson(response) {
7
+ return (await response.json().catch(() => ({})));
8
+ }
9
+ function toError(response, body) {
10
+ return new StsError(body.error || `Request failed (${response.status})`, body.code || 'REQUEST_FAILED', response.status, body.fieldId ?? null);
11
+ }
12
+ /**
13
+ * Framework-agnostic STS-AI client. One instance per site.
14
+ * Handles the site-key → session exchange and refreshes the session before it expires.
15
+ */
16
+ export function createSts(options) {
17
+ const apiBase = options.apiBase.replace(/\/$/, '');
18
+ let session = null;
19
+ let pending = null;
20
+ async function openSession() {
21
+ const response = await fetch(`${apiBase}/api/sdk/v1/session`, {
22
+ method: 'POST',
23
+ headers: { [SITE_KEY_HEADER]: options.siteKey },
24
+ });
25
+ const body = await readJson(response);
26
+ if (!response.ok || !body.session)
27
+ throw toError(response, body);
28
+ session = {
29
+ token: body.session.token,
30
+ expiresAt: body.session.expiresAt,
31
+ info: { business: body.business, services: body.services },
32
+ };
33
+ return session;
34
+ }
35
+ async function ensureSession(force = false) {
36
+ if (!force && session && session.expiresAt - REFRESH_MARGIN_MS > Date.now())
37
+ return session;
38
+ if (!pending)
39
+ pending = openSession().finally(() => (pending = null));
40
+ return pending;
41
+ }
42
+ async function request(path, init = {}) {
43
+ const send = async (force) => {
44
+ const { token } = await ensureSession(force);
45
+ const headers = new Headers(init.headers);
46
+ headers.set(SESSION_HEADER, token);
47
+ // JSON bodies only: a FormData upload sets its own multipart boundary.
48
+ if (typeof init.body === 'string')
49
+ headers.set('Content-Type', 'application/json');
50
+ return fetch(`${apiBase}${path}`, { ...init, headers });
51
+ };
52
+ let response = await send(false);
53
+ if (response.status === 401) {
54
+ const body = await readJson(response.clone());
55
+ if (body.code && SESSION_ERRORS.has(body.code))
56
+ response = await send(true);
57
+ }
58
+ const body = await readJson(response);
59
+ if (!response.ok)
60
+ throw toError(response, body);
61
+ return body;
62
+ }
63
+ return {
64
+ apiBase,
65
+ /** Business name + which services are on. Cached for the session. */
66
+ async info() {
67
+ return (await ensureSession()).info;
68
+ },
69
+ chat: {
70
+ send(message) {
71
+ return request('/api/sdk/v1/chat', { method: 'POST', body: JSON.stringify({ message }) });
72
+ },
73
+ /**
74
+ * Sends a document the chat asked for (PDF or photo, up to 10 MB) to the business's Google
75
+ * Drive. `documentId` is the id from `services.chat.documentRequests`, when you know it.
76
+ * Pass the returned `message` to `send()` so the assistant can confirm it arrived.
77
+ */
78
+ attach(file, documentId) {
79
+ const body = new FormData();
80
+ body.append('file', file);
81
+ if (documentId)
82
+ body.append('documentId', documentId);
83
+ return request('/api/sdk/v1/chat/upload', { method: 'POST', body });
84
+ },
85
+ },
86
+ speak: {
87
+ /** LiveKit credentials for a new call. Use with `livekit-client` (the React hook does this for you). */
88
+ connect(participantName) {
89
+ return request('/api/sdk/v1/speak', {
90
+ method: 'POST',
91
+ body: JSON.stringify({ participantName }),
92
+ });
93
+ },
94
+ },
95
+ form: {
96
+ async schema() {
97
+ return (await request('/api/sdk/v1/form')).form;
98
+ },
99
+ async submit(values, consent) {
100
+ const body = await request('/api/sdk/v1/form', {
101
+ method: 'POST',
102
+ body: JSON.stringify({ values, consent }),
103
+ });
104
+ return body.message;
105
+ },
106
+ },
107
+ wizard: {
108
+ async load(slug) {
109
+ return (await request(`/api/sdk/v1/wizards/${encodeURIComponent(slug)}`)).wizard;
110
+ },
111
+ },
112
+ business: {
113
+ async get() {
114
+ return (await request('/api/sdk/v1/business')).business;
115
+ },
116
+ /** The business's own answers to what customers ask most, for an FAQ block. */
117
+ async answers() {
118
+ return (await request('/api/sdk/v1/answers')).answers;
119
+ },
120
+ /** Reviews the business chose to show, newest first. */
121
+ async reviews() {
122
+ return (await request('/api/sdk/v1/reviews')).reviews;
123
+ },
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,7 @@
1
+ export { createSts } from './core.js';
2
+ export type { StsClient } from './core.js';
3
+ export { createWizardPlayer } from './wizardPlayer.js';
4
+ export type { WizardPlayer, WizardPlayerEvents } from './wizardPlayer.js';
5
+ export * from './types.js';
6
+ export { createChat, createForm, createVoice } from './controllers.js';
7
+ export type { StsCaption, StsChatController, StsChatMessage, StsChatState, StsFormController, StsFormState, StsVoiceController, StsVoiceState, } from './controllers.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createSts } from './core.js';
2
+ export { createWizardPlayer } from './wizardPlayer.js';
3
+ export * from './types.js';
4
+ export { createChat, createForm, createVoice } from './controllers.js';