@cosmoops/connect-sdk 0.30.1 → 0.33.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 (36) hide show
  1. package/CHANGELOG.md +267 -0
  2. package/dist/cjs/client/components/visitor-chat.js +387 -0
  3. package/dist/cjs/client/components/visitor-stream.js +124 -0
  4. package/dist/cjs/client/index.js +23 -3
  5. package/dist/cjs/client/provider.js +24 -0
  6. package/dist/cjs/client/use-push.js +139 -0
  7. package/dist/cjs/server/client.js +15 -1
  8. package/dist/cjs/server/handler.js +196 -0
  9. package/dist/cjs/server/resources/ai.js +85 -0
  10. package/dist/cjs/server/resources/enrichment.js +107 -0
  11. package/dist/cjs/server/resources/push.js +92 -0
  12. package/dist/cjs/server/resources/visitor.js +227 -0
  13. package/dist/esm/client/components/visitor-chat.js +384 -0
  14. package/dist/esm/client/components/visitor-stream.js +120 -0
  15. package/dist/esm/client/index.js +17 -1
  16. package/dist/esm/client/provider.js +23 -0
  17. package/dist/esm/client/use-push.js +136 -0
  18. package/dist/esm/server/client.js +15 -1
  19. package/dist/esm/server/handler.js +196 -0
  20. package/dist/esm/server/resources/ai.js +85 -0
  21. package/dist/esm/server/resources/enrichment.js +107 -0
  22. package/dist/esm/server/resources/push.js +88 -0
  23. package/dist/esm/server/resources/visitor.js +222 -0
  24. package/dist/types/client/components/visitor-chat.d.ts +120 -0
  25. package/dist/types/client/components/visitor-stream.d.ts +42 -0
  26. package/dist/types/client/index.d.ts +13 -1
  27. package/dist/types/client/provider.d.ts +21 -0
  28. package/dist/types/client/use-push.d.ts +56 -0
  29. package/dist/types/server/client.d.ts +13 -1
  30. package/dist/types/server/handler.d.ts +0 -24
  31. package/dist/types/server/resources/ai.d.ts +75 -1
  32. package/dist/types/server/resources/enrichment.d.ts +102 -1
  33. package/dist/types/server/resources/push.d.ts +73 -0
  34. package/dist/types/server/resources/visitor.d.ts +200 -0
  35. package/dist/types/types.d.ts +683 -0
  36. package/package.json +3 -2
