@ownhelp/widget 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/dist/lib/index.js CHANGED
@@ -1,264 +1,279 @@
1
- import { jsxs as p, jsx as s, Fragment as xe } from "react/jsx-runtime";
2
- import { useState as v, useRef as $, useCallback as J, useLayoutEffect as ve, useEffect as Q } from "react";
3
- function ue(e) {
4
- if (typeof e != "string" || e.length > 50) return;
5
- const t = e.trim(), r = /^(\+?[0-9 ().-]+?)(?:\s*[xX#]\s*(\d+))?$/.exec(t);
1
+ import { jsxs as g, jsx as s, Fragment as Pe } from "react/jsx-runtime";
2
+ import { useState as h, useRef as $, useCallback as Z, useLayoutEffect as Ae, useEffect as z } from "react";
3
+ import { createPortal as Re } from "react-dom";
4
+ function xe(t) {
5
+ if (typeof t != "string" || t.length > 50) return;
6
+ const e = t.trim(), r = /^(\+?[0-9 ().-]+?)(?:\s*[xX#]\s*(\d+))?$/.exec(e);
6
7
  if (!r || !/\d/.test(r[1])) return;
7
8
  const n = r[1].replace(/[^+0-9]/g, "");
8
- return { display: t, uri: `tel:${n}${r[2] ? `;ext=${r[2]}` : ""}` };
9
+ return { display: e, uri: `tel:${n}${r[2] ? `;ext=${r[2]}` : ""}` };
9
10
  }
10
- function ee(e) {
11
- if (!e || e.available !== !0 || typeof e.token != "string" || !e.token.trim()) return;
12
- const t = { available: !0, token: e.token };
13
- typeof e.contact_email == "string" && /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(e.contact_email) && (t.contactEmail = e.contact_email);
14
- const r = ue(e.contact_phone);
15
- return r && (t.contactPhone = r.display), t;
11
+ function oe(t) {
12
+ if (!t || t.available !== !0 || typeof t.token != "string" || !t.token.trim()) return;
13
+ const e = { available: !0, token: t.token };
14
+ typeof t.contact_email == "string" && /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(t.contact_email) && (e.contactEmail = t.contact_email);
15
+ const r = xe(t.contact_phone);
16
+ return r && (e.contactPhone = r.display), e;
16
17
  }
17
- function ke(e) {
18
- const t = ee({
18
+ function Le(t) {
19
+ const e = oe({
19
20
  available: !0,
20
- token: e?.token,
21
- contact_email: e?.contactEmail,
22
- contact_phone: e?.contactPhone
21
+ token: t?.token,
22
+ contact_email: t?.contactEmail,
23
+ contact_phone: t?.contactPhone
23
24
  });
24
25
  return {
25
- email: t?.contactEmail ? `mailto:${encodeURIComponent(t.contactEmail)}` : void 0,
26
- phone: ue(t?.contactPhone)?.uri
26
+ email: e?.contactEmail ? `mailto:${encodeURIComponent(e.contactEmail)}` : void 0,
27
+ phone: xe(e?.contactPhone)?.uri
27
28
  };
28
29
  }
29
- function Ce() {
30
- let e = 0;
31
- const t = /* @__PURE__ */ new Set();
30
+ function Oe() {
31
+ let t = 0;
32
+ const e = /* @__PURE__ */ new Set();
32
33
  return {
33
34
  begin() {
34
- const r = e, n = new AbortController();
35
- return t.add(n), {
35
+ const r = t, n = new AbortController();
36
+ return e.add(n), {
36
37
  signal: n.signal,
37
38
  abort: () => n.abort(),
38
- isCurrent: () => r === e,
39
- finish: () => t.delete(n)
39
+ isCurrent: () => r === t,
40
+ finish: () => e.delete(n)
40
41
  };
41
42
  },
42
43
  reset() {
43
- e += 1;
44
- for (const r of t) r.abort();
45
- t.clear();
44
+ t += 1;
45
+ for (const r of e) r.abort();
46
+ e.clear();
46
47
  }
47
48
  };
48
49
  }
49
- function _e(e) {
50
- let t = "", r = "message", n = [];
51
- function c() {
52
- n.length > 0 && e({ event: r, data: n.join(`
50
+ function ze(t) {
51
+ let e = "", r = "message", n = [];
52
+ function i() {
53
+ n.length > 0 && t({ event: r, data: n.join(`
53
54
  `) }), r = "message", n = [];
54
55
  }
55
- function k(l) {
56
- if (l === "") {
57
- c();
56
+ function f(u) {
57
+ if (u === "") {
58
+ i();
58
59
  return;
59
60
  }
60
- if (l.startsWith(":"))
61
+ if (u.startsWith(":"))
61
62
  return;
62
- const i = l.indexOf(":"), a = i === -1 ? l : l.slice(0, i);
63
- let d = i === -1 ? "" : l.slice(i + 1);
63
+ const l = u.indexOf(":"), a = l === -1 ? u : u.slice(0, l);
64
+ let d = l === -1 ? "" : u.slice(l + 1);
64
65
  d.startsWith(" ") && (d = d.slice(1)), a === "event" ? r = d : a === "data" && n.push(d);
65
66
  }
66
67
  return {
67
- push(l) {
68
- t += l;
69
- let i;
70
- for (; (i = t.search(/\r\n|\n|\r/)) !== -1; ) {
71
- const a = t.startsWith(`\r
72
- `, i);
73
- if (!a && t[i] === "\r" && i === t.length - 1)
68
+ push(u) {
69
+ e += u;
70
+ let l;
71
+ for (; (l = e.search(/\r\n|\n|\r/)) !== -1; ) {
72
+ const a = e.startsWith(`\r
73
+ `, l);
74
+ if (!a && e[l] === "\r" && l === e.length - 1)
74
75
  return;
75
- const d = t.slice(0, i);
76
- t = t.slice(i + (a ? 2 : 1)), k(d);
76
+ const d = e.slice(0, l);
77
+ e = e.slice(l + (a ? 2 : 1)), f(d);
77
78
  }
78
79
  },
79
80
  /** Call when the stream ends; dispatches nothing that was not terminated by a blank line. */
80
81
  flush() {
81
- t = "", r = "message", n = [];
82
+ e = "", r = "message", n = [];
82
83
  }
83
84
  };
84
85
  }
85
- class w extends Error {
86
- constructor(t, r, n, c) {
87
- super(r), this.name = "ChatError", this.code = t, this.status = n, this.retryAfterSec = c;
86
+ class b extends Error {
87
+ constructor(e, r, n, i) {
88
+ super(r), this.name = "ChatError", this.code = e, this.status = n, this.retryAfterSec = i;
88
89
  }
89
90
  }
90
- const Se = 3e4;
91
- function de(e) {
92
- return `${String(e).replace(/\/+$/, "")}/api/chat`;
91
+ const Me = 3e4;
92
+ function ae(t) {
93
+ return `${String(t).replace(/\/+$/, "")}/api/chat`;
93
94
  }
94
- async function fe(e) {
95
- let t = `http_${e.status}`, r = `Request failed (${e.status})`;
95
+ async function ye(t) {
96
+ let e = `http_${t.status}`, r = `Request failed (${t.status})`;
96
97
  try {
97
- const c = await e.json();
98
- c && c.error && (t = c.error.code || t, r = c.error.message || r);
98
+ const i = await t.json();
99
+ i && i.error && (e = i.error.code || e, r = i.error.message || r);
99
100
  } catch {
100
101
  }
101
- const n = Number(e.headers && e.headers.get && e.headers.get("retry-after"));
102
- return new w(t, r, e.status, Number.isFinite(n) && n > 0 ? n : void 0);
102
+ const n = Number(t.headers && t.headers.get && t.headers.get("retry-after"));
103
+ return new b(e, r, t.status, Number.isFinite(n) && n > 0 ? n : void 0);
103
104
  }
104
- async function Ee({
105
- apiUrl: e,
106
- tenantId: t,
105
+ async function je({
106
+ apiUrl: t,
107
+ tenantId: e,
107
108
  message: r,
108
109
  sessionId: n,
109
- signal: c,
110
- onToken: k = () => {
110
+ recordingNotice: i = !1,
111
+ signal: f,
112
+ onToken: u = () => {
111
113
  },
112
- idleTimeoutMs: l = Se,
113
- fetchImpl: i = (...a) => fetch(...a)
114
+ idleTimeoutMs: l = Me,
115
+ fetchImpl: a = (...d) => fetch(...d)
114
116
  }) {
115
- const a = new AbortController();
116
- let d = !1, N = null;
117
- const P = () => {
118
- l && (clearTimeout(N), N = setTimeout(() => {
119
- d = !0, a.abort();
117
+ const d = new AbortController();
118
+ let A = !1, T = null;
119
+ const M = () => {
120
+ l && (clearTimeout(T), T = setTimeout(() => {
121
+ A = !0, d.abort();
120
122
  }, l));
121
- }, U = () => a.abort();
122
- if (c) {
123
- if (c.aborted)
124
- throw new w("aborted", "Request cancelled");
125
- c.addEventListener("abort", U, { once: !0 });
123
+ }, R = () => d.abort();
124
+ if (f) {
125
+ if (f.aborted)
126
+ throw new b("aborted", "Request cancelled");
127
+ f.addEventListener("abort", R, { once: !0 });
126
128
  }
127
- const q = (f) => f instanceof w ? f : d ? new w("timeout", "The assistant took too long to respond") : a.signal.aborted ? new w("aborted", "Request cancelled") : new w("network_error", "Could not reach the support service");
129
+ const Q = (p) => p instanceof b ? p : A ? new b("timeout", "The assistant took too long to respond") : d.signal.aborted ? new b("aborted", "Request cancelled") : new b("network_error", "Could not reach the support service");
128
130
  try {
129
- P();
130
- const f = await i(de(e), {
131
+ M();
132
+ const p = await a(ae(t), {
131
133
  method: "POST",
132
134
  headers: {
133
135
  "Content-Type": "application/json",
134
136
  Accept: "text/event-stream, application/json"
135
137
  },
136
138
  body: JSON.stringify({
137
- tenant_id: t,
139
+ tenant_id: e,
138
140
  message: r,
139
- session_id: n
141
+ session_id: n,
142
+ ...i === !0 ? { recording_notice: !0 } : {}
140
143
  }),
141
- signal: a.signal
144
+ signal: d.signal
142
145
  });
143
- if (!f.ok)
144
- throw await fe(f);
145
- if (!(f.headers.get("content-type") || "").includes("text/event-stream") || !f.body) {
146
- const h = await f.json(), b = String(h.answer ?? "");
147
- b && k(b);
148
- const g = ee(h.follow_up);
149
- return { answer: b, sessionId: h.session_id ?? n, ...g ? { followUp: g } : {} };
146
+ if (!p.ok)
147
+ throw await ye(p);
148
+ if (!(p.headers.get("content-type") || "").includes("text/event-stream") || !p.body) {
149
+ const m = await p.json(), x = String(m.answer ?? "");
150
+ x && u(x);
151
+ const y = oe(m.follow_up);
152
+ return { answer: x, sessionId: m.session_id ?? n, ...y ? { followUp: y } : {} };
150
153
  }
151
- let L = "", _ = !1, S, m = null;
152
- const T = _e(({ event: h, data: b }) => {
153
- let g = {};
154
+ let N = "", S = !1, _, C = null;
155
+ const j = ze(({ event: m, data: x }) => {
156
+ let y = {};
154
157
  try {
155
- g = b ? JSON.parse(b) : {};
158
+ y = x ? JSON.parse(x) : {};
156
159
  } catch {
157
160
  return;
158
161
  }
159
- if (h === "token") {
160
- const z = String(g.text ?? "");
161
- L += z, k(z);
162
- } else h === "error" ? m = new w(
163
- g.code || "stream_error",
164
- g.message || "The assistant ran into a problem"
165
- ) : h === "done" && (_ = !0, S = ee(g.follow_up));
166
- }), j = f.body.getReader(), C = new TextDecoder();
162
+ if (m === "token") {
163
+ const L = String(y.text ?? "");
164
+ N += L, u(L);
165
+ } else m === "error" ? C = new b(
166
+ y.code || "stream_error",
167
+ y.message || "The assistant ran into a problem"
168
+ ) : m === "done" && (S = !0, _ = oe(y.follow_up));
169
+ }), k = p.body.getReader(), I = new TextDecoder();
167
170
  for (; ; ) {
168
- const { done: h, value: b } = await j.read();
169
- if (h)
171
+ const { done: m, value: x } = await k.read();
172
+ if (m)
170
173
  break;
171
- if (P(), T.push(C.decode(b, { stream: !0 })), m)
172
- throw await j.cancel().catch(() => {
173
- }), m;
174
- if (_) {
175
- await j.cancel().catch(() => {
174
+ if (M(), j.push(I.decode(x, { stream: !0 })), C)
175
+ throw await k.cancel().catch(() => {
176
+ }), C;
177
+ if (S) {
178
+ await k.cancel().catch(() => {
176
179
  });
177
180
  break;
178
181
  }
179
182
  }
180
- if (T.push(C.decode()), T.flush(), m)
181
- throw m;
182
- if (!_)
183
- throw new w("stream_interrupted", "The response ended unexpectedly");
184
- return { answer: L, sessionId: n, ...S ? { followUp: S } : {} };
185
- } catch (f) {
186
- throw q(f);
183
+ if (j.push(I.decode()), j.flush(), C)
184
+ throw C;
185
+ if (!S)
186
+ throw new b("stream_interrupted", "The response ended unexpectedly");
187
+ return { answer: N, sessionId: n, ..._ ? { followUp: _ } : {} };
188
+ } catch (p) {
189
+ throw Q(p);
187
190
  } finally {
188
- clearTimeout(N), c && c.removeEventListener("abort", U);
191
+ clearTimeout(T), f && f.removeEventListener("abort", R);
189
192
  }
190
193
  }
191
- async function Ne({
192
- apiUrl: e,
193
- tenantId: t,
194
+ async function Ie({ apiUrl: t, tenantId: e, signal: r, fetchImpl: n = (...i) => fetch(...i) }) {
195
+ try {
196
+ const i = await n(`${ae(t)}?tenant_id=${encodeURIComponent(e)}`, {
197
+ method: "GET",
198
+ headers: { Accept: "application/json" },
199
+ signal: r
200
+ });
201
+ return i.ok ? (await i.json())?.record_conversations === !0 : !1;
202
+ } catch {
203
+ return !1;
204
+ }
205
+ }
206
+ async function De({
207
+ apiUrl: t,
208
+ tenantId: e,
194
209
  sessionId: r,
195
210
  followUpToken: n,
196
- name: c,
197
- email: k,
198
- signal: l,
199
- fetchImpl: i = (...a) => fetch(...a)
211
+ name: i,
212
+ email: f,
213
+ signal: u,
214
+ fetchImpl: l = (...a) => fetch(...a)
200
215
  }) {
201
216
  try {
202
- if (l?.aborted) throw new w("aborted", "Request cancelled");
203
- const a = await i(`${de(e)}/contact`, {
217
+ if (u?.aborted) throw new b("aborted", "Request cancelled");
218
+ const a = await l(`${ae(t)}/contact`, {
204
219
  method: "POST",
205
220
  headers: { "Content-Type": "application/json", Accept: "application/json" },
206
221
  body: JSON.stringify({
207
- tenant_id: t,
222
+ tenant_id: e,
208
223
  session_id: r,
209
224
  follow_up_token: n,
210
- name: c.trim(),
211
- email: k.trim()
225
+ name: i.trim(),
226
+ email: f.trim()
212
227
  }),
213
- signal: l
228
+ signal: u
214
229
  });
215
- if (!a.ok) throw await fe(a);
216
- if ((await a.json()).status !== "saved") throw new w("invalid_response", "Could not confirm save");
230
+ if (!a.ok) throw await ye(a);
231
+ if ((await a.json()).status !== "saved") throw new b("invalid_response", "Could not confirm save");
217
232
  return { status: "saved" };
218
233
  } catch (a) {
219
- throw l?.aborted ? new w("aborted", "Request cancelled") : a instanceof w ? a : new w("network_error", "Could not save contact details");
234
+ throw u?.aborted ? new b("aborted", "Request cancelled") : a instanceof b ? a : new b("network_error", "Could not save contact details");
220
235
  }
221
236
  }
222
- const R = /* @__PURE__ */ new Map();
223
- function pe() {
237
+ const P = /* @__PURE__ */ new Map();
238
+ function ve() {
224
239
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `s_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
225
240
  }
226
- function we() {
241
+ function _e() {
227
242
  try {
228
243
  return typeof localStorage < "u" ? localStorage : null;
229
244
  } catch {
230
245
  return null;
231
246
  }
232
247
  }
233
- function ae(e, t = we()) {
234
- const r = `support_widget_session:${e}`;
235
- if (R.has(r)) return R.get(r);
248
+ function fe(t, e = _e()) {
249
+ const r = `support_widget_session:${t}`;
250
+ if (P.has(r)) return P.get(r);
236
251
  try {
237
- const c = t ? t.getItem(r) : null;
238
- if (c)
239
- return R.set(r, c), c;
252
+ const i = e ? e.getItem(r) : null;
253
+ if (i)
254
+ return P.set(r, i), i;
240
255
  } catch {
241
256
  }
242
- if (R.has(r))
243
- return R.get(r);
244
- const n = pe();
245
- R.set(r, n);
257
+ if (P.has(r))
258
+ return P.get(r);
259
+ const n = ve();
260
+ P.set(r, n);
246
261
  try {
247
- t && t.setItem(r, n);
262
+ e && e.setItem(r, n);
248
263
  } catch {
249
264
  }
250
265
  return n;
251
266
  }
252
- function Te(e, t = we()) {
253
- const r = `support_widget_session:${e}`, n = pe();
254
- R.set(r, n);
267
+ function qe(t, e = _e()) {
268
+ const r = `support_widget_session:${t}`, n = ve();
269
+ P.set(r, n);
255
270
  try {
256
- t?.setItem(r, n);
271
+ e?.setItem(r, n);
257
272
  } catch {
258
273
  }
259
274
  return n;
260
275
  }
261
- const me = "The support assistant is temporarily unavailable. Please try again shortly.", se = "Something went wrong. Please try again.", ce = {
276
+ const ke = "The support assistant is temporarily unavailable. Please try again shortly.", he = "Something went wrong. Please try again.", we = {
262
277
  network_error: {
263
278
  message: "We couldn't reach the support service. Please check your connection and try again.",
264
279
  retryable: !0
@@ -270,7 +285,7 @@ const me = "The support assistant is temporarily unavailable. Please try again s
270
285
  },
271
286
  generation_failed: { message: "The assistant ran into a problem. Please try again.", retryable: !0 },
272
287
  stream_error: { message: "The assistant ran into a problem. Please try again.", retryable: !0 },
273
- service_unavailable: { message: me, retryable: !0 },
288
+ service_unavailable: { message: ke, retryable: !0 },
274
289
  message_too_long: {
275
290
  message: "That message is too long. Please shorten it (2000 characters at most) and send it again.",
276
291
  retryable: !1
@@ -279,24 +294,52 @@ const me = "The support assistant is temporarily unavailable. Please try again s
279
294
  unknown_tenant: { message: "The support chat isn't available on this site.", retryable: !1 },
280
295
  origin_not_allowed: { message: "The support chat isn't available on this site.", retryable: !1 }
281
296
  };
282
- function he(e) {
283
- const t = e && e.code;
284
- if (t === "rate_limited") {
285
- const n = Number(e.retryAfterSec);
286
- return { message: `You're sending messages too quickly. Please wait ${Number.isFinite(n) && n > 0 ? n > 90 ? `${Math.ceil(n / 60)} minutes` : `${Math.ceil(n)} seconds` : "a moment"} and try again.`, retryable: !0 };
287
- }
288
- if (t && ce[t])
289
- return ce[t];
290
- const r = Number(e && e.status);
291
- return r >= 500 ? { message: me, retryable: !0 } : r >= 400 ? { message: se, retryable: !1 } : { message: se, retryable: !0 };
292
- }
293
- function $e(e) {
294
- return he(e).message;
295
- }
296
- function Re(e) {
297
- return he(e).retryable;
297
+ function Ce(t) {
298
+ const e = Number(t && t.retryAfterSec);
299
+ return !Number.isFinite(e) || e <= 0 ? "a moment" : e > 90 ? `${Math.ceil(e / 60)} minutes` : `${Math.ceil(e)} seconds`;
300
+ }
301
+ function Se(t) {
302
+ const e = t && t.code;
303
+ if (e === "rate_limited")
304
+ return {
305
+ message: `You're sending messages too quickly. Please wait ${Ce(t)} and try again.`,
306
+ retryable: !0
307
+ };
308
+ if (e && we[e])
309
+ return we[e];
310
+ const r = Number(t && t.status);
311
+ return r >= 500 ? { message: ke, retryable: !0 } : r >= 400 ? { message: he, retryable: !1 } : { message: he, retryable: !0 };
312
+ }
313
+ const Ue = "Your details could not be saved. Please try again or contact the business directly.", J = "contact the business directly", ne = {
314
+ invalid_request: "Please check your name and email address and try again.",
315
+ origin_not_allowed: `Email follow-up isn't available on this site. Please ${J}.`,
316
+ unknown_tenant: `Email follow-up isn't available on this site. Please ${J}.`,
317
+ invalid_follow_up: `This follow-up form has expired. Please send your message again to get a new one, or ${J}.`,
318
+ contact_already_submitted: `Different contact details were already saved for this conversation. Please ${J} to change them.`,
319
+ service_unavailable: "We couldn't save your details right now. Please try again shortly or contact the business directly.",
320
+ network_error: "We couldn't reach the support service. Please check your connection and try again.",
321
+ timeout: "Saving your details took too long. Please try again."
322
+ };
323
+ function We(t) {
324
+ const e = t && t.code === "aborted" ? "timeout" : t && t.code;
325
+ return e === "rate_limited" ? `Too many attempts. Please wait ${Ce(t)} and try again.` : e && Object.hasOwn(ne, e) ? ne[e] : Number(t && t.status) >= 500 ? ne.service_unavailable : Ue;
326
+ }
327
+ function Fe(t) {
328
+ return Se(t).message;
329
+ }
330
+ function Be(t) {
331
+ return Se(t).retryable;
332
+ }
333
+ const Ye = 120, He = 1.01;
334
+ function Ge({ innerHeight: t, vvHeight: e, vvOffsetTop: r, vvScale: n }) {
335
+ return ![t, e, r, n].every((f) => Number.isFinite(f)) || e <= 0 || n > He ? null : {
336
+ top: Math.max(0, Math.round(r)),
337
+ height: Math.round(e),
338
+ keyboardOpen: t - e >= Ye
339
+ };
298
340
  }
299
- const Pe = `
341
+ const Ve = `
342
+ :host { all: initial; }
300
343
  .cw-root {
301
344
  --cw-accent: #1f6feb;
302
345
  --cw-accent-text: #ffffff;
@@ -440,6 +483,7 @@ const Pe = `
440
483
  .cw-contact-form .cw-send { padding: 9px; }
441
484
  .cw-contact-form [role="alert"] { color: var(--cw-error); }
442
485
  .cw-new-chat:focus-visible, .cw-contact-form input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
486
+ .cw-notice { padding: 6px 12px; border-top: 1px solid var(--cw-border); background: var(--cw-surface); font-size: 12px; color: var(--cw-muted); text-align: center; }
443
487
  .cw-form {
444
488
  display: flex;
445
489
  gap: 8px;
@@ -469,127 +513,212 @@ const Pe = `
469
513
  .cw-send:disabled { opacity: 0.5; cursor: not-allowed; }
470
514
  .cw-footer { padding: 0 10px 8px; font-size: 11px; color: var(--cw-muted); text-align: center; }
471
515
 
516
+ /* Phones and short landscape screens: the open panel fills the screen. Its box follows the part of
517
+ the screen the keyboard leaves free (--cw-vv-top / --cw-vv-height, set from the visual viewport
518
+ by ChatWidget; 100dvh is the fallback), so the header and greeting stay visible and the input
519
+ sits just above the keyboard. Everything here lives inside the widget's own shadow root. */
520
+ @media (max-width: 640px), (max-height: 500px) {
521
+ .cw-root { bottom: max(16px, env(safe-area-inset-bottom)); }
522
+ .cw-root.cw-right { right: 16px; }
523
+ .cw-root.cw-left { left: 16px; }
524
+
525
+ .cw-root.cw-open,
526
+ .cw-root.cw-open.cw-right,
527
+ .cw-root.cw-open.cw-left {
528
+ top: var(--cw-vv-top, 0px);
529
+ left: 0;
530
+ right: 0;
531
+ bottom: auto;
532
+ height: var(--cw-vv-height, 100dvh);
533
+ }
534
+ .cw-panel {
535
+ width: 100%;
536
+ max-width: none;
537
+ height: 100%;
538
+ max-height: none;
539
+ border: none;
540
+ border-radius: 0;
541
+ box-shadow: none;
542
+ }
543
+ .cw-header {
544
+ padding: 8px 10px;
545
+ padding-top: max(8px, env(safe-area-inset-top));
546
+ gap: 6px;
547
+ touch-action: none;
548
+ }
549
+ .cw-header > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
550
+ .cw-new-chat { min-height: 40px; padding: 0 12px; font-size: 13px; }
551
+ .cw-close { min-width: 44px; min-height: 44px; font-size: 28px; }
552
+ .cw-messages { padding: 12px; font-size: 15px; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
553
+ .cw-msg { max-width: 90%; padding: 9px 13px; }
554
+ .cw-follow-up p, .cw-contact-form label { font-size: 13px; }
555
+ /* 16px stops iOS Safari from zooming the page when a field is focused. */
556
+ .cw-input { font-size: 16px; padding: 10px 12px; }
557
+ .cw-send { min-width: 64px; min-height: 44px; }
558
+ .cw-form { padding: 8px 10px; }
559
+ .cw-footer { padding-bottom: max(8px, env(safe-area-inset-bottom)); touch-action: none; }
560
+ /* With the keyboard up, drop the footer line and its safe-area padding to keep room for messages. */
561
+ .cw-root.cw-kb .cw-footer { display: none; }
562
+ }
563
+
472
564
  @media (prefers-reduced-motion: reduce) {
473
565
  .cw-typing::after { animation: none; }
474
566
  }
475
- `, ie = 2e3, Ae = 6e3;
476
- let le = 0;
477
- function V() {
478
- return le += 1, `m${le}`;
567
+ `, me = 2e3, Xe = 6e3;
568
+ let ge = 0;
569
+ function K() {
570
+ return ge += 1, `m${ge}`;
571
+ }
572
+ function be() {
573
+ try {
574
+ return !window.matchMedia("(pointer: coarse)").matches;
575
+ } catch {
576
+ return !0;
577
+ }
479
578
  }
480
- function qe({
481
- apiUrl: e,
482
- tenantId: t,
579
+ function Ze({
580
+ apiUrl: t,
581
+ tenantId: e,
483
582
  title: r = "Support",
484
583
  greeting: n = "Hi! How can I help you today?",
485
- position: c = "right",
486
- accentColor: k,
487
- defaultOpen: l = !1,
488
- fetchImpl: i
584
+ position: i = "right",
585
+ accentColor: f,
586
+ defaultOpen: u = !1,
587
+ fetchImpl: l
489
588
  }) {
490
- const [a, d] = v(l), [N, P] = v(""), [U, q] = v(!1), [f, A] = v(!1), [L, _] = v(() => [
491
- { id: V(), role: "assistant", text: n, status: "done" }
492
- ]), S = $(null), m = $(null);
493
- m.current || (m.current = Ce());
494
- const [T, j] = v(() => ae(t)), [C, h] = v(null), [b, g] = v(""), [z, Z] = v(""), [I, D] = v("idle"), [te, F] = v(""), W = $(!1), H = $(!1), re = $(null), Y = $(null), X = $(""), ne = J((o) => {
495
- m.current.reset(), S.current = null, H.current = !1, W.current = !1, X.current = "", j(o ? Te(t) : ae(t)), _([{ id: V(), role: "assistant", text: n, status: "done" }]), P(""), q(!1), A(!1), h(null), g(""), Z(""), D("idle"), F(""), Y.current?.focus();
496
- }, [t, n]);
497
- ve(() => {
498
- ne(!1);
499
- }, [t, e]), Q(() => {
500
- const o = re.current;
589
+ const [a, d] = h(u), [A, T] = h(""), [M, R] = h(!1), [Q, p] = h(!1), [U, N] = h(() => [
590
+ { id: K(), role: "assistant", text: n, status: "done" }
591
+ ]), S = $(null), _ = $(null);
592
+ _.current || (_.current = Oe());
593
+ const [C, j] = h(() => fe(e)), [k, I] = h(null), [m, x] = h(""), [y, L] = h(""), [O, W] = h("idle"), [se, F] = h(""), B = $(!1), Y = $(!1), ie = $(null), H = $(null), ee = $(""), [G, ce] = h(null), [te, le] = h(!1), de = Z((o) => {
594
+ _.current.reset(), S.current = null, Y.current = !1, B.current = !1, ee.current = "", j(o ? qe(e) : fe(e)), N([{ id: K(), role: "assistant", text: n, status: "done" }]), T(""), R(!1), p(!1), I(null), x(""), L(""), W("idle"), F(""), be() && H.current?.focus();
595
+ }, [e, n]);
596
+ Ae(() => {
597
+ de(!1);
598
+ }, [e, t]);
599
+ const ue = !!G?.keyboardOpen;
600
+ z(() => {
601
+ const o = ie.current;
501
602
  o && (o.scrollTop = o.scrollHeight);
502
- }, [L, a]), Q(() => {
503
- a && Y.current && Y.current.focus();
504
- }, [a]), Q(() => () => m.current.reset(), []);
505
- const M = J((o, u) => {
506
- _((x) => x.map((y) => y.id === o ? { ...y, ...u } : y));
507
- }, []), K = J(
603
+ }, [U, a, ue]), z(() => {
604
+ a && H.current && be() && H.current.focus();
605
+ }, [a]), z(() => {
606
+ const o = typeof window < "u" ? window.visualViewport : null;
607
+ if (!a || !o) {
608
+ ce(null);
609
+ return;
610
+ }
611
+ const c = () => ce(
612
+ Ge({
613
+ innerHeight: window.innerHeight,
614
+ vvHeight: o.height,
615
+ vvOffsetTop: o.offsetTop,
616
+ vvScale: o.scale
617
+ })
618
+ );
619
+ return c(), o.addEventListener("resize", c), o.addEventListener("scroll", c), () => {
620
+ o.removeEventListener("resize", c), o.removeEventListener("scroll", c);
621
+ };
622
+ }, [a]), z(() => () => _.current.reset(), []), z(() => {
623
+ if (le(!1), !a) return;
624
+ const o = new AbortController();
625
+ return Ie({ apiUrl: t, tenantId: e, signal: o.signal, fetchImpl: l }).then((c) => {
626
+ o.signal.aborted || le(c);
627
+ }), () => o.abort();
628
+ }, [a, t, e, l]);
629
+ const D = Z((o, c) => {
630
+ N((v) => v.map((w) => w.id === o ? { ...w, ...c } : w));
631
+ }, []), re = Z(
508
632
  async (o) => {
509
- const u = o.trim().slice(0, ie);
510
- if (!u || H.current)
633
+ const c = o.trim().slice(0, me);
634
+ if (!c || Y.current)
511
635
  return;
512
- H.current = !0, X.current = u;
513
- const x = V();
514
- _((E) => [
636
+ Y.current = !0, ee.current = c;
637
+ const v = K();
638
+ N((E) => [
515
639
  ...E,
516
- { id: V(), role: "user", text: u, status: "done" },
517
- { id: x, role: "assistant", text: "", status: "streaming" }
518
- ]), P(""), q(!0);
519
- const y = m.current.begin();
520
- S.current = y;
521
- let O = "";
522
- A(!1);
523
- const oe = setTimeout(() => {
524
- y.isCurrent() && A(!0);
525
- }, Ae);
640
+ { id: K(), role: "user", text: c, status: "done" },
641
+ { id: v, role: "assistant", text: "", status: "streaming" }
642
+ ]), T(""), R(!0);
643
+ const w = _.current.begin();
644
+ S.current = w;
645
+ let q = "";
646
+ p(!1);
647
+ const pe = setTimeout(() => {
648
+ w.isCurrent() && p(!0);
649
+ }, Xe);
526
650
  try {
527
- const E = await Ee({
528
- apiUrl: e,
529
- tenantId: t,
530
- message: u,
531
- sessionId: T,
532
- signal: y.signal,
533
- fetchImpl: i,
534
- onToken: (B) => {
535
- y.isCurrent() && (clearTimeout(oe), A(!1), O += B, M(x, { text: O }));
651
+ const E = await je({
652
+ apiUrl: t,
653
+ tenantId: e,
654
+ message: c,
655
+ sessionId: C,
656
+ // Only true while the recording notice is on screen (see `recording`).
657
+ recordingNotice: te,
658
+ signal: w.signal,
659
+ fetchImpl: l,
660
+ onToken: (X) => {
661
+ w.isCurrent() && (clearTimeout(pe), p(!1), q += X, D(v, { text: q }));
536
662
  }
537
663
  });
538
- if (!y.isCurrent()) return;
539
- M(x, { status: "done" }), E.followUp && (h(E.followUp), F(""));
664
+ if (!w.isCurrent()) return;
665
+ D(v, { status: "done" }), E.followUp && (I(E.followUp), F(""));
540
666
  } catch (E) {
541
- if (!y.isCurrent()) return;
667
+ if (!w.isCurrent()) return;
542
668
  if (E.code === "aborted")
543
- M(x, { status: "done", text: O || "(stopped)" });
669
+ D(v, { status: "done", text: q || "(stopped)" });
544
670
  else {
545
- const B = $e(E);
546
- M(x, {
671
+ const X = Fe(E);
672
+ D(v, {
547
673
  status: "error",
548
- retryable: Re(E),
549
- text: O ? `${O}
674
+ retryable: Be(E),
675
+ text: q ? `${q}
550
676
 
551
- ${B}` : B
677
+ ${X}` : X
552
678
  });
553
679
  }
554
680
  } finally {
555
- clearTimeout(oe), y.finish(), y.isCurrent() && (S.current = null, H.current = !1, A(!1), q(!1));
681
+ clearTimeout(pe), w.finish(), w.isCurrent() && (S.current = null, Y.current = !1, p(!1), R(!1));
556
682
  }
557
683
  },
558
- [e, t, T, i, M]
559
- ), be = J(() => {
560
- const o = X.current;
561
- o && (_((u) => u.slice(0, -2)), K(o));
562
- }, [K]), ge = (o) => {
563
- o.preventDefault(), K(N);
564
- }, ye = async (o) => {
565
- if (o.preventDefault(), !C || W.current || I === "saved") return;
566
- W.current = !0;
567
- const u = m.current.begin();
568
- D("pending"), F("");
569
- const x = setTimeout(() => u.abort(), 3e4);
684
+ [t, e, C, l, D, te]
685
+ ), Ee = Z(() => {
686
+ const o = ee.current;
687
+ o && (N((c) => c.slice(0, -2)), re(o));
688
+ }, [re]), Te = (o) => {
689
+ o.preventDefault(), re(A);
690
+ }, Ne = async (o) => {
691
+ if (o.preventDefault(), !k || B.current || O === "saved") return;
692
+ B.current = !0;
693
+ const c = _.current.begin();
694
+ W("pending"), F("");
695
+ const v = setTimeout(() => c.abort(), 3e4);
570
696
  try {
571
- await Ne({
572
- apiUrl: e,
573
- tenantId: t,
574
- sessionId: T,
575
- followUpToken: C.token,
576
- name: b,
577
- email: z,
578
- signal: u.signal,
579
- fetchImpl: i
580
- }), u.isCurrent() && (D("saved"), g(""), Z(""));
581
- } catch {
582
- u.isCurrent() && (D("error"), F("Your details could not be saved. Please try again or contact the business directly."));
697
+ await De({
698
+ apiUrl: t,
699
+ tenantId: e,
700
+ sessionId: C,
701
+ followUpToken: k.token,
702
+ name: m,
703
+ email: y,
704
+ signal: c.signal,
705
+ fetchImpl: l
706
+ }), c.isCurrent() && (W("saved"), x(""), L(""));
707
+ } catch (w) {
708
+ c.isCurrent() && (W("error"), F(We(w)));
583
709
  } finally {
584
- clearTimeout(x), u.finish(), u.isCurrent() && (W.current = !1);
710
+ clearTimeout(v), c.finish(), c.isCurrent() && (B.current = !1);
585
711
  }
586
- }, G = ke(C);
587
- return /* @__PURE__ */ p("div", { className: `cw-root ${c === "left" ? "cw-left" : "cw-right"}`, style: k ? { "--cw-accent": k } : void 0, children: [
588
- /* @__PURE__ */ s("style", { children: Pe }),
589
- a ? /* @__PURE__ */ p("section", { className: "cw-panel", role: "dialog", "aria-label": r, children: [
590
- /* @__PURE__ */ p("header", { className: "cw-header", children: [
712
+ }, V = Le(k), $e = {
713
+ ...f ? { "--cw-accent": f } : {},
714
+ ...a && G ? { "--cw-vv-top": `${G.top}px`, "--cw-vv-height": `${G.height}px` } : {}
715
+ };
716
+ return /* @__PURE__ */ g("div", { className: `cw-root ${i === "left" ? "cw-left" : "cw-right"}${`${a ? " cw-open" : ""}${a && ue ? " cw-kb" : ""}`}`, style: $e, children: [
717
+ /* @__PURE__ */ s("style", { children: Ve }),
718
+ a ? /* @__PURE__ */ g("section", { className: "cw-panel", role: "dialog", "aria-label": r, children: [
719
+ /* @__PURE__ */ g("header", { className: "cw-header", children: [
591
720
  /* @__PURE__ */ s("span", { children: r }),
592
- /* @__PURE__ */ s("button", { type: "button", className: "cw-new-chat", onClick: () => ne(!0), children: "New chat" }),
721
+ /* @__PURE__ */ s("button", { type: "button", className: "cw-new-chat", onClick: () => de(!0), children: "New chat" }),
593
722
  /* @__PURE__ */ s(
594
723
  "button",
595
724
  {
@@ -601,39 +730,39 @@ ${B}` : B
601
730
  }
602
731
  )
603
732
  ] }),
604
- /* @__PURE__ */ p("div", { className: "cw-messages", ref: re, role: "log", "aria-live": "polite", children: [
605
- L.map((o, u) => {
606
- const x = u === L.length - 1;
607
- return /* @__PURE__ */ p(
733
+ /* @__PURE__ */ g("div", { className: "cw-messages", ref: ie, role: "log", "aria-live": "polite", children: [
734
+ U.map((o, c) => {
735
+ const v = c === U.length - 1;
736
+ return /* @__PURE__ */ g(
608
737
  "div",
609
738
  {
610
739
  className: `cw-msg cw-${o.role}${o.status === "error" ? " cw-error" : ""}`,
611
740
  children: [
612
741
  o.text,
613
- o.status === "streaming" && !o.text ? /* @__PURE__ */ p(xe, { children: [
742
+ o.status === "streaming" && !o.text ? /* @__PURE__ */ g(Pe, { children: [
614
743
  /* @__PURE__ */ s("span", { className: "cw-typing", "aria-label": "Assistant is typing" }),
615
- f ? /* @__PURE__ */ s("span", { className: "cw-slow", children: "Still working on your answer…" }) : null
744
+ Q ? /* @__PURE__ */ s("span", { className: "cw-slow", children: "Still working on your answer…" }) : null
616
745
  ] }) : null,
617
- o.status === "error" && o.retryable !== !1 && x && !U ? /* @__PURE__ */ s("div", { children: /* @__PURE__ */ s("button", { type: "button", className: "cw-retry", onClick: be, children: "Retry" }) }) : null
746
+ o.status === "error" && o.retryable !== !1 && v && !M ? /* @__PURE__ */ s("div", { children: /* @__PURE__ */ s("button", { type: "button", className: "cw-retry", onClick: Ee, children: "Retry" }) }) : null
618
747
  ]
619
748
  },
620
749
  o.id
621
750
  );
622
751
  }),
623
- C ? /* @__PURE__ */ p("section", { className: "cw-follow-up", "aria-label": "Email follow-up", children: [
752
+ k ? /* @__PURE__ */ g("section", { className: "cw-follow-up", "aria-label": "Email follow-up", children: [
624
753
  /* @__PURE__ */ s("strong", { children: "Email follow-up" }),
625
754
  /* @__PURE__ */ s("p", { children: "Email follow-up is not immediate. For time-sensitive help, contact the business directly." }),
626
- G.phone ? /* @__PURE__ */ p("p", { children: [
755
+ V.phone ? /* @__PURE__ */ g("p", { children: [
627
756
  "Call ",
628
- /* @__PURE__ */ s("a", { href: G.phone, target: "_blank", rel: "noopener noreferrer", children: C.contactPhone })
757
+ /* @__PURE__ */ s("a", { href: V.phone, target: "_blank", rel: "noopener noreferrer", children: k.contactPhone })
629
758
  ] }) : null,
630
- G.email ? /* @__PURE__ */ p("p", { children: [
759
+ V.email ? /* @__PURE__ */ g("p", { children: [
631
760
  "Email ",
632
- /* @__PURE__ */ s("a", { href: G.email, target: "_blank", rel: "noopener noreferrer", children: C.contactEmail })
761
+ /* @__PURE__ */ s("a", { href: V.email, target: "_blank", rel: "noopener noreferrer", children: k.contactEmail })
633
762
  ] }) : null,
634
- I === "saved" ? /* @__PURE__ */ s("p", { role: "status", children: "Your details were saved for the team to review and follow up by email." }) : /* @__PURE__ */ p("form", { className: "cw-contact-form", onSubmit: ye, children: [
763
+ O === "saved" ? /* @__PURE__ */ s("p", { role: "status", children: "Your details were saved for the team to review and follow up by email." }) : /* @__PURE__ */ g("form", { className: "cw-contact-form", onSubmit: Ne, children: [
635
764
  /* @__PURE__ */ s("p", { children: "Leave your name and email to request follow-up about this conversation." }),
636
- /* @__PURE__ */ p("label", { children: [
765
+ /* @__PURE__ */ g("label", { children: [
637
766
  "Name",
638
767
  /* @__PURE__ */ s(
639
768
  "input",
@@ -643,13 +772,13 @@ ${B}` : B
643
772
  autoComplete: "name",
644
773
  required: !0,
645
774
  maxLength: 100,
646
- value: b,
647
- disabled: I === "pending",
648
- onChange: (o) => g(o.target.value)
775
+ value: m,
776
+ disabled: O === "pending",
777
+ onChange: (o) => x(o.target.value)
649
778
  }
650
779
  )
651
780
  ] }),
652
- /* @__PURE__ */ p("label", { children: [
781
+ /* @__PURE__ */ g("label", { children: [
653
782
  "Email",
654
783
  /* @__PURE__ */ s(
655
784
  "input",
@@ -660,31 +789,32 @@ ${B}` : B
660
789
  autoComplete: "email",
661
790
  required: !0,
662
791
  maxLength: 254,
663
- value: z,
664
- disabled: I === "pending",
665
- onChange: (o) => Z(o.target.value)
792
+ value: y,
793
+ disabled: O === "pending",
794
+ onChange: (o) => L(o.target.value)
666
795
  }
667
796
  )
668
797
  ] }),
669
- te ? /* @__PURE__ */ s("p", { role: "alert", children: te }) : null,
670
- /* @__PURE__ */ s("button", { className: "cw-send", type: "submit", disabled: I === "pending" || !b.trim() || !z.trim(), children: I === "pending" ? "Saving…" : "Request email follow-up" })
798
+ se ? /* @__PURE__ */ s("p", { role: "alert", children: se }) : null,
799
+ /* @__PURE__ */ s("button", { className: "cw-send", type: "submit", disabled: O === "pending" || !m.trim() || !y.trim(), children: O === "pending" ? "Saving…" : "Request email follow-up" })
671
800
  ] })
672
801
  ] }) : null
673
802
  ] }),
674
- /* @__PURE__ */ p("form", { className: "cw-form", onSubmit: ge, children: [
803
+ te ? /* @__PURE__ */ s("div", { className: "cw-notice", role: "note", children: "This conversation is recorded to improve the assistant." }) : null,
804
+ /* @__PURE__ */ g("form", { className: "cw-form", onSubmit: Te, children: [
675
805
  /* @__PURE__ */ s(
676
806
  "input",
677
807
  {
678
- ref: Y,
808
+ ref: H,
679
809
  className: "cw-input",
680
- value: N,
681
- maxLength: ie,
810
+ value: A,
811
+ maxLength: me,
682
812
  placeholder: "Type your question…",
683
813
  "aria-label": "Your message",
684
- onChange: (o) => P(o.target.value)
814
+ onChange: (o) => T(o.target.value)
685
815
  }
686
816
  ),
687
- U ? /* @__PURE__ */ s(
817
+ M ? /* @__PURE__ */ s(
688
818
  "button",
689
819
  {
690
820
  type: "button",
@@ -692,7 +822,7 @@ ${B}` : B
692
822
  onClick: () => S.current?.abort(),
693
823
  children: "Stop"
694
824
  }
695
- ) : /* @__PURE__ */ s("button", { type: "submit", className: "cw-send", disabled: !N.trim(), children: "Send" })
825
+ ) : /* @__PURE__ */ s("button", { type: "submit", className: "cw-send", disabled: !A.trim(), children: "Send" })
696
826
  ] }),
697
827
  /* @__PURE__ */ s("div", { className: "cw-footer", children: "AI assistant – answers may contain mistakes." })
698
828
  ] }) : /* @__PURE__ */ s(
@@ -707,11 +837,17 @@ ${B}` : B
707
837
  )
708
838
  ] });
709
839
  }
840
+ function rt(t) {
841
+ const [e, r] = h(null), [n, i] = h(null);
842
+ return z(() => {
843
+ e && i(e.shadowRoot || e.attachShadow({ mode: "open" }));
844
+ }, [e]), /* @__PURE__ */ s("div", { ref: r, "data-support-widget": t.tenantId, children: n ? Re(/* @__PURE__ */ s(Ze, { ...t }), n) : null });
845
+ }
710
846
  export {
711
- w as ChatError,
712
- qe as ChatWidget,
713
- ae as getSessionId,
714
- Te as newSessionId,
715
- Ee as streamChat,
716
- Ne as submitContact
847
+ b as ChatError,
848
+ rt as ChatWidget,
849
+ fe as getSessionId,
850
+ qe as newSessionId,
851
+ je as streamChat,
852
+ De as submitContact
717
853
  };