@@ -0,0 +1,384 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useId, useRef, useState } from "react";
4
+ import { Button, Input, Label, TextField } from "@heroui/react";
5
+ import { CalendarCheck, MessageCircle, Send, X } from "lucide-react";
6
+ import { cn } from "../../cn.js";
7
+ import { useConnectOptional } from "../provider.js";
8
+ import { readVisitorStream, visitorSlotOfferFrom } from "./visitor-stream.js";
9
+ /**
10
+ * The public chat bubble: a visitor with no account asks about your product,
11
+ * books a call, or gets started.
12
+ *
13
+ * ## It runs on pages that have no `ConnectProvider`
14
+ *
15
+ * Deliberately, and it is the main thing separating this component from every
16
+ * other one here. A marketing page usually has no session to hold and nothing
17
+ * on it that needs one, so requiring the provider would mean wrapping a
18
+ * landing page in an auth context to put a chat bubble on it. It reads the
19
+ * context through `useConnectOptional` and uses it only for `basePath` and the
20
+ * injected `fetch`; both have props, and both have defaults.
21
+ *
22
+ * ## Nothing happens until somebody opens it
23
+ *
24
+ * The conversation is minted on first open, never on mount. On a busy marketing
25
+ * site mounting would mean one Firestore write and one wasted session row per
26
+ * *page view*, for a bubble most visitors never touch - and the bubble itself
27
+ * needs no server state to render. The greeting arrives with that first call
28
+ * and is stored copy rather than generated, so opening costs one fast round
29
+ * trip and the visitor is reading real words immediately.
30
+ *
31
+ * ## It is built for a phone first
32
+ *
33
+ * Open, it is a full-height sheet on a narrow viewport and an anchored panel
34
+ * from `sm` up - a marketing chat that covers a desktop browser is harder to
35
+ * use, and one that does not cover a phone has nowhere to put a keyboard.
36
+ * `h-dvh` rather than `h-screen`, so the sheet tracks the visual viewport when
37
+ * the keyboard opens; `env(safe-area-inset-bottom)` on the composer, so the
38
+ * send button is not under a home indicator.
39
+ *
40
+ * The composer's input type is **the server's decision**, not a guess from what
41
+ * the assistant said - see `VisitorField`. That is what puts an `@` on the
42
+ * keyboard when an email is wanted and lets iOS offer a verification code
43
+ * straight from the notification.
44
+ *
45
+ * ## The times are drawn from the tool result, never the prose
46
+ *
47
+ * A turn that looked up availability carries the slots as structured data, and
48
+ * the buttons come from that. So a time the visitor taps is one the server
49
+ * offered, which is the property `/visitor/book` relies on and cannot check for
50
+ * itself.
51
+ *
52
+ * ## Replies render as text, not markdown
53
+ *
54
+ * `<ConnectAskAi>` lazy-loads a markdown renderer because it answers questions
55
+ * about a workspace's documents, where tables and code blocks carry meaning.
56
+ * This answers three-sentence questions about a product on a marketing page.
57
+ * Shipping 462 KB of renderer to a landing page for prose that is deliberately
58
+ * kept to a couple of lines is the wrong trade, so line breaks are preserved
59
+ * and nothing else is parsed.
60
+ */
61
+ export function ConnectVisitorChat({ workspaceId, assistantName, greeting = "Hi - ask me anything, or I can put you in touch with someone.", suggestions = [], bookingEventTypeSlug = null, basePath, page, title = "Chat with us", defaultOpen = false, showWhenSignedIn = false, fetch: fetchProp, }) {
62
+ const connect = useConnectOptional();
63
+ const root = basePath ?? "/api/connect";
64
+ const [isOpen, setIsOpen] = useState(defaultOpen);
65
+ const [session, setSession] = useState(null);
66
+ const [messages, setMessages] = useState([]);
67
+ const [field, setField] = useState("message");
68
+ const [input, setInput] = useState("");
69
+ const [streaming, setStreaming] = useState("");
70
+ const [isBusy, setIsBusy] = useState(false);
71
+ const [error, setError] = useState(null);
72
+ const [offer, setOffer] = useState(null);
73
+ const [chosen, setChosen] = useState(null);
74
+ const [booked, setBooked] = useState(null);
75
+ const [turnsRemaining, setTurnsRemaining] = useState(1);
76
+ const abortRef = useRef(null);
77
+ const bottomRef = useRef(null);
78
+ const headingId = useId();
79
+ /*
80
+ * **Through the provider when there is one, and directly when there is not.**
81
+ *
82
+ * `mutateResource` and `streamResource` already prefix the provider's own
83
+ * `basePath` and go through its injected `fetch` - which is the seam Storybook
84
+ * and the docs site mount this against, so using them is what makes those two
85
+ * work with nothing passed. Without a provider there is no seam to inherit and
86
+ * the `fetch` prop stands in, defaulting to the global.
87
+ *
88
+ * Reaching into the context for `basePath` and `fetch` instead would have
89
+ * meant widening `ConnectContextValue` with two fields nothing else needs, to
90
+ * re-implement two methods it already has.
91
+ */
92
+ const call = useCallback(async (path, body) => {
93
+ if (connect)
94
+ return connect.mutateResource(path, body);
95
+ const response = await (fetchProp ?? globalThis.fetch)(`${root}${path}`, {
96
+ method: "POST",
97
+ credentials: "same-origin",
98
+ headers: { accept: "application/json", "content-type": "application/json" },
99
+ body: JSON.stringify(body),
100
+ });
101
+ const payload = await response.json().catch(() => null);
102
+ if (!response.ok) {
103
+ throw new Error(payload?.error?.message ?? "Something went wrong. Please try again.");
104
+ }
105
+ return payload;
106
+ }, [connect, root, fetchProp]);
107
+ const openStream = useCallback(async (body, signal) => {
108
+ if (connect)
109
+ return connect.streamResource("/visitor/chat", body, { signal });
110
+ const response = await (fetchProp ?? globalThis.fetch)(`${root}/visitor/chat`, {
111
+ method: "POST",
112
+ credentials: "same-origin",
113
+ headers: { accept: "text/event-stream", "content-type": "application/json" },
114
+ body: JSON.stringify(body),
115
+ signal,
116
+ });
117
+ if (!response.ok) {
118
+ const envelope = await response.json().catch(() => null);
119
+ throw new Error(envelope?.error?.message ?? "Something went wrong. Please try again.");
120
+ }
121
+ return response;
122
+ }, [connect, root, fetchProp]);
123
+ /*
124
+ * Minted on first open. `storedSessionId` survives a reload, which is what
125
+ * lets somebody follow a link out of the chat and come back to it - on a
126
+ * phone, the most likely thing they will do.
127
+ */
128
+ useEffect(() => {
129
+ if (!isOpen || session)
130
+ return;
131
+ let cancelled = false;
132
+ void (async () => {
133
+ try {
134
+ const opened = await call("/visitor/session", {
135
+ workspaceId,
136
+ page: page ?? (typeof location !== "undefined" ? location.pathname : null),
137
+ resume: storedSessionId(),
138
+ });
139
+ if (cancelled)
140
+ return;
141
+ rememberSessionId(opened.sessionId);
142
+ setSession(opened);
143
+ setMessages(opened.messages);
144
+ setField(opened.field);
145
+ setTurnsRemaining(opened.turnsRemaining);
146
+ // Already carries its written-out `label`, so a reopened bubble names
147
+ // the time without formatting an instant in the visitor's own zone.
148
+ if (opened.booking)
149
+ setBooked(opened.booking);
150
+ }
151
+ catch (cause) {
152
+ if (!cancelled) {
153
+ setError(cause instanceof Error ? cause.message : "The assistant is unavailable.");
154
+ }
155
+ }
156
+ })();
157
+ return () => {
158
+ cancelled = true;
159
+ };
160
+ }, [isOpen, session, call, page, workspaceId]);
161
+ useEffect(() => {
162
+ bottomRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
163
+ }, [messages, streaming, offer, booked]);
164
+ // A conversation left mid-stream stops costing the application the moment the
165
+ // panel goes away.
166
+ useEffect(() => () => abortRef.current?.abort(), []);
167
+ const send = useCallback(async (text) => {
168
+ if (!session)
169
+ return;
170
+ const controller = new AbortController();
171
+ abortRef.current = controller;
172
+ setError(null);
173
+ setIsBusy(true);
174
+ setOffer(null);
175
+ setMessages((current) => [
176
+ ...current,
177
+ { role: "visitor", text, at: new Date().toISOString() },
178
+ ]);
179
+ let answer = "";
180
+ try {
181
+ const response = await openStream({
182
+ sessionId: session.sessionId,
183
+ workspaceId,
184
+ message: text,
185
+ assistantName: assistantName ?? "",
186
+ bookingEventTypeSlug,
187
+ }, controller.signal);
188
+ await readVisitorStream(response, {
189
+ onDelta: (delta) => {
190
+ answer += delta;
191
+ setStreaming(answer);
192
+ },
193
+ onDone: (done) => {
194
+ setField(done.field);
195
+ setTurnsRemaining(done.turnsRemaining);
196
+ setOffer(visitorSlotOfferFrom(done.toolCalls));
197
+ },
198
+ onError: (message) => setError(message),
199
+ });
200
+ }
201
+ catch (cause) {
202
+ if (!controller.signal.aborted) {
203
+ setError(cause instanceof Error ? cause.message : "Something went wrong.");
204
+ }
205
+ }
206
+ finally {
207
+ if (abortRef.current === controller)
208
+ abortRef.current = null;
209
+ /*
210
+ * The streamed text is committed to the transcript here rather than as
211
+ * it arrives, so there is exactly one copy of the reply on screen at
212
+ * every moment - `streaming` is what is being written, `messages` is
213
+ * what has been said.
214
+ */
215
+ if (answer.trim()) {
216
+ setMessages((current) => [
217
+ ...current,
218
+ { role: "assistant", text: answer.trim(), at: new Date().toISOString() },
219
+ ]);
220
+ }
221
+ setStreaming("");
222
+ setIsBusy(false);
223
+ }
224
+ }, [session, openStream, workspaceId, assistantName, bookingEventTypeSlug]);
225
+ const bookChosenSlot = useCallback(async (details) => {
226
+ if (!session || !chosen)
227
+ return;
228
+ setIsBusy(true);
229
+ setError(null);
230
+ try {
231
+ const appointment = await call("/visitor/book", {
232
+ sessionId: session.sessionId,
233
+ workspaceId,
234
+ eventTypeSlug: bookingEventTypeSlug,
235
+ startAt: chosen.startAt,
236
+ name: details.name,
237
+ phone: details.phone,
238
+ email: details.email || null,
239
+ });
240
+ setBooked(appointment);
241
+ setChosen(null);
242
+ setOffer(null);
243
+ setMessages((current) => [
244
+ ...current,
245
+ {
246
+ role: "assistant",
247
+ text: `You're booked for ${appointment.label}. A confirmation is on its way.`,
248
+ at: new Date().toISOString(),
249
+ },
250
+ ]);
251
+ }
252
+ catch (cause) {
253
+ setError(cause instanceof Error ? cause.message : "That time could not be booked.");
254
+ }
255
+ finally {
256
+ setIsBusy(false);
257
+ }
258
+ }, [session, chosen, call, workspaceId, bookingEventTypeSlug]);
259
+ /*
260
+ * A signed-in member has the application's own surfaces, and `<ConnectAskAi>`
261
+ * occupies this same corner - see `showWhenSignedIn`.
262
+ */
263
+ if (!showWhenSignedIn && connect?.session?.user)
264
+ return null;
265
+ const exhausted = turnsRemaining <= 0;
266
+ const composerDisabled = isBusy || !session || exhausted;
267
+ const handleSubmit = (event) => {
268
+ event.preventDefault();
269
+ const text = input.trim();
270
+ if (!text || composerDisabled)
271
+ return;
272
+ setInput("");
273
+ void send(text);
274
+ };
275
+ return (_jsxs(_Fragment, { children: [!isOpen && (_jsx(Button, { isIconOnly: true, variant: "primary", "aria-label": title, onPress: () => setIsOpen(true),
276
+ /*
277
+ * `size-14` on a phone and `size-12` from `sm` up: 56px is the floor
278
+ * for a one-handed thumb target on a surface where this is the only
279
+ * interactive element floating over the page.
280
+ */
281
+ className: "fixed end-4 bottom-4 z-30 size-14 rounded-full shadow-lg sm:size-12", style: { marginBottom: "env(safe-area-inset-bottom)" }, children: _jsx(MessageCircle, { className: "size-6 sm:size-5" }) })), isOpen && (_jsxs("div", { role: "dialog", "aria-modal": "true", "aria-labelledby": headingId,
282
+ /*
283
+ * A full-height sheet on a phone, an anchored panel from `sm` up.
284
+ * `h-dvh` rather than `h-screen`: `vh` is the *largest* viewport on
285
+ * iOS, so a `h-screen` sheet puts its composer under the keyboard.
286
+ */
287
+ className: cn("fixed inset-0 z-40 flex h-dvh flex-col bg-surface", "sm:inset-auto sm:end-6 sm:bottom-6 sm:h-[min(32rem,calc(100dvh-6rem))] sm:w-[22rem] sm:rounded-2xl sm:border sm:border-border sm:shadow-xl"), children: [_jsxs("div", { className: "flex shrink-0 items-center gap-2 border-b border-border px-4 py-3", children: [_jsx("span", { id: headingId, className: "flex-1 truncate text-sm font-semibold", children: assistantName?.trim() || title }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "Close", onPress: () => setIsOpen(false), children: _jsx(X, { className: "size-4" }) })] }), _jsxs("div", { className: "min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto p-4", children: [session && messages.length === 0 && (_jsx("p", { className: "text-sm text-muted", children: greeting })), messages.map((message, index) => (_jsx(Bubble, { role: message.role, text: message.text }, `${message.at}-${index}`))), streaming && _jsx(Bubble, { role: "assistant", text: streaming }), isBusy && !streaming && !chosen && (_jsx("p", { className: "text-xs text-muted", "aria-live": "polite", children: "Typing..." })), session && messages.length === 0 && suggestions.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-2 pt-1", children: suggestions.map((suggestion) => (_jsx(Button, { size: "sm", variant: "secondary", className: "h-auto min-h-11 whitespace-normal py-2 text-start sm:min-h-9", isDisabled: composerDisabled, onPress: () => void send(suggestion), children: suggestion }, suggestion))) })), offer && !chosen && !booked && (_jsx(SlotPicker, { offer: offer, onChoose: setChosen, isDisabled: isBusy })), chosen && !booked && (_jsx(AttendeeForm, { slotLabel: chosen.label, isBusy: isBusy, onCancel: () => setChosen(null), onSubmit: bookChosenSlot })), booked && (_jsxs("div", { className: "flex items-start gap-2 rounded-lg border border-border bg-accent/5 p-3 text-sm", children: [_jsx(CalendarCheck, { className: "mt-0.5 size-4 shrink-0 text-accent" }), _jsxs("span", { children: ["Booked - ", booked.label] })] })), error && (_jsx("p", { className: "text-xs text-content-danger", role: "alert", children: error })), exhausted && (_jsx("p", { className: "text-xs text-muted", children: "This conversation has reached its limit. Reload the page to start a new one." })), _jsx("div", { ref: bottomRef })] }), _jsxs("form", { onSubmit: handleSubmit, className: "flex shrink-0 gap-2 border-t border-border p-3",
288
+ // So the send button is not under a home indicator.
289
+ style: { paddingBottom: "max(0.75rem, env(safe-area-inset-bottom))" }, children: [_jsxs(TextField, { variant: "secondary", className: "min-w-0 flex-1", children: [_jsx(Label, { className: "sr-only", children: FIELD_LABEL[field] }), _jsx(Input, { ...FIELD_INPUT[field], placeholder: FIELD_LABEL[field], value: input, onChange: (event) => setInput(event.currentTarget.value), disabled: composerDisabled })] }), _jsx(Button, { type: "submit", isIconOnly: true, variant: "primary", "aria-label": "Send", className: "size-11 shrink-0 sm:size-10", isDisabled: composerDisabled || !input.trim(), children: _jsx(Send, { className: "size-4" }) })] })] }))] }));
290
+ }
291
+ function Bubble({ role, text }) {
292
+ const isVisitor = role === "visitor";
293
+ return (_jsx("div", { className: cn("flex", isVisitor ? "justify-end" : "justify-start"), children: _jsx("p", { className: cn(
294
+ // `max-w-[85%]` rather than a fixed width: a one-word reply should not
295
+ // be a full-width slab, and a long one still has to wrap.
296
+ "max-w-[85%] rounded-2xl px-3 py-2 text-sm whitespace-pre-wrap", isVisitor ? "bg-accent text-accent-foreground" : "bg-default"), children: text }) }));
297
+ }
298
+ /**
299
+ * The times, as buttons.
300
+ *
301
+ * Every one of them came from the server in this turn - see
302
+ * `visitorSlotOfferFrom`. `min-h-11` is the 44px touch floor; a row of times is
303
+ * exactly the control people mis-tap when it is sized for a mouse.
304
+ */
305
+ function SlotPicker({ offer, onChoose, isDisabled, }) {
306
+ return (_jsxs("div", { className: "space-y-2 rounded-lg border border-border p-3", children: [_jsxs("p", { className: "text-xs text-muted", children: [offer.eventType, " \u00B7 ", offer.durationMinutes, " min \u00B7 times shown in ", offer.timezone] }), _jsx("div", { className: "flex flex-wrap gap-2", children: offer.slots.map((slot) => (_jsx(Button, { size: "sm", variant: "secondary", className: "min-h-11 sm:min-h-9", isDisabled: isDisabled, onPress: () => onChoose(slot), children: slot.label }, slot.startAt))) })] }));
307
+ }
308
+ /**
309
+ * Name, phone and optionally email, in real fields.
310
+ *
311
+ * The reason the assistant does not ask for these in prose: a phone number
312
+ * typed into a chat composer arrives as whatever the autocorrect did to it,
313
+ * where `type="tel" inputmode="tel" autocomplete="tel"` brings up a keypad and
314
+ * offers the number the browser already has.
315
+ *
316
+ * Phone is required because Connect's booking requires it - a host with no way
317
+ * to reach the attendee has an appointment with a stranger.
318
+ */
319
+ function AttendeeForm({ slotLabel, isBusy, onCancel, onSubmit, }) {
320
+ const [name, setName] = useState("");
321
+ const [phone, setPhone] = useState("");
322
+ const [email, setEmail] = useState("");
323
+ const ready = name.trim().length > 0 && phone.trim().length >= 3;
324
+ return (_jsxs("form", { className: "space-y-2 rounded-lg border border-border p-3", onSubmit: (event) => {
325
+ event.preventDefault();
326
+ if (ready && !isBusy)
327
+ onSubmit({ name: name.trim(), phone: phone.trim(), email: email.trim() });
328
+ }, children: [_jsxs("p", { className: "text-xs text-muted", children: ["Booking ", slotLabel] }), _jsxs(TextField, { variant: "secondary", children: [_jsx(Label, { className: "text-xs", children: "Your name" }), _jsx(Input, { autoComplete: "name", value: name, onChange: (event) => setName(event.currentTarget.value), disabled: isBusy })] }), _jsxs(TextField, { variant: "secondary", children: [_jsx(Label, { className: "text-xs", children: "Phone" }), _jsx(Input, { type: "tel", inputMode: "tel", autoComplete: "tel", value: phone, onChange: (event) => setPhone(event.currentTarget.value), disabled: isBusy })] }), _jsxs(TextField, { variant: "secondary", children: [_jsx(Label, { className: "text-xs", children: "Email (optional)" }), _jsx(Input, { type: "email", inputMode: "email", autoComplete: "email", value: email, onChange: (event) => setEmail(event.currentTarget.value), disabled: isBusy })] }), _jsxs("div", { className: "flex gap-2 pt-1", children: [_jsx(Button, { type: "submit", variant: "primary", className: "min-h-11 flex-1 sm:min-h-9", isDisabled: !ready || isBusy, children: "Confirm" }), _jsx(Button, { type: "button", variant: "tertiary", className: "min-h-11 sm:min-h-9", isDisabled: isBusy, onPress: onCancel, children: "Back" })] })] }));
329
+ }
330
+ /**
331
+ * The composer's label and input attributes, per field Connect asked for.
332
+ *
333
+ * Total `Record`s over `VisitorField`, so a field added to the union fails the
334
+ * build here rather than silently rendering a plain text box - which is the
335
+ * whole failure this mechanism exists to prevent, since a plain text box is
336
+ * exactly what the wrong keyboard looks like.
337
+ */
338
+ const FIELD_LABEL = {
339
+ message: "Type a message...",
340
+ email: "Your email address",
341
+ code: "6-digit code",
342
+ name: "Your full name",
343
+ };
344
+ const FIELD_INPUT = {
345
+ message: {},
346
+ email: { type: "email", inputMode: "email", autoComplete: "email" },
347
+ /*
348
+ * `autocomplete="one-time-code"` is what lets iOS offer the code from the
349
+ * notification without the visitor leaving the chat, and `inputmode="numeric"`
350
+ * brings up a keypad rather than a keyboard.
351
+ */
352
+ code: { inputMode: "numeric", autoComplete: "one-time-code", maxLength: 6 },
353
+ name: { autoComplete: "name" },
354
+ };
355
+ /**
356
+ * The conversation token, in `sessionStorage`.
357
+ *
358
+ * `sessionStorage` rather than a cookie or `localStorage`, and each half of that
359
+ * is deliberate: it survives a reload, which is what makes "follow a link out of
360
+ * the chat and come back" work; it does not travel to another tab or outlive the
361
+ * visit, which is right for a bearer token whose only job is to continue one
362
+ * conversation.
363
+ *
364
+ * Every access is wrapped: storage throws outright in some privacy modes, and a
365
+ * chat bubble that fails to open because a visitor has blocked site data is a
366
+ * worse outcome than one that forgets a conversation.
367
+ */
368
+ const STORAGE_KEY = "connect.visitor.session";
369
+ function storedSessionId() {
370
+ try {
371
+ return sessionStorage.getItem(STORAGE_KEY);
372
+ }
373
+ catch {
374
+ return null;
375
+ }
376
+ }
377
+ function rememberSessionId(id) {
378
+ try {
379
+ sessionStorage.setItem(STORAGE_KEY, id);
380
+ }
381
+ catch {
382
+ /* private mode, or site data blocked - the conversation still works, it just will not resume */
383
+ }
384
+ }
@@ -0,0 +1,120 @@
1
+ export async function readVisitorStream(response, handlers) {
2
+ const body = response.body;
3
+ if (!body)
4
+ throw new Error("The assistant returned no reply.");
5
+ const reader = body.pipeThrough(new TextDecoderStream()).getReader();
6
+ let buffer = "";
7
+ for (;;) {
8
+ const { done, value } = await reader.read();
9
+ if (done)
10
+ break;
11
+ buffer += value;
12
+ /*
13
+ * Frames are separated by a blank line, so everything before the last one is
14
+ * complete and whatever follows waits for the next read. Splitting on single
15
+ * newlines would hand a half-received `data:` line to `JSON.parse`, which on
16
+ * a slow connection is most frames.
17
+ */
18
+ const frames = buffer.split("\n\n");
19
+ buffer = frames.pop() ?? "";
20
+ for (const frame of frames)
21
+ dispatch(frame, handlers);
22
+ }
23
+ // A stream that ends mid-frame has nothing complete left in the buffer; one
24
+ // that ends on a frame boundary with no trailing blank line still has its
25
+ // last frame there, which is the shape a server that closes immediately
26
+ // after `done` produces.
27
+ if (buffer.trim())
28
+ dispatch(buffer, handlers);
29
+ }
30
+ function dispatch(frame, handlers) {
31
+ let event = "";
32
+ let data = "";
33
+ for (const line of frame.split("\n")) {
34
+ if (line.startsWith("event:"))
35
+ event = line.slice(6).trim();
36
+ else if (line.startsWith("data:"))
37
+ data += line.slice(5).trim();
38
+ }
39
+ if (!event || !data)
40
+ return;
41
+ let payload;
42
+ try {
43
+ payload = JSON.parse(data);
44
+ }
45
+ catch {
46
+ /*
47
+ * A frame that cannot be parsed is a frame that cannot be rendered. Dropping
48
+ * it keeps the rest of the reply flowing, which is strictly better than
49
+ * failing a whole turn - already paid for - over one malformed chunk.
50
+ */
51
+ return;
52
+ }
53
+ const record = payload;
54
+ switch (event) {
55
+ case "delta":
56
+ if (typeof record.text === "string")
57
+ handlers.onDelta(record.text);
58
+ return;
59
+ case "done":
60
+ handlers.onDone({
61
+ toolCalls: Array.isArray(record.toolCalls) ? record.toolCalls : [],
62
+ field: record.field === "email" || record.field === "code" || record.field === "name"
63
+ ? record.field
64
+ : "message",
65
+ turnsRemaining: typeof record.turnsRemaining === "number" ? record.turnsRemaining : 0,
66
+ // Defaults to `true` on an older server that does not send it: claiming
67
+ // a reply was ungrounded when it may not have been would put a false
68
+ // gap in somebody's knowledge-base report.
69
+ grounded: record.grounded !== false,
70
+ });
71
+ return;
72
+ case "error":
73
+ handlers.onError(typeof record.message === "string"
74
+ ? record.message
75
+ : "Sorry - something went wrong. Please try again.");
76
+ return;
77
+ default:
78
+ // An event this version does not know about. Ignored rather than treated
79
+ // as an error, so Connect can add one without breaking a pinned SDK.
80
+ return;
81
+ }
82
+ }
83
+ /**
84
+ * The times a turn looked up, lifted out of its tool calls.
85
+ *
86
+ * **This is what the buttons are drawn from, never the assistant's sentence.** A
87
+ * time the visitor taps is then one the server offered, which is what makes it
88
+ * impossible to book an appointment at a time nobody gave - the property
89
+ * `/visitor/book` depends on and cannot check for itself.
90
+ *
91
+ * `null` when the turn looked nothing up, and also when the lookup *refused* -
92
+ * a tool answering `ok: false` is the assistant being told there is nothing
93
+ * available, and it says so in prose. Rendering an empty slot list under that
94
+ * would be a second, emptier way of saying the same thing.
95
+ */
96
+ export function visitorSlotOfferFrom(toolCalls) {
97
+ // The last one wins: a turn that looked twice - a wider window after an empty
98
+ // first answer - should offer what it found, not what it did not.
99
+ for (let index = toolCalls.length - 1; index >= 0; index -= 1) {
100
+ const call = toolCalls[index];
101
+ if (!call || call.name !== "find_slots")
102
+ continue;
103
+ const result = call.result;
104
+ if (!result || result.ok !== true || !Array.isArray(result.slots))
105
+ continue;
106
+ const slots = result.slots
107
+ .map((slot) => slot)
108
+ .filter((slot) => typeof slot.startAt === "string" && typeof slot.label === "string")
109
+ .map((slot) => ({ startAt: slot.startAt, label: slot.label }));
110
+ if (slots.length === 0)
111
+ return null;
112
+ return {
113
+ eventType: typeof result.eventType === "string" ? result.eventType : "Call",
114
+ durationMinutes: typeof result.durationMinutes === "number" ? result.durationMinutes : 30,
115
+ timezone: typeof result.timezone === "string" ? result.timezone : "UTC",
116
+ slots,
117
+ };
118
+ }
119
+ return null;
120
+ }
@@ -11,7 +11,10 @@
11
11
  * whatever theme the host application platform already configured, and one theme
12
12
  * change lands identically in all of them.
13
13
  */
14
- export { ConnectProvider, useConnect, useConnectUser, useConnectWorkspaceType, useConnectAudience, useConnectPlatformAccess, useConnectEntitlements, useConnectPlans, useConnectApps, useConnectCompanyProfile, useConnectAddonUsage, useConnectSessions, useConnectIntegrations, useConnectResource, CONNECT_APP_URL, } from "./provider.js";
14
+ export { ConnectProvider, useConnect,
15
+ // For a component that must render on a page with no provider - see its own
16
+ // note. `<ConnectVisitorChat>` is the case it exists for.
17
+ useConnectOptional, useConnectUser, useConnectWorkspaceType, useConnectAudience, useConnectPlatformAccess, useConnectEntitlements, useConnectPlans, useConnectApps, useConnectCompanyProfile, useConnectAddonUsage, useConnectSessions, useConnectIntegrations, useConnectResource, CONNECT_APP_URL, } from "./provider.js";
15
18
  // Re-exported from the root entry rather than kept there alone: it is a pure
16
19
  // helper, but every caller is UI code, and making a component file reach two
17
20
  // entry points for one function is friction with nothing behind it.
@@ -52,12 +55,25 @@ export { ConnectSidebar, ConnectSidebarHeader, ConnectSidebarBody, ConnectSideba
52
55
  export { ConnectShellProvider, useConnectShell, sidebarRowClass, RAIL_COLLAPSED, RAIL_EXPANDED, } from "./components/shell-context.js";
53
56
  export { ConnectSidebarNav, ConnectSideNav } from "./components/side-nav.js";
54
57
  export { useActivePath } from "./use-active-path.js";
58
+ /**
59
+ * Web Push. The hook owns the browser half - permission, the worker, the
60
+ * subscription - and Connect owns the keys, the devices and the member's
61
+ * preferences. Sending is server-side, through `connect.push.send`.
62
+ */
63
+ export { useConnectPush } from "./use-push.js";
55
64
  // The nav model is plain data and pure functions - a host generating its nav
56
65
  // from its own route table needs the types, and `resolveActivePath` is the
57
66
  // same longest-prefix rule the sidebar highlights with, so a breadcrumb or a
58
67
  // page title derived from it cannot disagree with the rail.
59
68
  export { normalizeNav, flattenNav, normalizePath, resolveActivePath, isNavItemActive, gateExemptPaths, filterNavForAudience, } from "./components/nav.js";
60
69
  export { matchConnectScreen, isLinkableConnectScreen, } from "./components/ai-screens.js";
70
+ /*
71
+ * The public chat bubble. Unlike every other component here it renders for a
72
+ * visitor with **no account**, and works on a page with no `ConnectProvider`
73
+ * at all - which is most marketing pages.
74
+ */
75
+ export { ConnectVisitorChat } from "./components/visitor-chat.js";
76
+ export { readVisitorStream, visitorSlotOfferFrom } from "./components/visitor-stream.js";
61
77
  export { ConnectAppsGrid } from "./components/apps-grid.js";
62
78
  // `AppShell askAi` mounts this; exported for an app that wants the panel
63
79
  // without the frame, or wants it somewhere other than the shell's flex row
@@ -332,6 +332,29 @@ export function useConnect() {
332
332
  }
333
333
  return value;
334
334
  }
335
+ /**
336
+ * The context when there is one, `null` when there is not.
337
+ *
338
+ * **For a component that must work on a page with no provider**, which is a
339
+ * real case rather than defensive coding: `<ConnectVisitorChat>` goes on a
340
+ * public marketing page, and those pages frequently have no `ConnectProvider`
341
+ * anywhere near them - there is no session to hold and nothing on the page that
342
+ * needs one. `useConnect()` throwing is right for every component that reads a
343
+ * session; it is wrong for one whose whole purpose is the visitor who has none.
344
+ *
345
+ * What inheriting the context buys such a component, when it is inside one, is
346
+ * `basePath` and the injected `fetch` - so the same component renders against
347
+ * Storybook's mock bridge and the docs site's canned fetch without either of
348
+ * them having to pass anything.
349
+ *
350
+ * Do not reach for this to make an ordinary component tolerant of a missing
351
+ * provider. A session-reading component that silently renders a signed-out
352
+ * state because somebody forgot to wrap their app is a bug that looks like a
353
+ * product decision.
354
+ */
355
+ export function useConnectOptional() {
356
+ return useContext(ConnectContext);
357
+ }
335
358
  /** The signed-in user, or `null`. Sugar over `useConnect().session`. */
336
359
  export function useConnectUser() {
337
360
  return useConnect().session?.user ?? null;