@xpert-ai/chatkit-ui5 0.1.1 → 0.3.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/dist/chatkit.cjs CHANGED
@@ -1,5 +1,3072 @@
1
1
  "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
6
+ var __typeError = (msg) => {
7
+ throw TypeError(msg);
8
+ };
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
12
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
13
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
14
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
15
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
16
+ var __runInitializers = (array, flags, self, value) => {
17
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
18
+ return value;
19
+ };
20
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
21
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
22
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
23
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
24
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
25
+ return __privateGet(this, extra);
26
+ }, set [name](x) {
27
+ return __privateSet(this, extra, x);
28
+ } }, name));
29
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
30
+ for (var i = decorators.length - 1; i >= 0; i--) {
31
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
32
+ if (k) {
33
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
34
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
35
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
36
+ }
37
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
38
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
39
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
40
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
41
+ }
42
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
43
+ };
44
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
45
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
46
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
47
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
48
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
49
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
50
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
51
+ var _a, _b, _setTrainingOptOut_dec, _hideHistory_dec, _showHistory_dec, _sendCustomAction_dec, _shareThread_dec, _setThreadId_dec, _setComposerValue_dec, _sendUserMessage_dec, _fetchUpdates_dec, _focusComposer_dec, _c, _opts, _frameUrl, _frame, _wrapper, _launcherCloseButton, _launcherOpen, _chatMinimizedToPet, _framePetOptionsOverride, _petClosedByContextMenu, _shadow, _petOverlay, _resolveLoaded, _loaded, _messenger, _ChatKitElementBase_instances, emitAndThrow_fn, setOptionsDataAttributes_fn, getDisplayMode_fn, getConfiguredPetOptions_fn, mergeConfiguredPetPositionDefaults_fn, getOverlayPetOptions_fn, resolvePetAssetUrl_fn, resolveOverlayPetOptions_fn, getFrameOptions_fn, setLauncherOpen_fn, setChatMinimizedToPet_fn, syncPetOverlayOptions_fn, handlePetActivate_fn, handlePetClose_fn, handlePetReply_fn, handlePetThreadSummaryActivate_fn, _handleLauncherClose, getFrameUrl_fn, setFrameUrl_fn, consumeFrameUrl_fn, _handleFrameLoad, _initialized, maybeInit_fn, _init;
2
52
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
53
+ const chatkitTypes = require("@xpert-ai/chatkit-types");
54
+ class EventEmitter {
55
+ constructor() {
56
+ __publicField(this, "callbacks", /* @__PURE__ */ new Map());
57
+ }
58
+ on(event, callback) {
59
+ if (!this.callbacks.has(event)) {
60
+ this.callbacks.set(event, /* @__PURE__ */ new Set());
61
+ }
62
+ this.callbacks.get(event).add(callback);
63
+ }
64
+ emit(event, ...args) {
65
+ var _a2;
66
+ const data = args[0];
67
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.forEach((callback) => callback(data));
68
+ }
69
+ off(event, callback) {
70
+ var _a2;
71
+ if (!callback) {
72
+ this.callbacks.delete(event);
73
+ } else {
74
+ (_a2 = this.callbacks.get(event)) == null ? void 0 : _a2.delete(callback);
75
+ }
76
+ }
77
+ allOff() {
78
+ this.callbacks.clear();
79
+ }
80
+ }
81
+ async function getBytes(stream, onChunk) {
82
+ const reader = stream.getReader();
83
+ let result;
84
+ while (!(result = await reader.read()).done) {
85
+ onChunk(result.value);
86
+ }
87
+ }
88
+ function getLines(onLine) {
89
+ let buffer;
90
+ let position;
91
+ let fieldLength;
92
+ let discardTrailingNewline = false;
93
+ return function onChunk(arr) {
94
+ if (buffer === void 0) {
95
+ buffer = arr;
96
+ position = 0;
97
+ fieldLength = -1;
98
+ } else {
99
+ buffer = concat(buffer, arr);
100
+ }
101
+ const bufLength = buffer.length;
102
+ let lineStart = 0;
103
+ while (position < bufLength) {
104
+ if (discardTrailingNewline) {
105
+ if (buffer[position] === 10) {
106
+ lineStart = ++position;
107
+ }
108
+ discardTrailingNewline = false;
109
+ }
110
+ let lineEnd = -1;
111
+ for (; position < bufLength && lineEnd === -1; ++position) {
112
+ switch (buffer[position]) {
113
+ case 58:
114
+ if (fieldLength === -1) {
115
+ fieldLength = position - lineStart;
116
+ }
117
+ break;
118
+ case 13:
119
+ discardTrailingNewline = true;
120
+ case 10:
121
+ lineEnd = position;
122
+ break;
123
+ }
124
+ }
125
+ if (lineEnd === -1) {
126
+ break;
127
+ }
128
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
129
+ lineStart = position;
130
+ fieldLength = -1;
131
+ }
132
+ if (lineStart === bufLength) {
133
+ buffer = void 0;
134
+ } else if (lineStart !== 0) {
135
+ buffer = buffer.subarray(lineStart);
136
+ position -= lineStart;
137
+ }
138
+ };
139
+ }
140
+ function getMessages(onId, onRetry, onMessage) {
141
+ let message = newMessage();
142
+ const decoder = new TextDecoder();
143
+ return function onLine(line, fieldLength) {
144
+ if (line.length === 0) {
145
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
146
+ message = newMessage();
147
+ } else if (fieldLength > 0) {
148
+ const field = decoder.decode(line.subarray(0, fieldLength));
149
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
150
+ const value = decoder.decode(line.subarray(valueOffset));
151
+ switch (field) {
152
+ case "data":
153
+ message.data = message.data ? message.data + "\n" + value : value;
154
+ break;
155
+ case "event":
156
+ message.event = value;
157
+ break;
158
+ case "id":
159
+ onId(message.id = value);
160
+ break;
161
+ case "retry":
162
+ const retry = parseInt(value, 10);
163
+ if (!isNaN(retry)) {
164
+ onRetry(message.retry = retry);
165
+ }
166
+ break;
167
+ }
168
+ }
169
+ };
170
+ }
171
+ function concat(a, b) {
172
+ const res = new Uint8Array(a.length + b.length);
173
+ res.set(a);
174
+ res.set(b, a.length);
175
+ return res;
176
+ }
177
+ function newMessage() {
178
+ return {
179
+ data: "",
180
+ event: "",
181
+ id: "",
182
+ retry: void 0
183
+ };
184
+ }
185
+ var __rest = function(s, e) {
186
+ var t = {};
187
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
188
+ t[p] = s[p];
189
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
190
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
191
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
192
+ t[p[i]] = s[p[i]];
193
+ }
194
+ return t;
195
+ };
196
+ const EventStreamContentType = "text/event-stream";
197
+ const DefaultRetryInterval = 1e3;
198
+ const LastEventId = "last-event-id";
199
+ function fetchEventSource(input, _a2) {
200
+ var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a2, rest = __rest(_a2, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
201
+ return new Promise((resolve, reject) => {
202
+ const headers = Object.assign({}, inputHeaders);
203
+ if (!headers.accept) {
204
+ headers.accept = EventStreamContentType;
205
+ }
206
+ let curRequestController;
207
+ function onVisibilityChange() {
208
+ curRequestController.abort();
209
+ if (!document.hidden) {
210
+ create();
211
+ }
212
+ }
213
+ if (!openWhenHidden) {
214
+ document.addEventListener("visibilitychange", onVisibilityChange);
215
+ }
216
+ let retryInterval = DefaultRetryInterval;
217
+ let retryTimer = 0;
218
+ function dispose() {
219
+ document.removeEventListener("visibilitychange", onVisibilityChange);
220
+ window.clearTimeout(retryTimer);
221
+ curRequestController.abort();
222
+ }
223
+ inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener("abort", () => {
224
+ dispose();
225
+ resolve();
226
+ });
227
+ const fetch2 = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
228
+ const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
229
+ async function create() {
230
+ var _a3;
231
+ curRequestController = new AbortController();
232
+ try {
233
+ const response = await fetch2(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
234
+ await onopen(response);
235
+ await getBytes(response.body, getLines(getMessages((id) => {
236
+ if (id) {
237
+ headers[LastEventId] = id;
238
+ } else {
239
+ delete headers[LastEventId];
240
+ }
241
+ }, (retry) => {
242
+ retryInterval = retry;
243
+ }, onmessage)));
244
+ onclose === null || onclose === void 0 ? void 0 : onclose();
245
+ dispose();
246
+ resolve();
247
+ } catch (err) {
248
+ if (!curRequestController.signal.aborted) {
249
+ try {
250
+ const interval = (_a3 = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a3 !== void 0 ? _a3 : retryInterval;
251
+ window.clearTimeout(retryTimer);
252
+ retryTimer = window.setTimeout(create, interval);
253
+ } catch (innerErr) {
254
+ dispose();
255
+ reject(innerErr);
256
+ }
257
+ }
258
+ }
259
+ }
260
+ create();
261
+ });
262
+ }
263
+ function defaultOnOpen(response) {
264
+ const contentType = response.headers.get("content-type");
265
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
266
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
267
+ }
268
+ }
269
+ const FRAME_SAFE_ERROR_KEY = "__chatkit_error__";
270
+ class HttpError extends Error {
271
+ constructor(message, res, metadata) {
272
+ super(message);
273
+ __publicField(this, "status");
274
+ __publicField(this, "statusText");
275
+ __publicField(this, "metadata");
276
+ this.name = "HttpError";
277
+ this.statusText = res.statusText;
278
+ this.status = res.status;
279
+ this.metadata = metadata;
280
+ }
281
+ static fromPossibleFrameSafeError(error) {
282
+ if (error instanceof HttpError) {
283
+ return error;
284
+ }
285
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "HttpError") {
286
+ const safeError = error;
287
+ const parsedError = new HttpError(
288
+ safeError.message,
289
+ {
290
+ status: safeError.status,
291
+ statusText: safeError.statusText
292
+ },
293
+ safeError.metadata
294
+ );
295
+ parsedError.stack = safeError.stack;
296
+ return parsedError;
297
+ }
298
+ return null;
299
+ }
300
+ }
301
+ _a = FRAME_SAFE_ERROR_KEY;
302
+ const _FrameSafeHttpError = class _FrameSafeHttpError {
303
+ constructor(message, res, metadata) {
304
+ __publicField(this, _a, "HttpError");
305
+ __publicField(this, "message");
306
+ __publicField(this, "stack");
307
+ __publicField(this, "status");
308
+ __publicField(this, "statusText");
309
+ __publicField(this, "metadata");
310
+ this.message = message;
311
+ this.stack = new Error(message).stack;
312
+ this.status = res.status;
313
+ this.statusText = res.statusText;
314
+ this.metadata = metadata;
315
+ }
316
+ static fromHttpError(error) {
317
+ return new _FrameSafeHttpError(
318
+ error.message,
319
+ {
320
+ status: error.status,
321
+ statusText: error.statusText
322
+ },
323
+ error.metadata
324
+ );
325
+ }
326
+ };
327
+ let FrameSafeHttpError = _FrameSafeHttpError;
328
+ const BASE_RETRY_DELAY_MS = 1e3;
329
+ const MAX_RETRY_DELAY_MS = 1e4;
330
+ const MAX_RETRY_ATTEMPTS = 5;
331
+ const nextDelay = (attempt, maxRetryDelay = MAX_RETRY_DELAY_MS, baseDelayMs = BASE_RETRY_DELAY_MS) => {
332
+ const max = Math.min(maxRetryDelay, baseDelayMs * 2 ** attempt);
333
+ return Math.floor(max * (0.5 + Math.random() * 0.5));
334
+ };
335
+ class RetryableError extends Error {
336
+ constructor(cause) {
337
+ super();
338
+ this.cause = cause;
339
+ }
340
+ }
341
+ const fetchEventSourceWithRetry = async (url, params) => {
342
+ let retryAttempt = 0;
343
+ const { onopen, ...restParams } = params;
344
+ await fetchEventSource(url, {
345
+ ...restParams,
346
+ onopen: async (res) => {
347
+ var _a2;
348
+ onopen == null ? void 0 : onopen(res);
349
+ if (res.ok && ((_a2 = res.headers.get("content-type")) == null ? void 0 : _a2.startsWith("text/event-stream"))) {
350
+ retryAttempt = 0;
351
+ return;
352
+ }
353
+ const httpError = new FrameSafeHttpError(`Streaming failed: ${res.statusText}`, res);
354
+ if (res.status >= 400 && res.status < 500) {
355
+ throw httpError;
356
+ } else {
357
+ throw new RetryableError(httpError);
358
+ }
359
+ },
360
+ onerror: (error) => {
361
+ if (error instanceof RetryableError) {
362
+ if (retryAttempt >= MAX_RETRY_ATTEMPTS) {
363
+ throw error.cause;
364
+ }
365
+ retryAttempt += 1;
366
+ return nextDelay(retryAttempt);
367
+ }
368
+ throw error;
369
+ }
370
+ });
371
+ };
372
+ function safeRandomUUID() {
373
+ const cryptoRef = globalThis.crypto;
374
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.randomUUID) === "function") {
375
+ return cryptoRef.randomUUID();
376
+ }
377
+ if (typeof (cryptoRef == null ? void 0 : cryptoRef.getRandomValues) === "function") {
378
+ const bytes = new Uint8Array(16);
379
+ cryptoRef.getRandomValues(bytes);
380
+ bytes[6] = bytes[6] & 15 | 64;
381
+ bytes[8] = bytes[8] & 63 | 128;
382
+ return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
383
+ }
384
+ return `ck_${Date.now()}_${Math.random().toString(16).slice(2)}`;
385
+ }
386
+ let IntegrationError$1 = class IntegrationError extends Error {
387
+ constructor(message) {
388
+ super(message);
389
+ __publicField(this, "_name");
390
+ this.name = "IntegrationError";
391
+ this._name = this.name;
392
+ }
393
+ static fromPossibleFrameSafeError(error) {
394
+ if (error && typeof error === "object" && FRAME_SAFE_ERROR_KEY in error && error[FRAME_SAFE_ERROR_KEY] === "IntegrationError") {
395
+ const safeError = error;
396
+ const parsedError = new IntegrationError(safeError.message);
397
+ parsedError.stack = safeError.stack;
398
+ return parsedError;
399
+ }
400
+ return null;
401
+ }
402
+ };
403
+ _b = FRAME_SAFE_ERROR_KEY;
404
+ class FrameSafeIntegrationError {
405
+ constructor(message) {
406
+ __publicField(this, _b, "IntegrationError");
407
+ __publicField(this, "message");
408
+ __publicField(this, "stack");
409
+ this.message = message;
410
+ this.stack = new Error(message).stack;
411
+ }
412
+ }
413
+ class BaseMessenger {
414
+ constructor({
415
+ handlers,
416
+ target,
417
+ targetOrigin,
418
+ fetch: fetch2 = window.fetch
419
+ }) {
420
+ __publicField(this, "targetOrigin");
421
+ __publicField(this, "target");
422
+ __publicField(this, "commandHandlers");
423
+ __publicField(this, "_fetch");
424
+ __publicField(this, "emitter", new EventEmitter());
425
+ __publicField(this, "handlers", /* @__PURE__ */ new Map());
426
+ __publicField(this, "fetchEventSourceHandlers", /* @__PURE__ */ new Map());
427
+ __publicField(this, "abortControllers", /* @__PURE__ */ new Map());
428
+ __publicField(this, "commands", new Proxy(
429
+ {},
430
+ {
431
+ get: (_, command) => {
432
+ return (data, transfer) => {
433
+ return new Promise((resolve, reject) => {
434
+ const nonce = safeRandomUUID();
435
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
436
+ this.sendMessage(
437
+ {
438
+ type: "command",
439
+ nonce,
440
+ command: `on${command.charAt(0).toUpperCase()}${command.slice(1)}`,
441
+ data
442
+ },
443
+ transfer
444
+ );
445
+ });
446
+ };
447
+ }
448
+ }
449
+ ));
450
+ __publicField(this, "handleMessage", async (event) => {
451
+ var _a2, _b2, _c2, _d;
452
+ if (!event.data || event.data.__xpaiChatKit !== true || event.origin !== this.targetOrigin || event.source !== this.target()) {
453
+ return;
454
+ }
455
+ const data = event.data;
456
+ switch (data.type) {
457
+ case "event": {
458
+ this.emitter.emit(data.event, data.data);
459
+ break;
460
+ }
461
+ case "fetch": {
462
+ try {
463
+ if (data.formData) {
464
+ const formData = new FormData();
465
+ for (const [key, value] of Object.entries(data.formData)) {
466
+ formData.append(key, value);
467
+ }
468
+ data.params.body = formData;
469
+ }
470
+ const controller = new AbortController();
471
+ this.abortControllers.set(data.nonce, controller);
472
+ data.params.signal = controller.signal;
473
+ const res = await this._fetch(data.url, data.params);
474
+ if (!res.ok) {
475
+ const message = await res.json().then((json2) => json2.message || res.statusText).catch(() => res.statusText);
476
+ throw new FrameSafeHttpError(message, res);
477
+ }
478
+ const json = await res.json().catch(() => ({}));
479
+ this.sendMessage({
480
+ type: "response",
481
+ response: json,
482
+ nonce: data.nonce
483
+ });
484
+ } catch (error) {
485
+ this.sendMessage({
486
+ type: "response",
487
+ error,
488
+ nonce: data.nonce
489
+ });
490
+ }
491
+ break;
492
+ }
493
+ case "fetchEventSource": {
494
+ try {
495
+ const controller = new AbortController();
496
+ this.abortControllers.set(data.nonce, controller);
497
+ await fetchEventSourceWithRetry(data.url, {
498
+ ...data.params,
499
+ signal: controller.signal,
500
+ fetch: this._fetch,
501
+ onmessage: (message) => {
502
+ this.sendMessage({
503
+ type: "fetchEventSourceMessage",
504
+ message,
505
+ nonce: data.nonce
506
+ });
507
+ }
508
+ });
509
+ this.sendMessage({
510
+ type: "response",
511
+ response: void 0,
512
+ nonce: data.nonce
513
+ });
514
+ } catch (error) {
515
+ this.sendMessage({
516
+ type: "response",
517
+ error,
518
+ nonce: data.nonce
519
+ });
520
+ }
521
+ break;
522
+ }
523
+ case "command": {
524
+ if (!this.canReceiveCommand(data.command)) {
525
+ this.sendMessage({
526
+ type: "response",
527
+ error: new FrameSafeIntegrationError(`Command ${data.command} not supported`),
528
+ nonce: data.nonce
529
+ });
530
+ return;
531
+ }
532
+ try {
533
+ const response = await ((_b2 = (_a2 = this.commandHandlers)[data.command]) == null ? void 0 : _b2.call(_a2, data.data));
534
+ this.sendMessage({
535
+ type: "response",
536
+ response,
537
+ nonce: data.nonce
538
+ });
539
+ } catch (error) {
540
+ this.sendMessage({
541
+ type: "response",
542
+ error,
543
+ nonce: data.nonce
544
+ });
545
+ }
546
+ break;
547
+ }
548
+ case "response": {
549
+ const handler = this.handlers.get(data.nonce);
550
+ if (!handler) {
551
+ console.error("No handler found for nonce", data.nonce);
552
+ return;
553
+ }
554
+ if (data.error) {
555
+ const integrationError = IntegrationError$1.fromPossibleFrameSafeError(data.error);
556
+ const httpError = HttpError.fromPossibleFrameSafeError(data.error);
557
+ if (integrationError) {
558
+ integrationError.stack = handler.stack;
559
+ handler.reject(integrationError);
560
+ } else if (httpError) {
561
+ handler.reject(httpError);
562
+ } else {
563
+ handler.reject(data.error);
564
+ }
565
+ } else {
566
+ handler.resolve(data.response);
567
+ }
568
+ this.handlers.delete(data.nonce);
569
+ break;
570
+ }
571
+ case "fetchEventSourceMessage": {
572
+ const handler = this.fetchEventSourceHandlers.get(data.nonce);
573
+ if (!handler) {
574
+ console.error("No handler found for nonce", data.nonce);
575
+ return;
576
+ }
577
+ (_d = (_c2 = this.fetchEventSourceHandlers.get(data.nonce)) == null ? void 0 : _c2.onmessage) == null ? void 0 : _d.call(_c2, data.message);
578
+ break;
579
+ }
580
+ case "abortSignal": {
581
+ const controller = this.abortControllers.get(data.nonce);
582
+ if (controller) {
583
+ controller.abort(data.reason);
584
+ this.abortControllers.delete(data.nonce);
585
+ }
586
+ break;
587
+ }
588
+ }
589
+ });
590
+ this.commandHandlers = handlers;
591
+ this.target = target;
592
+ this.targetOrigin = targetOrigin;
593
+ this._fetch = (...args) => fetch2(...args);
594
+ }
595
+ setTargetOrigin(targetOrigin) {
596
+ this.targetOrigin = targetOrigin;
597
+ }
598
+ sendMessage(data, transfer) {
599
+ var _a2;
600
+ const message = {
601
+ __xpaiChatKit: true,
602
+ ...data
603
+ };
604
+ (_a2 = this.target()) == null ? void 0 : _a2.postMessage(message, this.targetOrigin, transfer);
605
+ }
606
+ connect() {
607
+ window.addEventListener("message", this.handleMessage);
608
+ }
609
+ disconnect() {
610
+ window.removeEventListener("message", this.handleMessage);
611
+ }
612
+ fetch(url, params) {
613
+ return new Promise((resolve, reject) => {
614
+ const nonce = safeRandomUUID();
615
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
616
+ let formData;
617
+ if (params.body instanceof FormData) {
618
+ formData = {};
619
+ for (const [key, value] of params.body.entries()) {
620
+ formData[key] = value;
621
+ }
622
+ params.body = void 0;
623
+ }
624
+ if (params.signal) {
625
+ params.signal.addEventListener("abort", () => {
626
+ var _a2;
627
+ this.sendMessage({
628
+ type: "abortSignal",
629
+ nonce,
630
+ reason: (_a2 = params.signal) == null ? void 0 : _a2.reason
631
+ });
632
+ });
633
+ params.signal = void 0;
634
+ }
635
+ this.sendMessage({ type: "fetch", nonce, params, formData, url });
636
+ });
637
+ }
638
+ // Supporting onopen would require a good way for us to serialize the Response object
639
+ // across the iframe boundary, which is not trivial and also not really necessary.
640
+ fetchEventSource(url, params) {
641
+ return new Promise((resolve, reject) => {
642
+ const { onmessage, signal, ...rest } = params;
643
+ const nonce = safeRandomUUID();
644
+ this.handlers.set(nonce, { resolve, reject, stack: new Error().stack || "" });
645
+ this.fetchEventSourceHandlers.set(nonce, {
646
+ onmessage
647
+ });
648
+ if (signal) {
649
+ signal.addEventListener("abort", () => {
650
+ this.sendMessage({
651
+ type: "abortSignal",
652
+ nonce,
653
+ reason: signal.reason
654
+ });
655
+ });
656
+ }
657
+ this.sendMessage({ type: "fetchEventSource", nonce, params: rest, url });
658
+ });
659
+ }
660
+ emit(...[event, data, transfer]) {
661
+ this.sendMessage(
662
+ {
663
+ type: "event",
664
+ event,
665
+ data
666
+ },
667
+ transfer
668
+ );
669
+ }
670
+ on(...[event, callback]) {
671
+ this.emitter.on(event, callback);
672
+ }
673
+ destroy() {
674
+ window.removeEventListener("message", this.handleMessage);
675
+ this.emitter.allOff();
676
+ this.handlers.clear();
677
+ }
678
+ }
679
+ const toUrlBase64 = (bin) => btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
680
+ const encodeBase64 = (value) => {
681
+ if (value === void 0) {
682
+ throw new TypeError(
683
+ "encodeBase64: `undefined` cannot be encoded to valid JSON. Pass null instead."
684
+ );
685
+ }
686
+ const json = JSON.stringify(value);
687
+ const bytes = new TextEncoder().encode(json);
688
+ let bin = "";
689
+ for (const b of bytes) bin += String.fromCharCode(b);
690
+ return toUrlBase64(bin);
691
+ };
692
+ class IntegrationError2 extends Error {
693
+ }
694
+ function fromPossibleFrameSafeError(err) {
695
+ return err.message;
696
+ }
697
+ const BASE_CAPABILITY_ALLOWLIST = [
698
+ // commands
699
+ "command.setOptions",
700
+ "command.sendUserMessage",
701
+ "command.setComposerValue",
702
+ "command.setThreadId",
703
+ "command.focusComposer",
704
+ "command.fetchUpdates",
705
+ "command.sendCustomAction",
706
+ "command.showHistory",
707
+ "command.hideHistory",
708
+ // events
709
+ "event.ready",
710
+ "event.error",
711
+ "event.log",
712
+ "event.response.start",
713
+ "event.response.end",
714
+ "event.response.stop",
715
+ "event.thread.change",
716
+ "event.tool.change",
717
+ "event.thread.load.start",
718
+ "event.thread.load.end",
719
+ "event.deeplink",
720
+ "event.effect",
721
+ // errors
722
+ "error.StreamError",
723
+ "error.StreamEventParsingError",
724
+ "error.WidgetItemError",
725
+ "error.InitialThreadLoadError",
726
+ "error.FileAttachmentError",
727
+ "error.HistoryViewError",
728
+ "error.FatalAppError",
729
+ "error.IntegrationError",
730
+ "error.EntitySearchError",
731
+ "error.DomainVerificationRequestError",
732
+ // backend
733
+ "backend.threads.get_by_id",
734
+ "backend.threads.list",
735
+ "backend.threads.update",
736
+ "backend.threads.delete",
737
+ "backend.threads.create",
738
+ "backend.threads.add_user_message",
739
+ "backend.threads.add_client_tool_output",
740
+ "backend.threads.retry_after_item",
741
+ "backend.threads.custom_action",
742
+ "backend.attachments.create",
743
+ "backend.attachments.get_preview",
744
+ "backend.attachments.delete",
745
+ "backend.items.list",
746
+ "backend.items.feedback",
747
+ // thread item types
748
+ "thread.item.generated_image",
749
+ "thread.item.user_message",
750
+ "thread.item.assistant_message",
751
+ "thread.item.client_tool_call",
752
+ "thread.item.widget",
753
+ "thread.item.task",
754
+ "thread.item.workflow",
755
+ "thread.item.end_of_turn",
756
+ "thread.item.image_generation",
757
+ // widgets
758
+ "widget.Basic",
759
+ "widget.Card",
760
+ "widget.ListView",
761
+ "widget.ListViewItem",
762
+ "widget.Badge",
763
+ "widget.Box",
764
+ "widget.Row",
765
+ "widget.Col",
766
+ "widget.Button",
767
+ "widget.Caption",
768
+ "widget.Chart",
769
+ "widget.Checkbox",
770
+ "widget.DatePicker",
771
+ "widget.Divider",
772
+ "widget.Form",
773
+ "widget.Icon",
774
+ "widget.Image",
775
+ "widget.Input",
776
+ "widget.Label",
777
+ "widget.Markdown",
778
+ "widget.RadioGroup",
779
+ "widget.Select",
780
+ "widget.Spacer",
781
+ "widget.Text",
782
+ "widget.Textarea",
783
+ "widget.Title",
784
+ "widget.Transition"
785
+ ];
786
+ const BASE_CAPABILITY_DENYLIST = [
787
+ // --- commands
788
+ "command.shareThread",
789
+ "command.setTrainingOptOut",
790
+ // --- events
791
+ "event.thread.restore",
792
+ "event.message.share",
793
+ "event.image.download",
794
+ "event.history.open",
795
+ "event.history.close",
796
+ "event.log.chatgpt",
797
+ // --- errors
798
+ // These errors considered internal and are not exposed to the user by default.
799
+ "error.HttpError",
800
+ "error.NetworkError",
801
+ "error.UnhandledError",
802
+ "error.UnhandledPromiseRejectionError",
803
+ "error.StreamEventHandlingError",
804
+ "error.StreamStopError",
805
+ "error.ThreadRenderingError",
806
+ "error.IntlError",
807
+ "error.AppError",
808
+ // --- backend
809
+ "backend.threads.stop",
810
+ "backend.threads.share",
811
+ "backend.threads.create_from_shared",
812
+ "backend.threads.init",
813
+ "backend.attachments.process",
814
+ // widgets
815
+ "widget.CardCarousel",
816
+ "widget.Favicon",
817
+ "widget.CardLinkItem",
818
+ "widget.Map"
819
+ ];
820
+ const PROFILE_TO_RULES = {
821
+ "chatkit": {
822
+ allow: [...BASE_CAPABILITY_ALLOWLIST, "thread.item.image_generation"],
823
+ deny: BASE_CAPABILITY_DENYLIST
824
+ }
825
+ };
826
+ const getCapabilities = (profile) => {
827
+ const rules = PROFILE_TO_RULES[profile];
828
+ const effective = new Set(rules.allow);
829
+ for (const capability of rules.deny ?? []) {
830
+ effective.delete(capability);
831
+ }
832
+ const commands = /* @__PURE__ */ new Set();
833
+ const events = /* @__PURE__ */ new Set();
834
+ const backend = /* @__PURE__ */ new Set();
835
+ const threadItems = /* @__PURE__ */ new Set();
836
+ const errors = /* @__PURE__ */ new Set();
837
+ const widgets = /* @__PURE__ */ new Set();
838
+ for (const capability of effective) {
839
+ if (capability.startsWith("command.")) {
840
+ commands.add(capability.slice("command.".length));
841
+ continue;
842
+ }
843
+ if (capability.startsWith("event.")) {
844
+ events.add(capability.slice("event.".length));
845
+ continue;
846
+ }
847
+ if (capability.startsWith("backend.")) {
848
+ backend.add(capability.slice("backend.".length));
849
+ continue;
850
+ }
851
+ if (capability.startsWith("thread.item.")) {
852
+ threadItems.add(capability.slice("thread.item.".length));
853
+ }
854
+ if (capability.startsWith("error.")) {
855
+ errors.add(capability.slice("error.".length));
856
+ continue;
857
+ }
858
+ if (capability.startsWith("widget.")) {
859
+ widgets.add(capability.slice("widget.".length));
860
+ continue;
861
+ }
862
+ }
863
+ return { commands, events, backend, threadItems, errors, widgets };
864
+ };
865
+ class ChatFrameMessenger extends BaseMessenger {
866
+ // Messenger running in outer can always handle commands coming from inner
867
+ canReceiveCommand(_) {
868
+ return true;
869
+ }
870
+ }
871
+ const removeMethods = (obj, seen = /* @__PURE__ */ new WeakSet()) => {
872
+ if (typeof obj === "function") return "[ChatKitMethod]";
873
+ if (typeof obj !== "object" || obj === null) return obj;
874
+ if (seen.has(obj)) return obj;
875
+ seen.add(obj);
876
+ if (Array.isArray(obj)) {
877
+ return obj.map((c) => removeMethods(c, seen));
878
+ }
879
+ const result = {};
880
+ for (const [key, value] of Object.entries(obj)) {
881
+ if (typeof value !== "function") {
882
+ result[key] = removeMethods(value, seen);
883
+ } else {
884
+ result[key] = "[ChatKitMethod]";
885
+ }
886
+ }
887
+ return result;
888
+ };
889
+ const DRAG_DIRECTION_THRESHOLD_PX = 2;
890
+ const PET_BASE_RENDER_SCALE = 0.5;
891
+ const PET_FRAME_DURATION_MULTIPLIER = 1.5;
892
+ const PET_RESTING_FRAME_DURATION_MULTIPLIER = 3;
893
+ const PET_RESTING_DELAY_MS = 2e3;
894
+ const PET_SUMMARY_GAP = 12;
895
+ const PET_SUMMARY_WIDTH = 320;
896
+ const PET_SUMMARY_MARGIN = 12;
897
+ const PET_CONTEXT_MENU_MARGIN = 8;
898
+ const PET_SUMMARY_FONT_FAMILY = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
899
+ const PET_OVERLAY_COPY = {
900
+ "en-US": {
901
+ closePetMenuItem: "Close pet",
902
+ hideMessage: "Hide message",
903
+ expandMessage: "Expand message",
904
+ collapseMessage: "Collapse message",
905
+ restoreMessage: "Show message",
906
+ replyButton: "Reply",
907
+ replyPlaceholder: "Reply...",
908
+ sendButton: "Send",
909
+ sendingButton: "Sending...",
910
+ sendFailed: "Failed to send"
911
+ },
912
+ "zh-CN": {
913
+ closePetMenuItem: "关闭宠物",
914
+ hideMessage: "隐藏消息",
915
+ expandMessage: "展开消息",
916
+ collapseMessage: "收起消息",
917
+ restoreMessage: "显示消息",
918
+ replyButton: "回复",
919
+ replyPlaceholder: "输入回复...",
920
+ sendButton: "发送",
921
+ sendingButton: "发送中...",
922
+ sendFailed: "发送失败"
923
+ }
924
+ };
925
+ function stopEventPropagation(event) {
926
+ event.stopPropagation();
927
+ }
928
+ function getViewportSize() {
929
+ const visualViewport = window.visualViewport;
930
+ return {
931
+ width: (visualViewport == null ? void 0 : visualViewport.width) || window.innerWidth || 320,
932
+ height: (visualViewport == null ? void 0 : visualViewport.height) || window.innerHeight || 480
933
+ };
934
+ }
935
+ function readPersistedPosition(storageKey, persist) {
936
+ if (!persist) {
937
+ return null;
938
+ }
939
+ try {
940
+ const raw = window.localStorage.getItem(storageKey);
941
+ if (!raw) {
942
+ return null;
943
+ }
944
+ const parsed = JSON.parse(raw);
945
+ if (!parsed || typeof parsed !== "object" || typeof parsed.x !== "number" || typeof parsed.y !== "number") {
946
+ return null;
947
+ }
948
+ return { x: parsed.x, y: parsed.y };
949
+ } catch {
950
+ return null;
951
+ }
952
+ }
953
+ function writePersistedPosition(storageKey, persist, position) {
954
+ if (!persist) {
955
+ return;
956
+ }
957
+ try {
958
+ window.localStorage.setItem(storageKey, JSON.stringify(position));
959
+ } catch {
960
+ }
961
+ }
962
+ function escapeCssUrl(value) {
963
+ return value.replace(/["\\]/g, "\\$&");
964
+ }
965
+ function getRenderScale(scale) {
966
+ return Math.max(0.1, scale) * PET_BASE_RENDER_SCALE;
967
+ }
968
+ function clampNumber(value, min, max) {
969
+ return Math.min(max, Math.max(min, value));
970
+ }
971
+ function getDefaultLocale() {
972
+ if (typeof window !== "undefined") {
973
+ try {
974
+ const stored = window.localStorage.getItem("chatkit:locale");
975
+ if (stored) {
976
+ return stored;
977
+ }
978
+ } catch {
979
+ }
980
+ }
981
+ return typeof navigator !== "undefined" ? navigator.language : null;
982
+ }
983
+ function resolveCopyLocale(locale) {
984
+ const normalized = (locale ?? getDefaultLocale() ?? "").trim().toLowerCase();
985
+ if (normalized === "zh-cn" || normalized === "zh-hans" || normalized.startsWith("zh")) {
986
+ return "zh-CN";
987
+ }
988
+ return "en-US";
989
+ }
990
+ function getSummaryDensityMetrics(density) {
991
+ switch (density) {
992
+ case "compact":
993
+ return {
994
+ padding: "8px 10px",
995
+ gap: 6,
996
+ marginTop: 3,
997
+ toggleSize: 30,
998
+ actionSize: 22
999
+ };
1000
+ case "spacious":
1001
+ return {
1002
+ padding: "14px 16px",
1003
+ gap: 10,
1004
+ marginTop: 6,
1005
+ toggleSize: 38,
1006
+ actionSize: 28
1007
+ };
1008
+ case "normal":
1009
+ default:
1010
+ return {
1011
+ padding: "12px 14px",
1012
+ gap: 8,
1013
+ marginTop: 4,
1014
+ toggleSize: 34,
1015
+ actionSize: 26
1016
+ };
1017
+ }
1018
+ }
1019
+ function getSummaryRadius(radius) {
1020
+ switch (radius) {
1021
+ case "pill":
1022
+ return 24;
1023
+ case "round":
1024
+ return 16;
1025
+ case "sharp":
1026
+ return 0;
1027
+ case "soft":
1028
+ default:
1029
+ return 12;
1030
+ }
1031
+ }
1032
+ function getSummaryThemeMetrics(theme) {
1033
+ var _a2, _b2;
1034
+ const themeObject = typeof theme === "string" ? null : theme;
1035
+ const baseSize = ((_a2 = themeObject == null ? void 0 : themeObject.typography) == null ? void 0 : _a2.baseSize) ?? 16;
1036
+ const density = (themeObject == null ? void 0 : themeObject.density) ?? "normal";
1037
+ const densityOffset = density === "compact" ? -1 : density === "spacious" ? 1 : 0;
1038
+ const bodySize = clampNumber(baseSize - 2 + densityOffset, 11, 17);
1039
+ const densityMetrics = getSummaryDensityMetrics(density);
1040
+ return {
1041
+ ...densityMetrics,
1042
+ bodySize,
1043
+ titleSize: bodySize + 1,
1044
+ iconSize: clampNumber(bodySize + 2, 13, 19),
1045
+ radius: getSummaryRadius(themeObject == null ? void 0 : themeObject.radius),
1046
+ fontFamily: ((_b2 = themeObject == null ? void 0 : themeObject.typography) == null ? void 0 : _b2.fontFamily) ?? PET_SUMMARY_FONT_FAMILY
1047
+ };
1048
+ }
1049
+ function isPetState(value) {
1050
+ return value === "idle" || value === "running-right" || value === "running-left" || value === "waving" || value === "jumping" || value === "failed" || value === "waiting" || value === "running" || value === "review";
1051
+ }
1052
+ function parsePetStateChangePayload(value) {
1053
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1054
+ return null;
1055
+ }
1056
+ const payload = value;
1057
+ return isPetState(payload.state) ? { state: payload.state } : null;
1058
+ }
1059
+ function parsePetOptionsChangePayload(value) {
1060
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1061
+ return null;
1062
+ }
1063
+ const payload = value;
1064
+ if (payload.pet === null || typeof payload.pet === "boolean") {
1065
+ return { pet: payload.pet };
1066
+ }
1067
+ if (payload.pet && typeof payload.pet === "object" && !Array.isArray(payload.pet)) {
1068
+ return { pet: payload.pet };
1069
+ }
1070
+ return null;
1071
+ }
1072
+ function isThreadSummaryStatus(value) {
1073
+ return value === "running" || value === "completed" || value === "failed";
1074
+ }
1075
+ function getThreadSummaryKey(summary) {
1076
+ if (!summary) {
1077
+ return null;
1078
+ }
1079
+ return [
1080
+ summary.threadId,
1081
+ summary.messageId || summary.updatedAt || summary.message
1082
+ ].join(":");
1083
+ }
1084
+ function getThreadSummaryInteractionKey(summary) {
1085
+ if (!summary) {
1086
+ return null;
1087
+ }
1088
+ return [summary.threadId, summary.messageId ?? ""].join(":");
1089
+ }
1090
+ function parseThreadSummaryPayload(value) {
1091
+ if (value === null) {
1092
+ return { summary: null };
1093
+ }
1094
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1095
+ return null;
1096
+ }
1097
+ const payload = value;
1098
+ if (typeof payload.threadId !== "string" || !payload.threadId.trim() || typeof payload.title !== "string" || !payload.title.trim() || typeof payload.message !== "string" || !payload.message.trim() || !isThreadSummaryStatus(payload.status)) {
1099
+ return null;
1100
+ }
1101
+ return {
1102
+ summary: {
1103
+ threadId: payload.threadId,
1104
+ title: payload.title,
1105
+ message: payload.message,
1106
+ status: payload.status,
1107
+ ...typeof payload.messageId === "string" && payload.messageId.trim() ? { messageId: payload.messageId } : {},
1108
+ ...typeof payload.updatedAt === "string" && payload.updatedAt.trim() ? { updatedAt: payload.updatedAt } : {}
1109
+ }
1110
+ };
1111
+ }
1112
+ function parseThreadSummaryLogPayload(value) {
1113
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1114
+ return null;
1115
+ }
1116
+ const payload = value;
1117
+ if (payload.name !== "thread.summary") {
1118
+ return null;
1119
+ }
1120
+ return parseThreadSummaryPayload(payload.data ?? null);
1121
+ }
1122
+ class PetOverlay {
1123
+ constructor(root, options) {
1124
+ this.overlayElement = null;
1125
+ this.petElement = null;
1126
+ this.contextMenuElement = null;
1127
+ this.summaryElement = null;
1128
+ this.summaryToggleElement = null;
1129
+ this.mediaElement = null;
1130
+ this.options = null;
1131
+ this.theme = null;
1132
+ this.resolved = null;
1133
+ this.summary = null;
1134
+ this.summaryRenderKey = null;
1135
+ this.dismissedSummaryKey = null;
1136
+ this.isSummaryCollapsed = false;
1137
+ this.isSummaryExpanded = false;
1138
+ this.isSummaryHovering = false;
1139
+ this.isReplyOpen = false;
1140
+ this.isReplySubmitting = false;
1141
+ this.replyError = null;
1142
+ this.replyDraft = "";
1143
+ this.replyInputElement = null;
1144
+ this.copyLocale = resolveCopyLocale();
1145
+ this.copy = PET_OVERLAY_COPY[this.copyLocale];
1146
+ this.currentState = "waiting";
1147
+ this.lastAutoState = "waiting";
1148
+ this.transient = null;
1149
+ this.position = null;
1150
+ this.dragPosition = null;
1151
+ this.dragOffset = { x: 0, y: 0 };
1152
+ this.lastDragPosition = null;
1153
+ this.lastDragClientX = null;
1154
+ this.dragAnimation = null;
1155
+ this.isDragging = false;
1156
+ this.isHovering = false;
1157
+ this.movedDuringDrag = false;
1158
+ this.prefersReducedMotion = false;
1159
+ this.frame = 0;
1160
+ this.completed = false;
1161
+ this.activeAnimationName = null;
1162
+ this.activeAnimationMode = null;
1163
+ this.frameTimer = null;
1164
+ this.restingDelayTimer = null;
1165
+ this.mediaQuery = null;
1166
+ this.connected = false;
1167
+ this.handleViewportChange = () => {
1168
+ this.closeContextMenu();
1169
+ this.render();
1170
+ };
1171
+ this.handleReducedMotionChange = () => {
1172
+ var _a2;
1173
+ this.prefersReducedMotion = Boolean((_a2 = this.mediaQuery) == null ? void 0 : _a2.matches);
1174
+ if (this.prefersReducedMotion) {
1175
+ this.transient = null;
1176
+ }
1177
+ this.render();
1178
+ };
1179
+ this.handlePointerEnter = () => {
1180
+ this.clearRestingDelayTimer();
1181
+ this.isHovering = true;
1182
+ this.rescheduleAnimation();
1183
+ };
1184
+ this.handlePointerLeave = () => {
1185
+ if (!this.isDragging) {
1186
+ this.enterRestingAfterDelay();
1187
+ }
1188
+ };
1189
+ this.handleContextMenu = (event) => {
1190
+ event.preventDefault();
1191
+ event.stopPropagation();
1192
+ this.openContextMenu({ x: event.clientX, y: event.clientY });
1193
+ };
1194
+ this.handleContextMenuEvent = (event) => {
1195
+ event.preventDefault();
1196
+ event.stopPropagation();
1197
+ };
1198
+ this.handleContextMenuOutsidePointerDown = (event) => {
1199
+ const menu = this.contextMenuElement;
1200
+ if (menu && event.composedPath().includes(menu)) {
1201
+ return;
1202
+ }
1203
+ this.closeContextMenu();
1204
+ };
1205
+ this.handleContextMenuKeyDown = (event) => {
1206
+ if (event.key !== "Escape") {
1207
+ return;
1208
+ }
1209
+ event.preventDefault();
1210
+ this.closeContextMenu();
1211
+ };
1212
+ this.handleClosePetMenuItemClick = (event) => {
1213
+ var _a2;
1214
+ event.preventDefault();
1215
+ event.stopPropagation();
1216
+ this.closeContextMenu();
1217
+ (_a2 = this.onClose) == null ? void 0 : _a2.call(this);
1218
+ };
1219
+ this.handleSummaryPointerEnter = () => {
1220
+ this.isSummaryHovering = true;
1221
+ this.render();
1222
+ };
1223
+ this.handleSummaryPointerLeave = () => {
1224
+ this.isSummaryHovering = false;
1225
+ if (!this.isReplyOpen) {
1226
+ this.render();
1227
+ }
1228
+ };
1229
+ this.handleSummaryClick = () => {
1230
+ var _a2, _b2;
1231
+ const threadId = (_a2 = this.summary) == null ? void 0 : _a2.threadId.trim();
1232
+ if (!threadId) {
1233
+ return;
1234
+ }
1235
+ (_b2 = this.onThreadSummaryActivate) == null ? void 0 : _b2.call(this, threadId);
1236
+ };
1237
+ this.handleSummaryDelete = () => {
1238
+ const summaryKey = getThreadSummaryKey(this.summary);
1239
+ if (summaryKey) {
1240
+ this.dismissedSummaryKey = summaryKey;
1241
+ }
1242
+ this.isSummaryCollapsed = false;
1243
+ this.isReplyOpen = false;
1244
+ this.replyDraft = "";
1245
+ this.replyError = null;
1246
+ this.removeSummaryElements();
1247
+ };
1248
+ this.handleSummaryCollapseToggle = () => {
1249
+ this.isSummaryCollapsed = !this.isSummaryCollapsed;
1250
+ this.isSummaryExpanded = false;
1251
+ this.isReplyOpen = false;
1252
+ this.replyError = null;
1253
+ this.render();
1254
+ };
1255
+ this.handleSummaryExpandToggle = () => {
1256
+ this.isSummaryExpanded = !this.isSummaryExpanded;
1257
+ this.render();
1258
+ };
1259
+ this.handleReplyOpen = () => {
1260
+ this.isReplyOpen = true;
1261
+ this.replyError = null;
1262
+ this.render();
1263
+ };
1264
+ this.handleReplyInput = (event) => {
1265
+ const target = event.currentTarget;
1266
+ if (target instanceof HTMLInputElement) {
1267
+ this.replyDraft = target.value;
1268
+ this.replyError = null;
1269
+ }
1270
+ };
1271
+ this.handleReplySubmit = (event) => {
1272
+ event.preventDefault();
1273
+ void this.submitReply();
1274
+ };
1275
+ this.handleReplyKeyDown = (event) => {
1276
+ if (event.key !== "Escape") {
1277
+ return;
1278
+ }
1279
+ event.preventDefault();
1280
+ this.isReplyOpen = false;
1281
+ this.replyError = null;
1282
+ this.render();
1283
+ };
1284
+ this.handlePointerDown = (event) => {
1285
+ var _a2, _b2;
1286
+ if (event.button !== 0 || event.ctrlKey) {
1287
+ return;
1288
+ }
1289
+ this.closeContextMenu();
1290
+ if (!((_a2 = this.options) == null ? void 0 : _a2.position.draggable)) {
1291
+ return;
1292
+ }
1293
+ event.preventDefault();
1294
+ const rect = (_b2 = this.petElement) == null ? void 0 : _b2.getBoundingClientRect();
1295
+ if (!rect) {
1296
+ return;
1297
+ }
1298
+ const nextPosition = {
1299
+ x: rect.left,
1300
+ y: rect.top
1301
+ };
1302
+ this.dragOffset = {
1303
+ x: event.clientX - rect.left,
1304
+ y: event.clientY - rect.top
1305
+ };
1306
+ this.lastDragPosition = nextPosition;
1307
+ this.lastDragClientX = event.clientX;
1308
+ this.dragAnimation = null;
1309
+ this.movedDuringDrag = false;
1310
+ this.dragPosition = nextPosition;
1311
+ this.isDragging = true;
1312
+ this.clearRestingDelayTimer();
1313
+ this.isHovering = true;
1314
+ this.installDragListeners();
1315
+ this.rescheduleAnimation();
1316
+ };
1317
+ this.handlePointerMove = (event) => {
1318
+ const nextPosition = this.getNextDragPosition(event);
1319
+ const last = this.lastDragPosition;
1320
+ if (last && (Math.abs(last.x - nextPosition.x) > DRAG_DIRECTION_THRESHOLD_PX || Math.abs(last.y - nextPosition.y) > DRAG_DIRECTION_THRESHOLD_PX)) {
1321
+ this.movedDuringDrag = true;
1322
+ }
1323
+ if (this.lastDragClientX !== null) {
1324
+ const deltaX = event.clientX - this.lastDragClientX;
1325
+ if (deltaX > DRAG_DIRECTION_THRESHOLD_PX) {
1326
+ this.dragAnimation = "running-right";
1327
+ } else if (deltaX < -DRAG_DIRECTION_THRESHOLD_PX) {
1328
+ this.dragAnimation = "running-left";
1329
+ }
1330
+ }
1331
+ this.lastDragClientX = event.clientX;
1332
+ this.lastDragPosition = nextPosition;
1333
+ this.dragPosition = nextPosition;
1334
+ this.render();
1335
+ };
1336
+ this.handlePointerUp = (event) => {
1337
+ const finalPosition = this.lastDragPosition ?? this.getNextDragPosition(event);
1338
+ this.isDragging = false;
1339
+ this.dragPosition = null;
1340
+ this.dragAnimation = null;
1341
+ this.lastDragClientX = null;
1342
+ this.removeDragListeners();
1343
+ this.persistPosition(finalPosition);
1344
+ if (event.pointerType === "mouse" && this.isPointerOverPet(event)) {
1345
+ this.isHovering = true;
1346
+ this.rescheduleAnimation();
1347
+ } else {
1348
+ this.enterRestingAfterDelay();
1349
+ this.rescheduleAnimation();
1350
+ }
1351
+ };
1352
+ this.handleClick = () => {
1353
+ var _a2;
1354
+ if (this.movedDuringDrag) {
1355
+ return;
1356
+ }
1357
+ (_a2 = this.onActivate) == null ? void 0 : _a2.call(this);
1358
+ if (this.prefersReducedMotion) {
1359
+ return;
1360
+ }
1361
+ this.transient = { name: "waving" };
1362
+ this.render();
1363
+ };
1364
+ this.root = root;
1365
+ this.onActivate = options == null ? void 0 : options.onActivate;
1366
+ this.onClose = options == null ? void 0 : options.onClose;
1367
+ this.onReply = options == null ? void 0 : options.onReply;
1368
+ this.onThreadSummaryActivate = options == null ? void 0 : options.onThreadSummaryActivate;
1369
+ this.connect();
1370
+ }
1371
+ connect() {
1372
+ if (this.connected) {
1373
+ return;
1374
+ }
1375
+ this.connected = true;
1376
+ this.installViewportListeners();
1377
+ this.installReducedMotionListener();
1378
+ this.render();
1379
+ }
1380
+ setOptions(pet, theme) {
1381
+ this.closeContextMenu();
1382
+ const nextOptions = chatkitTypes.normalizePetOptions(pet);
1383
+ this.options = nextOptions;
1384
+ this.theme = theme ?? null;
1385
+ if (!nextOptions) {
1386
+ this.isDragging = false;
1387
+ this.isHovering = false;
1388
+ this.position = null;
1389
+ this.dragPosition = null;
1390
+ this.dragAnimation = null;
1391
+ this.lastDragPosition = null;
1392
+ this.lastDragClientX = null;
1393
+ this.transient = null;
1394
+ this.resolved = null;
1395
+ this.clearRestingDelayTimer();
1396
+ this.removeDragListeners();
1397
+ this.removeOverlay();
1398
+ return;
1399
+ }
1400
+ this.position = readPersistedPosition(
1401
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1402
+ nextOptions.position.persist
1403
+ );
1404
+ if (nextOptions.behavior === "auto" && !this.prefersReducedMotion) {
1405
+ this.transient = { name: "waving" };
1406
+ }
1407
+ this.resolveCharacter();
1408
+ this.render();
1409
+ }
1410
+ setState(state) {
1411
+ var _a2;
1412
+ const previous = this.lastAutoState;
1413
+ this.lastAutoState = state;
1414
+ this.currentState = state;
1415
+ if (((_a2 = this.options) == null ? void 0 : _a2.behavior) === "auto" && !this.prefersReducedMotion && state === "idle" && (previous === "running" || previous === "review") && !this.transient) {
1416
+ this.transient = { name: "jumping" };
1417
+ } else if (state !== "idle") {
1418
+ this.transient = null;
1419
+ }
1420
+ this.render();
1421
+ }
1422
+ setLocale(locale) {
1423
+ const nextLocale = resolveCopyLocale(locale);
1424
+ if (nextLocale === this.copyLocale) {
1425
+ return;
1426
+ }
1427
+ this.copyLocale = nextLocale;
1428
+ this.copy = PET_OVERLAY_COPY[nextLocale];
1429
+ this.summaryRenderKey = null;
1430
+ this.closeContextMenu();
1431
+ this.render();
1432
+ }
1433
+ setThreadSummary(summary) {
1434
+ const previousKey = getThreadSummaryInteractionKey(this.summary);
1435
+ const nextKey = getThreadSummaryInteractionKey(summary);
1436
+ this.summary = summary;
1437
+ if (!summary) {
1438
+ this.isSummaryCollapsed = false;
1439
+ this.isSummaryExpanded = false;
1440
+ this.isSummaryHovering = false;
1441
+ this.isReplyOpen = false;
1442
+ this.isReplySubmitting = false;
1443
+ this.replyError = null;
1444
+ this.replyDraft = "";
1445
+ this.summaryRenderKey = null;
1446
+ this.removeSummaryElements();
1447
+ return;
1448
+ }
1449
+ if (previousKey !== nextKey) {
1450
+ this.isSummaryCollapsed = false;
1451
+ this.isSummaryExpanded = false;
1452
+ this.isSummaryHovering = false;
1453
+ this.isReplyOpen = false;
1454
+ this.isReplySubmitting = false;
1455
+ this.replyError = null;
1456
+ this.replyDraft = "";
1457
+ }
1458
+ this.render();
1459
+ }
1460
+ setThreadSummaryStatus(status) {
1461
+ if (!this.summary || this.summary.status === status) {
1462
+ return;
1463
+ }
1464
+ this.summary = { ...this.summary, status };
1465
+ this.render();
1466
+ }
1467
+ destroy() {
1468
+ var _a2, _b2, _c2, _d;
1469
+ if (!this.connected) {
1470
+ return;
1471
+ }
1472
+ this.connected = false;
1473
+ this.clearRestingDelayTimer();
1474
+ this.clearTimers();
1475
+ this.removeDragListeners();
1476
+ this.removeOverlay();
1477
+ window.removeEventListener("resize", this.handleViewportChange);
1478
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.removeEventListener(
1479
+ "resize",
1480
+ this.handleViewportChange
1481
+ );
1482
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.removeEventListener(
1483
+ "scroll",
1484
+ this.handleViewportChange
1485
+ );
1486
+ (_d = (_c2 = this.mediaQuery) == null ? void 0 : _c2.removeEventListener) == null ? void 0 : _d.call(
1487
+ _c2,
1488
+ "change",
1489
+ this.handleReducedMotionChange
1490
+ );
1491
+ this.mediaQuery = null;
1492
+ }
1493
+ installViewportListeners() {
1494
+ var _a2, _b2;
1495
+ window.addEventListener("resize", this.handleViewportChange);
1496
+ (_a2 = window.visualViewport) == null ? void 0 : _a2.addEventListener(
1497
+ "resize",
1498
+ this.handleViewportChange
1499
+ );
1500
+ (_b2 = window.visualViewport) == null ? void 0 : _b2.addEventListener(
1501
+ "scroll",
1502
+ this.handleViewportChange
1503
+ );
1504
+ }
1505
+ installReducedMotionListener() {
1506
+ var _a2, _b2;
1507
+ if (!window.matchMedia) {
1508
+ return;
1509
+ }
1510
+ this.mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
1511
+ this.prefersReducedMotion = this.mediaQuery.matches;
1512
+ (_b2 = (_a2 = this.mediaQuery).addEventListener) == null ? void 0 : _b2.call(
1513
+ _a2,
1514
+ "change",
1515
+ this.handleReducedMotionChange
1516
+ );
1517
+ }
1518
+ resolveCharacter() {
1519
+ if (!this.options) {
1520
+ this.resolved = null;
1521
+ return;
1522
+ }
1523
+ const character = this.options.character;
1524
+ this.resolved = chatkitTypes.resolvePetCharacter(character);
1525
+ }
1526
+ ensureOverlay() {
1527
+ if (this.overlayElement && this.petElement) {
1528
+ return;
1529
+ }
1530
+ const overlay = document.createElement("div");
1531
+ overlay.setAttribute("data-chatkit-host-pet-layer", "");
1532
+ overlay.style.position = "fixed";
1533
+ overlay.style.inset = "0";
1534
+ overlay.style.pointerEvents = "none";
1535
+ overlay.style.overflow = "visible";
1536
+ const style = document.createElement("style");
1537
+ style.textContent = `
1538
+ @keyframes chatkit-pet-summary-spin {
1539
+ to { transform: rotate(360deg); }
1540
+ }
1541
+ `;
1542
+ const pet = document.createElement("div");
1543
+ pet.setAttribute("data-chatkit-host-pet", "");
1544
+ pet.style.position = "absolute";
1545
+ pet.style.top = "0";
1546
+ pet.style.left = "0";
1547
+ pet.style.pointerEvents = "auto";
1548
+ pet.style.touchAction = "none";
1549
+ pet.style.userSelect = "none";
1550
+ pet.style.willChange = "transform";
1551
+ pet.addEventListener("pointerenter", this.handlePointerEnter);
1552
+ pet.addEventListener("pointerleave", this.handlePointerLeave);
1553
+ pet.addEventListener("pointerdown", this.handlePointerDown);
1554
+ pet.addEventListener("contextmenu", this.handleContextMenu);
1555
+ pet.addEventListener("click", this.handleClick);
1556
+ overlay.append(style, pet);
1557
+ this.root.append(overlay);
1558
+ this.overlayElement = overlay;
1559
+ this.petElement = pet;
1560
+ }
1561
+ removeOverlay() {
1562
+ var _a2;
1563
+ this.clearRestingDelayTimer();
1564
+ this.clearTimers();
1565
+ this.closeContextMenu();
1566
+ if (this.petElement) {
1567
+ this.petElement.removeEventListener(
1568
+ "pointerenter",
1569
+ this.handlePointerEnter
1570
+ );
1571
+ this.petElement.removeEventListener(
1572
+ "pointerleave",
1573
+ this.handlePointerLeave
1574
+ );
1575
+ this.petElement.removeEventListener(
1576
+ "pointerdown",
1577
+ this.handlePointerDown
1578
+ );
1579
+ this.petElement.removeEventListener(
1580
+ "contextmenu",
1581
+ this.handleContextMenu
1582
+ );
1583
+ this.petElement.removeEventListener("click", this.handleClick);
1584
+ }
1585
+ this.isHovering = false;
1586
+ this.removeSummaryElements();
1587
+ (_a2 = this.overlayElement) == null ? void 0 : _a2.remove();
1588
+ this.overlayElement = null;
1589
+ this.petElement = null;
1590
+ this.mediaElement = null;
1591
+ }
1592
+ removeSummaryElements() {
1593
+ var _a2, _b2;
1594
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1595
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1596
+ this.summaryElement = null;
1597
+ this.summaryToggleElement = null;
1598
+ this.replyInputElement = null;
1599
+ this.summaryRenderKey = null;
1600
+ }
1601
+ getSize() {
1602
+ if (!this.options || !this.resolved) {
1603
+ return { width: 0, height: 0 };
1604
+ }
1605
+ const scale = getRenderScale(this.options.position.scale);
1606
+ const baseSize = {
1607
+ width: this.resolved.atlas.cellWidth,
1608
+ height: this.resolved.atlas.cellHeight
1609
+ };
1610
+ return {
1611
+ width: baseSize.width * scale,
1612
+ height: baseSize.height * scale
1613
+ };
1614
+ }
1615
+ getCurrentPosition(size) {
1616
+ const options = this.options;
1617
+ if (!options) {
1618
+ return { x: 0, y: 0 };
1619
+ }
1620
+ const viewport = getViewportSize();
1621
+ const padding = chatkitTypes.normalizeBoundsPadding(options.position.boundsPadding);
1622
+ const pin = options.position.pin === void 0 ? "bottom-right" : options.position.pin;
1623
+ const pinnedPosition = pin ? chatkitTypes.getPinnedPetPosition(pin, size, viewport, padding) : null;
1624
+ return chatkitTypes.clampPetPosition(
1625
+ this.dragPosition ?? this.position ?? pinnedPosition ?? { x: padding.left, y: padding.top },
1626
+ size,
1627
+ viewport,
1628
+ padding
1629
+ );
1630
+ }
1631
+ persistPosition(nextPosition) {
1632
+ if (!this.options) {
1633
+ return;
1634
+ }
1635
+ const size = this.getSize();
1636
+ const clamped = chatkitTypes.clampPetPosition(
1637
+ nextPosition,
1638
+ size,
1639
+ getViewportSize(),
1640
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
1641
+ );
1642
+ this.position = clamped;
1643
+ writePersistedPosition(
1644
+ chatkitTypes.DEFAULT_PET_STORAGE_KEY,
1645
+ this.options.position.persist,
1646
+ clamped
1647
+ );
1648
+ }
1649
+ getActiveAnimationName() {
1650
+ if (!this.options) {
1651
+ return "idle";
1652
+ }
1653
+ if (this.isDragging) {
1654
+ return this.dragAnimation ?? "running";
1655
+ }
1656
+ if (this.transient) {
1657
+ return this.transient.name;
1658
+ }
1659
+ if (this.options.behavior === "manual") {
1660
+ return "idle";
1661
+ }
1662
+ return this.currentState;
1663
+ }
1664
+ getActiveAnimationMode() {
1665
+ if (this.isDragging) {
1666
+ return "loop";
1667
+ }
1668
+ return this.transient ? "once" : "loop";
1669
+ }
1670
+ resetAnimationIfNeeded(name, mode) {
1671
+ if (this.activeAnimationName === name && this.activeAnimationMode === mode) {
1672
+ return;
1673
+ }
1674
+ this.clearTimers();
1675
+ this.activeAnimationName = name;
1676
+ this.activeAnimationMode = mode;
1677
+ this.frame = 0;
1678
+ this.completed = false;
1679
+ }
1680
+ render() {
1681
+ if (!this.options || !this.resolved) {
1682
+ this.clearTimers();
1683
+ if (this.petElement) {
1684
+ this.petElement.replaceChildren();
1685
+ }
1686
+ this.removeSummaryElements();
1687
+ this.mediaElement = null;
1688
+ this.activeAnimationName = null;
1689
+ this.activeAnimationMode = null;
1690
+ this.frame = 0;
1691
+ this.completed = false;
1692
+ return;
1693
+ }
1694
+ this.ensureOverlay();
1695
+ const overlay = this.overlayElement;
1696
+ const pet = this.petElement;
1697
+ if (!overlay || !pet) {
1698
+ return;
1699
+ }
1700
+ const size = this.getSize();
1701
+ const position = this.getCurrentPosition(size);
1702
+ const animationName = this.getActiveAnimationName();
1703
+ const animationMode = this.getActiveAnimationMode();
1704
+ this.resetAnimationIfNeeded(animationName, animationMode);
1705
+ overlay.style.zIndex = String(this.options.position.zIndex);
1706
+ pet.style.width = `${size.width}px`;
1707
+ pet.style.height = `${size.height}px`;
1708
+ pet.style.transform = `translate3d(${position.x}px, ${position.y}px, 0)`;
1709
+ pet.style.cursor = this.options.position.draggable ? this.isDragging ? "grabbing" : "grab" : "default";
1710
+ pet.dataset.petAnimation = animationName;
1711
+ pet.setAttribute("aria-label", this.options.ariaLabel);
1712
+ pet.setAttribute("role", "img");
1713
+ this.renderAtlas(animationName, animationMode);
1714
+ this.renderThreadSummary(position, size);
1715
+ this.scheduleNextFrame(animationName, animationMode);
1716
+ }
1717
+ renderThreadSummary(position, size) {
1718
+ var _a2, _b2, _c2;
1719
+ const summary = this.summary;
1720
+ const summaryKey = getThreadSummaryKey(summary);
1721
+ if (!summary || !summaryKey || this.dismissedSummaryKey === summaryKey) {
1722
+ this.removeSummaryElements();
1723
+ return;
1724
+ }
1725
+ if (this.isSummaryCollapsed) {
1726
+ this.renderCollapsedSummary(position, size);
1727
+ return;
1728
+ }
1729
+ const nextRenderKey = [
1730
+ this.copyLocale,
1731
+ this.isSummaryExpanded ? "expanded" : "compact",
1732
+ this.isSummaryHovering ? "hover" : "rest",
1733
+ this.isReplyOpen ? "reply" : "closed",
1734
+ this.isReplySubmitting ? "submitting" : "ready",
1735
+ this.replyError ?? ""
1736
+ ].join("|");
1737
+ if (!this.summaryElement || this.summaryRenderKey !== nextRenderKey) {
1738
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1739
+ (_b2 = this.summaryToggleElement) == null ? void 0 : _b2.remove();
1740
+ this.summaryElement = this.createSummaryBubble(summary);
1741
+ this.summaryToggleElement = this.createSummaryToggleButton("v");
1742
+ (_c2 = this.overlayElement) == null ? void 0 : _c2.append(
1743
+ this.summaryElement,
1744
+ this.summaryToggleElement
1745
+ );
1746
+ this.summaryRenderKey = nextRenderKey;
1747
+ if (this.isReplyOpen && !this.isReplySubmitting) {
1748
+ window.setTimeout(() => {
1749
+ var _a3;
1750
+ return (_a3 = this.replyInputElement) == null ? void 0 : _a3.focus();
1751
+ }, 0);
1752
+ }
1753
+ }
1754
+ this.updateSummaryBubbleContent(summary);
1755
+ this.positionSummaryBubble(position, size);
1756
+ }
1757
+ renderCollapsedSummary(position, size) {
1758
+ var _a2, _b2;
1759
+ (_a2 = this.summaryElement) == null ? void 0 : _a2.remove();
1760
+ this.summaryElement = null;
1761
+ this.summaryRenderKey = null;
1762
+ if (!this.summaryToggleElement) {
1763
+ this.summaryToggleElement = this.createSummaryToggleButton("1");
1764
+ (_b2 = this.overlayElement) == null ? void 0 : _b2.append(this.summaryToggleElement);
1765
+ }
1766
+ this.summaryToggleElement.textContent = "1";
1767
+ this.positionSummaryToggleBadge(position, size);
1768
+ }
1769
+ positionSummaryToggleBadge(position, size) {
1770
+ const badge = this.summaryToggleElement;
1771
+ if (!badge) {
1772
+ return;
1773
+ }
1774
+ const viewport = getViewportSize();
1775
+ const badgeSize = getSummaryThemeMetrics(this.theme).toggleSize;
1776
+ const x = clampNumber(
1777
+ position.x + size.width - badgeSize * 0.35,
1778
+ PET_SUMMARY_MARGIN,
1779
+ viewport.width - badgeSize - PET_SUMMARY_MARGIN
1780
+ );
1781
+ const y = clampNumber(
1782
+ position.y - badgeSize * 0.35,
1783
+ PET_SUMMARY_MARGIN,
1784
+ viewport.height - badgeSize - PET_SUMMARY_MARGIN
1785
+ );
1786
+ badge.style.width = `${badgeSize}px`;
1787
+ badge.style.height = `${badgeSize}px`;
1788
+ badge.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1789
+ badge.style.borderRadius = "999px";
1790
+ }
1791
+ positionSummaryBubble(position, size) {
1792
+ const bubble = this.summaryElement;
1793
+ const toggle = this.summaryToggleElement;
1794
+ if (!bubble || !toggle) {
1795
+ return;
1796
+ }
1797
+ const viewport = getViewportSize();
1798
+ const width = Math.min(
1799
+ PET_SUMMARY_WIDTH,
1800
+ viewport.width - PET_SUMMARY_MARGIN * 2
1801
+ );
1802
+ bubble.style.width = `${width}px`;
1803
+ const bubbleHeight = bubble.offsetHeight || 96;
1804
+ const aboveY = position.y - bubbleHeight - PET_SUMMARY_GAP;
1805
+ const showAbove = aboveY >= PET_SUMMARY_MARGIN;
1806
+ const y = showAbove ? aboveY : clampNumber(
1807
+ position.y + size.height + PET_SUMMARY_GAP,
1808
+ PET_SUMMARY_MARGIN,
1809
+ viewport.height - bubbleHeight - PET_SUMMARY_MARGIN
1810
+ );
1811
+ const x = clampNumber(
1812
+ position.x + size.width / 2 - width / 2,
1813
+ PET_SUMMARY_MARGIN,
1814
+ viewport.width - width - PET_SUMMARY_MARGIN
1815
+ );
1816
+ bubble.style.transform = `translate3d(${x}px, ${y}px, 0)`;
1817
+ this.positionSummaryToggleBadge(position, size);
1818
+ }
1819
+ createSummaryBubble(summary) {
1820
+ const shouldShowReplyButton = this.isSummaryHovering && !this.isReplyOpen;
1821
+ const metrics = getSummaryThemeMetrics(this.theme);
1822
+ const bubble = document.createElement("div");
1823
+ bubble.setAttribute("data-chatkit-pet-summary", "");
1824
+ bubble.addEventListener("pointerenter", this.handleSummaryPointerEnter);
1825
+ bubble.addEventListener("pointerleave", this.handleSummaryPointerLeave);
1826
+ bubble.addEventListener("click", this.handleSummaryClick);
1827
+ bubble.style.position = "absolute";
1828
+ bubble.style.top = "0";
1829
+ bubble.style.left = "0";
1830
+ bubble.style.boxSizing = "border-box";
1831
+ bubble.style.pointerEvents = "auto";
1832
+ bubble.style.padding = metrics.padding;
1833
+ bubble.style.border = "1px solid rgba(148, 163, 184, 0.22)";
1834
+ bubble.style.borderRadius = `${metrics.radius}px`;
1835
+ bubble.style.background = "rgba(255, 255, 255, 0.94)";
1836
+ bubble.style.color = "#1f2937";
1837
+ bubble.style.boxShadow = "0 8px 24px rgba(15, 23, 42, 0.1)";
1838
+ bubble.style.font = `500 ${metrics.bodySize}px/1.35 ${metrics.fontFamily}`;
1839
+ bubble.style.backdropFilter = "blur(10px)";
1840
+ const header = document.createElement("div");
1841
+ header.style.display = "flex";
1842
+ header.style.alignItems = "center";
1843
+ header.style.gap = `${metrics.gap}px`;
1844
+ if (this.isSummaryHovering || this.isReplyOpen) {
1845
+ header.append(
1846
+ this.createSummaryActionButton(
1847
+ "x",
1848
+ this.copy.hideMessage,
1849
+ this.handleSummaryDelete
1850
+ )
1851
+ );
1852
+ }
1853
+ const title = document.createElement("div");
1854
+ title.textContent = summary.title;
1855
+ title.style.minWidth = "0";
1856
+ title.style.flex = "1";
1857
+ title.style.overflow = "hidden";
1858
+ title.style.textOverflow = "ellipsis";
1859
+ title.style.whiteSpace = "nowrap";
1860
+ title.style.fontWeight = "700";
1861
+ title.style.fontSize = `${metrics.titleSize}px`;
1862
+ title.dataset.chatkitPetSummaryTitle = "";
1863
+ header.append(title);
1864
+ if (this.isSummaryHovering || this.isReplyOpen) {
1865
+ header.append(
1866
+ this.createSummaryActionButton(
1867
+ this.isSummaryExpanded ? "-" : ">",
1868
+ this.isSummaryExpanded ? this.copy.collapseMessage : this.copy.expandMessage,
1869
+ this.handleSummaryExpandToggle
1870
+ )
1871
+ );
1872
+ } else {
1873
+ header.append(this.createStatusIcon(summary.status));
1874
+ }
1875
+ const message = document.createElement("div");
1876
+ message.textContent = summary.message;
1877
+ message.style.marginTop = `${metrics.marginTop}px`;
1878
+ message.style.fontWeight = "400";
1879
+ message.style.color = "#374151";
1880
+ message.style.overflow = "hidden";
1881
+ if (this.isSummaryExpanded) {
1882
+ message.style.maxHeight = "7em";
1883
+ message.style.overflowY = "auto";
1884
+ } else {
1885
+ message.style.display = "-webkit-box";
1886
+ message.style.setProperty("-webkit-line-clamp", "2");
1887
+ message.style.setProperty("-webkit-box-orient", "vertical");
1888
+ }
1889
+ message.dataset.chatkitPetSummaryMessage = "";
1890
+ bubble.append(header, message);
1891
+ if (shouldShowReplyButton) {
1892
+ const reply = this.createTextButton(
1893
+ this.copy.replyButton,
1894
+ this.handleReplyOpen
1895
+ );
1896
+ reply.style.position = "absolute";
1897
+ reply.style.right = "14px";
1898
+ reply.style.bottom = "10px";
1899
+ bubble.append(reply);
1900
+ }
1901
+ if (this.isReplyOpen) {
1902
+ bubble.append(this.createReplyForm());
1903
+ }
1904
+ return bubble;
1905
+ }
1906
+ updateSummaryBubbleContent(summary) {
1907
+ var _a2, _b2, _c2;
1908
+ const title = (_a2 = this.summaryElement) == null ? void 0 : _a2.querySelector(
1909
+ "[data-chatkit-pet-summary-title]"
1910
+ );
1911
+ if (title && title.textContent !== summary.title) {
1912
+ title.textContent = summary.title;
1913
+ }
1914
+ const message = (_b2 = this.summaryElement) == null ? void 0 : _b2.querySelector(
1915
+ "[data-chatkit-pet-summary-message]"
1916
+ );
1917
+ if (message && message.textContent !== summary.message) {
1918
+ message.textContent = summary.message;
1919
+ }
1920
+ const statusIcon = (_c2 = this.summaryElement) == null ? void 0 : _c2.querySelector(
1921
+ "[data-chatkit-pet-summary-status]"
1922
+ );
1923
+ if (statusIcon && statusIcon.dataset.chatkitPetSummaryStatus !== summary.status) {
1924
+ const nextIcon = this.createStatusIcon(summary.status);
1925
+ statusIcon.replaceWith(nextIcon);
1926
+ }
1927
+ }
1928
+ createSummaryToggleButton(label) {
1929
+ const metrics = getSummaryThemeMetrics(this.theme);
1930
+ const button = document.createElement("button");
1931
+ button.type = "button";
1932
+ button.textContent = label;
1933
+ button.title = label === "1" ? this.copy.restoreMessage : this.copy.collapseMessage;
1934
+ button.addEventListener("click", stopEventPropagation);
1935
+ button.addEventListener("click", this.handleSummaryCollapseToggle);
1936
+ button.style.position = "absolute";
1937
+ button.style.top = "0";
1938
+ button.style.left = "0";
1939
+ button.style.pointerEvents = "auto";
1940
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
1941
+ button.style.background = "rgba(248, 250, 252, 0.94)";
1942
+ button.style.color = "#475569";
1943
+ button.style.boxShadow = "0 6px 18px rgba(15, 23, 42, 0.1)";
1944
+ button.style.cursor = "pointer";
1945
+ button.style.font = `600 ${metrics.titleSize}px/1 ${metrics.fontFamily}`;
1946
+ button.style.display = "flex";
1947
+ button.style.alignItems = "center";
1948
+ button.style.justifyContent = "center";
1949
+ return button;
1950
+ }
1951
+ createStatusIcon(status) {
1952
+ const metrics = getSummaryThemeMetrics(this.theme);
1953
+ const iconSize = metrics.iconSize;
1954
+ const icon = document.createElement("span");
1955
+ icon.setAttribute("aria-hidden", "true");
1956
+ icon.dataset.chatkitPetSummaryStatus = status;
1957
+ icon.style.display = "inline-flex";
1958
+ icon.style.width = `${iconSize}px`;
1959
+ icon.style.height = `${iconSize}px`;
1960
+ icon.style.alignItems = "center";
1961
+ icon.style.justifyContent = "center";
1962
+ icon.style.flex = "0 0 auto";
1963
+ if (status === "running") {
1964
+ icon.style.border = "2px solid rgba(71, 85, 105, 0.32)";
1965
+ icon.style.borderTopColor = "#64748b";
1966
+ icon.style.borderRadius = "999px";
1967
+ icon.style.animation = "chatkit-pet-summary-spin 900ms linear infinite";
1968
+ return icon;
1969
+ }
1970
+ icon.style.borderRadius = "999px";
1971
+ icon.style.fontSize = `${Math.max(10, iconSize - 4)}px`;
1972
+ icon.style.fontWeight = "700";
1973
+ if (status === "failed") {
1974
+ icon.textContent = "!";
1975
+ icon.style.background = "#fee2e2";
1976
+ icon.style.color = "#b91c1c";
1977
+ return icon;
1978
+ }
1979
+ icon.textContent = "";
1980
+ icon.style.border = "2px solid #22c55e";
1981
+ icon.style.position = "relative";
1982
+ const check = document.createElement("span");
1983
+ check.style.width = `${Math.round(iconSize * 0.44)}px`;
1984
+ check.style.height = `${Math.round(iconSize * 0.25)}px`;
1985
+ check.style.borderLeft = "2px solid #22c55e";
1986
+ check.style.borderBottom = "2px solid #22c55e";
1987
+ check.style.transform = "rotate(-45deg) translate(1px, -1px)";
1988
+ icon.append(check);
1989
+ return icon;
1990
+ }
1991
+ createSummaryActionButton(label, title, onClick) {
1992
+ const metrics = getSummaryThemeMetrics(this.theme);
1993
+ const button = document.createElement("button");
1994
+ button.type = "button";
1995
+ button.textContent = label;
1996
+ button.title = title;
1997
+ button.addEventListener("click", (event) => {
1998
+ event.preventDefault();
1999
+ event.stopPropagation();
2000
+ onClick();
2001
+ });
2002
+ button.style.width = `${metrics.actionSize}px`;
2003
+ button.style.height = `${metrics.actionSize}px`;
2004
+ button.style.border = "0";
2005
+ button.style.borderRadius = "999px";
2006
+ button.style.background = "rgba(241, 245, 249, 0.96)";
2007
+ button.style.color = "#475569";
2008
+ button.style.cursor = "pointer";
2009
+ button.style.font = `600 ${metrics.titleSize}px/1 ${metrics.fontFamily}`;
2010
+ return button;
2011
+ }
2012
+ createTextButton(label, onClick) {
2013
+ const button = document.createElement("button");
2014
+ button.type = "button";
2015
+ button.textContent = label;
2016
+ button.addEventListener("click", (event) => {
2017
+ event.preventDefault();
2018
+ event.stopPropagation();
2019
+ onClick();
2020
+ });
2021
+ button.style.border = "1px solid rgba(148, 163, 184, 0.28)";
2022
+ button.style.borderRadius = "999px";
2023
+ button.style.background = "rgba(248, 250, 252, 0.95)";
2024
+ button.style.color = "#334155";
2025
+ button.style.cursor = "pointer";
2026
+ button.style.padding = "3px 10px";
2027
+ button.style.font = '600 12px/1.4 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2028
+ return button;
2029
+ }
2030
+ createReplyForm() {
2031
+ const form = document.createElement("form");
2032
+ form.addEventListener("click", stopEventPropagation);
2033
+ form.addEventListener("submit", this.handleReplySubmit);
2034
+ form.addEventListener("keydown", this.handleReplyKeyDown);
2035
+ form.style.display = "flex";
2036
+ form.style.gap = "6px";
2037
+ form.style.alignItems = "center";
2038
+ form.style.marginTop = "8px";
2039
+ const input = document.createElement("input");
2040
+ input.type = "text";
2041
+ input.value = this.replyDraft;
2042
+ input.disabled = this.isReplySubmitting;
2043
+ input.placeholder = this.copy.replyPlaceholder;
2044
+ input.addEventListener("input", this.handleReplyInput);
2045
+ input.style.minWidth = "0";
2046
+ input.style.flex = "1";
2047
+ input.style.border = "1px solid rgba(148, 163, 184, 0.35)";
2048
+ input.style.borderRadius = "999px";
2049
+ input.style.padding = "6px 10px";
2050
+ input.style.font = '400 13px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2051
+ this.replyInputElement = input;
2052
+ const send = document.createElement("button");
2053
+ send.type = "submit";
2054
+ send.textContent = this.isReplySubmitting ? this.copy.sendingButton : this.copy.sendButton;
2055
+ send.disabled = this.isReplySubmitting;
2056
+ send.style.border = "0";
2057
+ send.style.borderRadius = "999px";
2058
+ send.style.background = "#22c55e";
2059
+ send.style.color = "#052e16";
2060
+ send.style.cursor = this.isReplySubmitting ? "default" : "pointer";
2061
+ send.style.padding = "6px 10px";
2062
+ send.style.font = '700 12px/1.2 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2063
+ form.append(input, send);
2064
+ if (this.replyError) {
2065
+ const error = document.createElement("div");
2066
+ error.textContent = this.copy.sendFailed;
2067
+ error.style.flexBasis = "100%";
2068
+ error.style.color = "#b91c1c";
2069
+ error.style.fontSize = "12px";
2070
+ form.style.flexWrap = "wrap";
2071
+ form.append(error);
2072
+ }
2073
+ return form;
2074
+ }
2075
+ createContextMenu() {
2076
+ const menu = document.createElement("div");
2077
+ menu.setAttribute("data-chatkit-pet-context-menu", "");
2078
+ menu.setAttribute("role", "menu");
2079
+ menu.addEventListener("contextmenu", this.handleContextMenuEvent);
2080
+ menu.addEventListener("pointerdown", stopEventPropagation);
2081
+ menu.addEventListener("click", stopEventPropagation);
2082
+ menu.style.position = "absolute";
2083
+ menu.style.top = "0";
2084
+ menu.style.left = "0";
2085
+ menu.style.boxSizing = "border-box";
2086
+ menu.style.minWidth = "132px";
2087
+ menu.style.padding = "4px";
2088
+ menu.style.pointerEvents = "auto";
2089
+ menu.style.border = "1px solid rgba(148, 163, 184, 0.28)";
2090
+ menu.style.borderRadius = "10px";
2091
+ menu.style.background = "rgba(255, 255, 255, 0.96)";
2092
+ menu.style.color = "#1f2937";
2093
+ menu.style.boxShadow = "0 12px 28px rgba(15, 23, 42, 0.16)";
2094
+ menu.style.font = '500 13px/1.3 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
2095
+ menu.style.backdropFilter = "blur(10px)";
2096
+ const closeItem = document.createElement("button");
2097
+ closeItem.type = "button";
2098
+ closeItem.textContent = this.copy.closePetMenuItem;
2099
+ closeItem.setAttribute("role", "menuitem");
2100
+ closeItem.addEventListener("click", this.handleClosePetMenuItemClick);
2101
+ closeItem.style.display = "block";
2102
+ closeItem.style.width = "100%";
2103
+ closeItem.style.border = "0";
2104
+ closeItem.style.borderRadius = "7px";
2105
+ closeItem.style.background = "transparent";
2106
+ closeItem.style.color = "inherit";
2107
+ closeItem.style.cursor = "pointer";
2108
+ closeItem.style.padding = "7px 10px";
2109
+ closeItem.style.textAlign = "left";
2110
+ closeItem.style.font = "inherit";
2111
+ menu.append(closeItem);
2112
+ return menu;
2113
+ }
2114
+ openContextMenu(position) {
2115
+ var _a2;
2116
+ const overlay = this.overlayElement;
2117
+ if (!overlay) {
2118
+ return;
2119
+ }
2120
+ this.closeContextMenu();
2121
+ const menu = this.createContextMenu();
2122
+ overlay.append(menu);
2123
+ this.contextMenuElement = menu;
2124
+ this.positionContextMenu(position);
2125
+ (_a2 = menu.querySelector("button")) == null ? void 0 : _a2.focus({ preventScroll: true });
2126
+ window.addEventListener(
2127
+ "pointerdown",
2128
+ this.handleContextMenuOutsidePointerDown,
2129
+ true
2130
+ );
2131
+ window.addEventListener("keydown", this.handleContextMenuKeyDown);
2132
+ }
2133
+ closeContextMenu() {
2134
+ var _a2;
2135
+ (_a2 = this.contextMenuElement) == null ? void 0 : _a2.remove();
2136
+ this.contextMenuElement = null;
2137
+ window.removeEventListener(
2138
+ "pointerdown",
2139
+ this.handleContextMenuOutsidePointerDown,
2140
+ true
2141
+ );
2142
+ window.removeEventListener("keydown", this.handleContextMenuKeyDown);
2143
+ }
2144
+ positionContextMenu(position) {
2145
+ const menu = this.contextMenuElement;
2146
+ if (!menu) {
2147
+ return;
2148
+ }
2149
+ const viewport = getViewportSize();
2150
+ const width = menu.offsetWidth || 132;
2151
+ const height = menu.offsetHeight || 40;
2152
+ const maxX = Math.max(
2153
+ PET_CONTEXT_MENU_MARGIN,
2154
+ viewport.width - width - PET_CONTEXT_MENU_MARGIN
2155
+ );
2156
+ const maxY = Math.max(
2157
+ PET_CONTEXT_MENU_MARGIN,
2158
+ viewport.height - height - PET_CONTEXT_MENU_MARGIN
2159
+ );
2160
+ const x = clampNumber(position.x, PET_CONTEXT_MENU_MARGIN, maxX);
2161
+ const y = clampNumber(position.y, PET_CONTEXT_MENU_MARGIN, maxY);
2162
+ menu.style.transform = `translate3d(${x}px, ${y}px, 0)`;
2163
+ }
2164
+ renderAtlas(animationName, animationMode) {
2165
+ var _a2;
2166
+ if (!this.petElement || ((_a2 = this.resolved) == null ? void 0 : _a2.kind) !== "atlas" || !this.options) {
2167
+ return;
2168
+ }
2169
+ if (!(this.mediaElement instanceof HTMLDivElement)) {
2170
+ const frame = document.createElement("div");
2171
+ frame.setAttribute("aria-hidden", "true");
2172
+ this.petElement.replaceChildren(frame);
2173
+ this.mediaElement = frame;
2174
+ }
2175
+ const frameElement = this.mediaElement;
2176
+ const atlas = this.resolved.atlas;
2177
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
2178
+ const safeFrame = animationMode === "once" && this.completed ? Math.max(0, definition.frames - 1) : Math.min(this.frame, Math.max(0, definition.frames - 1));
2179
+ const scale = getRenderScale(this.options.position.scale);
2180
+ const sourceWidth = atlas.cellWidth;
2181
+ const sourceHeight = atlas.cellHeight;
2182
+ const backgroundWidth = atlas.columns * sourceWidth;
2183
+ const backgroundHeight = atlas.rows * sourceHeight;
2184
+ frameElement.style.width = `${sourceWidth}px`;
2185
+ frameElement.style.height = `${sourceHeight}px`;
2186
+ frameElement.style.overflow = "hidden";
2187
+ frameElement.style.transform = `scale(${scale})`;
2188
+ frameElement.style.transformOrigin = "top left";
2189
+ frameElement.style.pointerEvents = "none";
2190
+ frameElement.style.backgroundImage = `url("${escapeCssUrl(
2191
+ this.resolved.src
2192
+ )}")`;
2193
+ frameElement.style.backgroundRepeat = "no-repeat";
2194
+ frameElement.style.backgroundSize = `${backgroundWidth}px ${backgroundHeight}px`;
2195
+ frameElement.style.backgroundPosition = `${-safeFrame * sourceWidth}px ${-definition.row * sourceHeight}px`;
2196
+ frameElement.style.imageRendering = this.options.imageRendering;
2197
+ frameElement.dataset.petFrame = String(safeFrame);
2198
+ }
2199
+ scheduleNextFrame(animationName, animationMode) {
2200
+ if (this.prefersReducedMotion || this.completed || !this.resolved) {
2201
+ this.clearTimers();
2202
+ return;
2203
+ }
2204
+ if (this.frameTimer !== null) {
2205
+ return;
2206
+ }
2207
+ const atlas = this.resolved.atlas;
2208
+ const definition = atlas.animations[animationName] ?? atlas.animations.idle;
2209
+ const duration = definition.frameDurations[this.frame] ?? definition.frameDurations[definition.frameDurations.length - 1] ?? 150;
2210
+ const baseDuration = duration * PET_FRAME_DURATION_MULTIPLIER;
2211
+ const effectiveDuration = this.isHovering || this.isDragging ? baseDuration : baseDuration * PET_RESTING_FRAME_DURATION_MULTIPLIER;
2212
+ this.frameTimer = window.setTimeout(() => {
2213
+ this.frameTimer = null;
2214
+ const nextFrame = this.frame + 1;
2215
+ if (nextFrame >= definition.frames) {
2216
+ if (animationMode === "once") {
2217
+ this.completed = true;
2218
+ this.frame = Math.max(0, definition.frames - 1);
2219
+ this.finishTransient();
2220
+ return;
2221
+ }
2222
+ this.frame = 0;
2223
+ this.render();
2224
+ return;
2225
+ }
2226
+ this.frame = nextFrame;
2227
+ this.render();
2228
+ }, effectiveDuration);
2229
+ }
2230
+ clearTimers() {
2231
+ if (this.frameTimer !== null) {
2232
+ window.clearTimeout(this.frameTimer);
2233
+ this.frameTimer = null;
2234
+ }
2235
+ }
2236
+ clearRestingDelayTimer() {
2237
+ if (this.restingDelayTimer !== null) {
2238
+ window.clearTimeout(this.restingDelayTimer);
2239
+ this.restingDelayTimer = null;
2240
+ }
2241
+ }
2242
+ finishTransient() {
2243
+ this.transient = null;
2244
+ this.activeAnimationName = null;
2245
+ this.activeAnimationMode = null;
2246
+ this.render();
2247
+ }
2248
+ rescheduleAnimation() {
2249
+ this.clearTimers();
2250
+ this.render();
2251
+ }
2252
+ enterRestingAfterDelay() {
2253
+ this.clearRestingDelayTimer();
2254
+ this.isHovering = true;
2255
+ this.restingDelayTimer = window.setTimeout(() => {
2256
+ this.restingDelayTimer = null;
2257
+ if (this.isDragging) {
2258
+ return;
2259
+ }
2260
+ this.isHovering = false;
2261
+ this.rescheduleAnimation();
2262
+ }, PET_RESTING_DELAY_MS);
2263
+ }
2264
+ isPointOverPet(clientX, clientY) {
2265
+ var _a2;
2266
+ const rect = (_a2 = this.petElement) == null ? void 0 : _a2.getBoundingClientRect();
2267
+ if (!rect) {
2268
+ return false;
2269
+ }
2270
+ return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
2271
+ }
2272
+ isPointerOverPet(event) {
2273
+ return this.isPointOverPet(event.clientX, event.clientY);
2274
+ }
2275
+ async submitReply() {
2276
+ var _a2;
2277
+ const text = this.replyDraft.trim();
2278
+ if (!text || this.isReplySubmitting) {
2279
+ return;
2280
+ }
2281
+ this.isReplySubmitting = true;
2282
+ this.replyError = null;
2283
+ this.render();
2284
+ try {
2285
+ await ((_a2 = this.onReply) == null ? void 0 : _a2.call(this, text));
2286
+ this.replyDraft = "";
2287
+ this.isReplyOpen = false;
2288
+ this.isSummaryHovering = false;
2289
+ } catch {
2290
+ this.replyError = "Failed to send";
2291
+ } finally {
2292
+ this.isReplySubmitting = false;
2293
+ this.render();
2294
+ }
2295
+ }
2296
+ getNextDragPosition(event) {
2297
+ if (!this.options) {
2298
+ return { x: 0, y: 0 };
2299
+ }
2300
+ return chatkitTypes.clampPetPosition(
2301
+ {
2302
+ x: event.clientX - this.dragOffset.x,
2303
+ y: event.clientY - this.dragOffset.y
2304
+ },
2305
+ this.getSize(),
2306
+ getViewportSize(),
2307
+ chatkitTypes.normalizeBoundsPadding(this.options.position.boundsPadding)
2308
+ );
2309
+ }
2310
+ installDragListeners() {
2311
+ window.addEventListener("pointermove", this.handlePointerMove);
2312
+ window.addEventListener("pointerup", this.handlePointerUp, { once: true });
2313
+ window.addEventListener("pointercancel", this.handlePointerUp, {
2314
+ once: true
2315
+ });
2316
+ }
2317
+ removeDragListeners() {
2318
+ window.removeEventListener("pointermove", this.handlePointerMove);
2319
+ window.removeEventListener("pointerup", this.handlePointerUp);
2320
+ window.removeEventListener("pointercancel", this.handlePointerUp);
2321
+ }
2322
+ }
2323
+ function getInnerOptions(options) {
2324
+ return removeMethods(options);
2325
+ }
2326
+ function requireCommandCapability(value, context) {
2327
+ const command = String(context.name);
2328
+ return function(...args) {
2329
+ if (!this.capabilities.commands.has(command)) {
2330
+ throw new IntegrationError2(
2331
+ `ChatKit command "${String(command)}" is not available for the "${this.profile}" profile.`
2332
+ );
2333
+ }
2334
+ return value.apply(this, args);
2335
+ };
2336
+ }
2337
+ class ChatKitElementBase extends (_c = HTMLElement, _focusComposer_dec = [requireCommandCapability], _fetchUpdates_dec = [requireCommandCapability], _sendUserMessage_dec = [requireCommandCapability], _setComposerValue_dec = [requireCommandCapability], _setThreadId_dec = [requireCommandCapability], _shareThread_dec = [requireCommandCapability], _sendCustomAction_dec = [requireCommandCapability], _showHistory_dec = [requireCommandCapability], _hideHistory_dec = [requireCommandCapability], _setTrainingOptOut_dec = [requireCommandCapability], _c) {
2338
+ constructor({ profile }) {
2339
+ super();
2340
+ __runInitializers(_init, 5, this);
2341
+ __privateAdd(this, _ChatKitElementBase_instances);
2342
+ __privateAdd(this, _opts);
2343
+ __privateAdd(this, _frameUrl);
2344
+ __privateAdd(this, _frame);
2345
+ __privateAdd(this, _wrapper);
2346
+ __privateAdd(this, _launcherCloseButton);
2347
+ __privateAdd(this, _launcherOpen, false);
2348
+ __privateAdd(this, _chatMinimizedToPet, false);
2349
+ __privateAdd(this, _framePetOptionsOverride);
2350
+ __privateAdd(this, _petClosedByContextMenu, false);
2351
+ __privateAdd(this, _shadow, this.attachShadow({ mode: "open" }));
2352
+ __privateAdd(this, _petOverlay, new PetOverlay(__privateGet(this, _shadow), {
2353
+ onActivate: () => __privateMethod(this, _ChatKitElementBase_instances, handlePetActivate_fn).call(this),
2354
+ onClose: () => __privateMethod(this, _ChatKitElementBase_instances, handlePetClose_fn).call(this),
2355
+ onReply: (text) => __privateMethod(this, _ChatKitElementBase_instances, handlePetReply_fn).call(this, text),
2356
+ onThreadSummaryActivate: (threadId) => void __privateMethod(this, _ChatKitElementBase_instances, handlePetThreadSummaryActivate_fn).call(this, threadId)
2357
+ }));
2358
+ __privateAdd(this, _resolveLoaded);
2359
+ __privateAdd(this, _loaded, new Promise((resolve) => {
2360
+ __privateSet(this, _resolveLoaded, resolve);
2361
+ }));
2362
+ __privateAdd(this, _messenger, new ChatFrameMessenger({
2363
+ fetch: (...args) => {
2364
+ var _a2;
2365
+ const customFetch = ((_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.api) && "fetch" in __privateGet(this, _opts).api && __privateGet(this, _opts).api.fetch;
2366
+ return customFetch ? customFetch(...args) : fetch(...args);
2367
+ },
2368
+ target: () => {
2369
+ var _a2;
2370
+ return ((_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.contentWindow) ?? null;
2371
+ },
2372
+ targetOrigin: window.location.origin,
2373
+ handlers: {
2374
+ onFileInputClick: ({
2375
+ inputAttributes
2376
+ }) => {
2377
+ return new Promise((resolve) => {
2378
+ const input = document.createElement("input");
2379
+ for (const [key, value] of Object.entries(inputAttributes)) {
2380
+ input.setAttribute(key, String(value));
2381
+ }
2382
+ const respond = () => {
2383
+ resolve(Array.from(input.files || []));
2384
+ if (__privateGet(this, _shadow).contains(input)) {
2385
+ __privateGet(this, _shadow).removeChild(input);
2386
+ }
2387
+ };
2388
+ input.addEventListener("cancel", respond);
2389
+ input.addEventListener("change", respond);
2390
+ __privateGet(this, _shadow).appendChild(input);
2391
+ input.click();
2392
+ });
2393
+ },
2394
+ onClientToolCall: async ({
2395
+ name,
2396
+ params,
2397
+ id,
2398
+ tool_call_id
2399
+ }) => {
2400
+ var _a2;
2401
+ const onClientTool = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.onClientTool;
2402
+ if (!onClientTool) {
2403
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
2404
+ `No handler for client tool calls. You'll need to add onClientTool to your ChatKit options.`
2405
+ ));
2406
+ }
2407
+ return onClientTool({ name, params, id, tool_call_id });
2408
+ },
2409
+ onWidgetAction: async ({
2410
+ action,
2411
+ widgetItem
2412
+ }) => {
2413
+ var _a2, _b2;
2414
+ const onAction = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.widgets) == null ? void 0 : _b2.onAction;
2415
+ if (!onAction) {
2416
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
2417
+ `No handler for widget actions. You'll need to add widgets.onAction to your ChatKit options.`
2418
+ ));
2419
+ }
2420
+ return onAction(action, widgetItem);
2421
+ },
2422
+ onEntitySearch: async ({ query }) => {
2423
+ var _a2, _b2, _c2;
2424
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onTagSearch) == null ? void 0 : _c2.call(_b2, query)) ?? [];
2425
+ },
2426
+ onEntityClick: async ({ entity }) => {
2427
+ var _a2, _b2, _c2;
2428
+ return (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onClick) == null ? void 0 : _c2.call(_b2, entity);
2429
+ },
2430
+ onEntityPreview: async ({ entity }) => {
2431
+ var _a2, _b2, _c2;
2432
+ return ((_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.entities) == null ? void 0 : _b2.onRequestPreview) == null ? void 0 : _c2.call(_b2, entity)) ?? { preview: null };
2433
+ },
2434
+ onGetClientSecret: async (currentClientSecret) => {
2435
+ if (!__privateGet(this, _opts) || !("getClientSecret" in __privateGet(this, _opts).api) || !__privateGet(this, _opts).api.getClientSecret) {
2436
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, new IntegrationError2(
2437
+ "Could not refresh the session because ChatKitOptions.api.getClientSecret is not configured."
2438
+ ));
2439
+ }
2440
+ return __privateGet(this, _opts).api.getClientSecret(currentClientSecret ?? null);
2441
+ },
2442
+ onAddMetadataToRequest: ({
2443
+ op,
2444
+ params
2445
+ }) => {
2446
+ throw new IntegrationError2(
2447
+ "ChatKit: onAddMetadataToRequest is unimplemented."
2448
+ );
2449
+ }
2450
+ }
2451
+ }));
2452
+ __privateAdd(this, _handleLauncherClose, () => {
2453
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2454
+ });
2455
+ __privateAdd(this, _handleFrameLoad, () => {
2456
+ var _a2;
2457
+ this.dataset.loaded = "true";
2458
+ this.dispatchEvent(
2459
+ new CustomEvent("chatkit.ready", { bubbles: true, composed: true })
2460
+ );
2461
+ (_a2 = __privateGet(this, _resolveLoaded)) == null ? void 0 : _a2.call(this);
2462
+ });
2463
+ __privateAdd(this, _initialized, false);
2464
+ this.profile = profile;
2465
+ this.capabilities = getCapabilities(profile);
2466
+ }
2467
+ setProfile(profile) {
2468
+ this.profile = profile;
2469
+ this.capabilities = getCapabilities(profile);
2470
+ }
2471
+ connectedCallback() {
2472
+ __privateGet(this, _petOverlay).connect();
2473
+ const style = document.createElement("style");
2474
+ style.textContent = `
2475
+ :host {
2476
+ display: block;
2477
+ position: relative;
2478
+ height: 100%;
2479
+ width: 100%;
2480
+ overflow: visible;
2481
+ }
2482
+ :host([data-display-mode="pet"]) {
2483
+ display: contents;
2484
+ }
2485
+ :host([data-chat-minimized-to-pet="true"]) {
2486
+ display: contents;
2487
+ }
2488
+ .ck-iframe {
2489
+ border: none;
2490
+ position: absolute;
2491
+ inset: 0;
2492
+ width: 100%;
2493
+ height: 100%;
2494
+ overflow: hidden;
2495
+ color-scheme: light only;
2496
+ }
2497
+ .ck-wrapper {
2498
+ position: absolute;
2499
+ inset: 0;
2500
+ width: 100%;
2501
+ height: 100%;
2502
+ overflow: hidden;
2503
+ opacity: 0;
2504
+ }
2505
+ .ck-launcher-close {
2506
+ display: none;
2507
+ }
2508
+ :host([data-display-mode="pet"]) .ck-wrapper {
2509
+ position: fixed;
2510
+ inset: auto 16px 16px auto;
2511
+ width: min(420px, calc(100vw - 32px));
2512
+ height: min(720px, calc(100vh - 32px));
2513
+ max-height: calc(100vh - 32px);
2514
+ overflow: visible;
2515
+ border: 1px solid rgba(148, 163, 184, 0.35);
2516
+ border-radius: 18px;
2517
+ background: Canvas;
2518
+ box-shadow:
2519
+ 0 24px 80px rgba(15, 23, 42, 0.22),
2520
+ 0 0 0 1px rgba(15, 23, 42, 0.04);
2521
+ opacity: 0;
2522
+ pointer-events: none;
2523
+ transform: translateY(12px) scale(0.98);
2524
+ transition:
2525
+ opacity 160ms ease,
2526
+ transform 160ms ease;
2527
+ z-index: 39;
2528
+ }
2529
+ :host([data-display-mode="pet"][data-chat-open="true"]) .ck-wrapper {
2530
+ opacity: 1;
2531
+ pointer-events: auto;
2532
+ transform: translateY(0) scale(1);
2533
+ }
2534
+ :host([data-display-mode="pet"]) .ck-iframe {
2535
+ border-radius: inherit;
2536
+ }
2537
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2538
+ display: inline-flex;
2539
+ position: absolute;
2540
+ top: -10px;
2541
+ right: -10px;
2542
+ z-index: 2;
2543
+ width: 28px;
2544
+ height: 28px;
2545
+ align-items: center;
2546
+ justify-content: center;
2547
+ border: 1px solid rgba(148, 163, 184, 0.45);
2548
+ border-radius: 999px;
2549
+ background: rgba(255, 255, 255, 0.96);
2550
+ color: #475569;
2551
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
2552
+ cursor: pointer;
2553
+ font: inherit;
2554
+ font-size: 0;
2555
+ line-height: 1;
2556
+ }
2557
+ :host([data-display-mode="pet"]) .ck-launcher-close::before,
2558
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2559
+ content: '';
2560
+ position: absolute;
2561
+ top: 50%;
2562
+ left: 50%;
2563
+ width: 14px;
2564
+ height: 2px;
2565
+ border-radius: 999px;
2566
+ background: currentColor;
2567
+ transform: translate(-50%, -50%) rotate(45deg);
2568
+ }
2569
+ :host([data-display-mode="pet"]) .ck-launcher-close::after {
2570
+ transform: translate(-50%, -50%) rotate(-45deg);
2571
+ }
2572
+ :host([data-display-mode="pet"]) .ck-launcher-close:hover {
2573
+ background: #fff;
2574
+ color: #0f172a;
2575
+ }
2576
+ :host([data-color-scheme="dark"]) .ck-iframe {
2577
+ color-scheme: dark only;
2578
+ }
2579
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-wrapper {
2580
+ border-color: rgba(148, 163, 184, 0.28);
2581
+ background: #020617;
2582
+ box-shadow:
2583
+ 0 24px 80px rgba(0, 0, 0, 0.5),
2584
+ 0 0 0 1px rgba(255, 255, 255, 0.06);
2585
+ }
2586
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close {
2587
+ background: rgba(15, 23, 42, 0.88);
2588
+ border-color: rgba(148, 163, 184, 0.32);
2589
+ color: #cbd5e1;
2590
+ }
2591
+ :host([data-color-scheme="dark"][data-display-mode="pet"]) .ck-launcher-close:hover {
2592
+ background: #1e293b;
2593
+ color: #f8fafc;
2594
+ }
2595
+ :host([data-loaded="true"]) .ck-wrapper {
2596
+ opacity: 1;
2597
+ }
2598
+ :host([data-chat-minimized-to-pet="true"]) .ck-wrapper {
2599
+ opacity: 0;
2600
+ pointer-events: none;
2601
+ visibility: hidden;
2602
+ }
2603
+ :host([data-display-mode="pet"]:not([data-chat-open="true"])) .ck-wrapper {
2604
+ opacity: 0;
2605
+ }
2606
+ @media (max-width: 520px) {
2607
+ :host([data-display-mode="pet"]) .ck-wrapper {
2608
+ inset: auto 8px 8px 8px;
2609
+ width: auto;
2610
+ height: min(680px, calc(100vh - 16px));
2611
+ max-height: calc(100vh - 16px);
2612
+ border-radius: 16px;
2613
+ }
2614
+ :host([data-display-mode="pet"]) .ck-launcher-close {
2615
+ top: -8px;
2616
+ right: 8px;
2617
+ }
2618
+ }
2619
+ `;
2620
+ const frame = document.createElement("iframe");
2621
+ frame.className = "ck-iframe";
2622
+ frame.name = "chatkit";
2623
+ frame.role = "presentation";
2624
+ frame.tabIndex = 0;
2625
+ frame.setAttribute("allowtransparency", "true");
2626
+ frame.setAttribute("frameborder", "0");
2627
+ frame.setAttribute("scrolling", "no");
2628
+ frame.setAttribute("allow", "clipboard-read; clipboard-write");
2629
+ __privateSet(this, _frame, frame);
2630
+ const wrapper = document.createElement("div");
2631
+ wrapper.className = "ck-wrapper";
2632
+ wrapper.appendChild(frame);
2633
+ __privateSet(this, _wrapper, wrapper);
2634
+ const closeButton = document.createElement("button");
2635
+ closeButton.className = "ck-launcher-close";
2636
+ closeButton.type = "button";
2637
+ closeButton.setAttribute("aria-label", "Close chat");
2638
+ closeButton.addEventListener("click", __privateGet(this, _handleLauncherClose));
2639
+ wrapper.appendChild(closeButton);
2640
+ __privateSet(this, _launcherCloseButton, closeButton);
2641
+ __privateGet(this, _shadow).append(style);
2642
+ __privateGet(this, _messenger).on("left_header_icon_click", () => {
2643
+ var _a2, _b2, _c2;
2644
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.leftAction) == null ? void 0 : _c2.onClick();
2645
+ });
2646
+ __privateGet(this, _messenger).on("right_header_icon_click", () => {
2647
+ var _a2, _b2, _c2;
2648
+ (_c2 = (_b2 = (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.header) == null ? void 0 : _b2.rightAction) == null ? void 0 : _c2.onClick();
2649
+ });
2650
+ __privateGet(this, _messenger).on("public_event", ([event, data]) => {
2651
+ if (event === "log") {
2652
+ const payload = parseThreadSummaryLogPayload(data);
2653
+ if (payload) {
2654
+ __privateGet(this, _petOverlay).setThreadSummary(payload.summary);
2655
+ }
2656
+ } else if (event === "response.start") {
2657
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("running");
2658
+ } else if (event === "response.end") {
2659
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2660
+ } else if (event === "response.stop") {
2661
+ __privateGet(this, _petOverlay).setThreadSummaryStatus("completed");
2662
+ }
2663
+ if (!this.capabilities.events.has(event)) return;
2664
+ if (event === "error" && "error" in data) {
2665
+ const error = fromPossibleFrameSafeError(data.error);
2666
+ this.dispatchEvent(
2667
+ new CustomEvent("chatkit.error", { detail: { error } })
2668
+ );
2669
+ if (error instanceof IntegrationError2) {
2670
+ throw error;
2671
+ }
2672
+ return;
2673
+ }
2674
+ this.dispatchEvent(new CustomEvent(`chatkit.${event}`, { detail: data }));
2675
+ });
2676
+ __privateGet(this, _messenger).on("pet_state_change", (data) => {
2677
+ const payload = parsePetStateChangePayload(data);
2678
+ if (payload) {
2679
+ __privateGet(this, _petOverlay).setState(payload.state);
2680
+ }
2681
+ });
2682
+ __privateGet(this, _messenger).on("pet_options_change", (data) => {
2683
+ const payload = parsePetOptionsChangePayload(data);
2684
+ if (payload) {
2685
+ if (!__privateGet(this, _petClosedByContextMenu) || payload.pet === null) {
2686
+ __privateSet(this, _petClosedByContextMenu, false);
2687
+ }
2688
+ __privateSet(this, _framePetOptionsOverride, payload.pet);
2689
+ __privateMethod(this, _ChatKitElementBase_instances, syncPetOverlayOptions_fn).call(this);
2690
+ }
2691
+ });
2692
+ __privateGet(this, _messenger).on("chat_minimize_change", (data) => {
2693
+ const minimized = typeof data === "object" && data !== null && "minimized" in data && data.minimized === true;
2694
+ if (minimized && !__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this)) {
2695
+ return;
2696
+ }
2697
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, minimized);
2698
+ if (minimized) {
2699
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2700
+ }
2701
+ });
2702
+ __privateGet(this, _messenger).on("unmount", () => {
2703
+ if (__privateGet(this, _wrapper) && __privateGet(this, _shadow).contains(__privateGet(this, _wrapper))) {
2704
+ __privateGet(this, _shadow).removeChild(__privateGet(this, _wrapper));
2705
+ __privateSet(this, _wrapper, void 0);
2706
+ __privateSet(this, _frame, void 0);
2707
+ }
2708
+ });
2709
+ __privateGet(this, _messenger).on(
2710
+ "capabilities_profile_change",
2711
+ ({ profile }) => {
2712
+ this.setProfile(profile);
2713
+ }
2714
+ );
2715
+ frame.addEventListener("load", __privateGet(this, _handleFrameLoad), { once: true });
2716
+ try {
2717
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2718
+ } catch (error) {
2719
+ console.error(error);
2720
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError2("Failed to initialize ChatKit"));
2721
+ }
2722
+ }
2723
+ disconnectedCallback() {
2724
+ var _a2, _b2;
2725
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.removeEventListener("load", __privateGet(this, _handleFrameLoad));
2726
+ (_b2 = __privateGet(this, _launcherCloseButton)) == null ? void 0 : _b2.removeEventListener(
2727
+ "click",
2728
+ __privateGet(this, _handleLauncherClose)
2729
+ );
2730
+ __privateGet(this, _messenger).disconnect();
2731
+ __privateGet(this, _petOverlay).destroy();
2732
+ }
2733
+ applySanitizedOptions(newOptions) {
2734
+ __privateSet(this, _opts, newOptions);
2735
+ __privateSet(this, _petClosedByContextMenu, false);
2736
+ __privateGet(this, _petOverlay).setLocale(newOptions.locale);
2737
+ __privateMethod(this, _ChatKitElementBase_instances, syncPetOverlayOptions_fn).call(this);
2738
+ if (__privateGet(this, _initialized)) {
2739
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
2740
+ __privateGet(this, _loaded).then(() => {
2741
+ __privateGet(this, _messenger).commands.setOptions(
2742
+ getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, newOptions))
2743
+ );
2744
+ });
2745
+ } else {
2746
+ __privateMethod(this, _ChatKitElementBase_instances, maybeInit_fn).call(this);
2747
+ }
2748
+ }
2749
+ setOptions(newOptions) {
2750
+ try {
2751
+ const sanitized = this.sanitizeOptions(newOptions);
2752
+ __privateMethod(this, _ChatKitElementBase_instances, consumeFrameUrl_fn).call(this, sanitized);
2753
+ this.applySanitizedOptions(sanitized);
2754
+ } catch (error) {
2755
+ __privateMethod(this, _ChatKitElementBase_instances, emitAndThrow_fn).call(this, error instanceof Error ? error : new IntegrationError2("Failed to parse options"));
2756
+ }
2757
+ }
2758
+ async focusComposer() {
2759
+ var _a2, _b2;
2760
+ await __privateGet(this, _loaded);
2761
+ (_a2 = __privateGet(this, _frame)) == null ? void 0 : _a2.focus();
2762
+ await ((_b2 = __privateGet(this, _messenger)) == null ? void 0 : _b2.commands.focusComposer());
2763
+ }
2764
+ async fetchUpdates() {
2765
+ var _a2;
2766
+ await __privateGet(this, _loaded);
2767
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.fetchUpdates());
2768
+ }
2769
+ async sendUserMessage(params) {
2770
+ var _a2;
2771
+ await __privateGet(this, _loaded);
2772
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendUserMessage(params));
2773
+ }
2774
+ async setComposerValue(params) {
2775
+ var _a2;
2776
+ await __privateGet(this, _loaded);
2777
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setComposerValue(params));
2778
+ }
2779
+ async setThreadId(threadId) {
2780
+ var _a2;
2781
+ await __privateGet(this, _loaded);
2782
+ await ((_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setThreadId({ threadId }));
2783
+ }
2784
+ async shareThread() {
2785
+ var _a2;
2786
+ await __privateGet(this, _loaded);
2787
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.shareThread();
2788
+ }
2789
+ async sendCustomAction(action, itemId) {
2790
+ var _a2;
2791
+ await __privateGet(this, _loaded);
2792
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.sendCustomAction({ action, itemId });
2793
+ }
2794
+ async showHistory() {
2795
+ var _a2;
2796
+ await __privateGet(this, _loaded);
2797
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.showHistory();
2798
+ }
2799
+ async hideHistory() {
2800
+ var _a2;
2801
+ await __privateGet(this, _loaded);
2802
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.hideHistory();
2803
+ }
2804
+ async setTrainingOptOut(value) {
2805
+ var _a2;
2806
+ await __privateGet(this, _loaded);
2807
+ return (_a2 = __privateGet(this, _messenger)) == null ? void 0 : _a2.commands.setTrainingOptOut({ value });
2808
+ }
2809
+ }
2810
+ _init = __decoratorStart(_c);
2811
+ _opts = new WeakMap();
2812
+ _frameUrl = new WeakMap();
2813
+ _frame = new WeakMap();
2814
+ _wrapper = new WeakMap();
2815
+ _launcherCloseButton = new WeakMap();
2816
+ _launcherOpen = new WeakMap();
2817
+ _chatMinimizedToPet = new WeakMap();
2818
+ _framePetOptionsOverride = new WeakMap();
2819
+ _petClosedByContextMenu = new WeakMap();
2820
+ _shadow = new WeakMap();
2821
+ _petOverlay = new WeakMap();
2822
+ _resolveLoaded = new WeakMap();
2823
+ _loaded = new WeakMap();
2824
+ _messenger = new WeakMap();
2825
+ _ChatKitElementBase_instances = new WeakSet();
2826
+ emitAndThrow_fn = function(error) {
2827
+ this.dispatchEvent(new CustomEvent("chatkit.error", { detail: { error } }));
2828
+ throw error;
2829
+ };
2830
+ setOptionsDataAttributes_fn = function(options) {
2831
+ var _a2;
2832
+ this.dataset.colorScheme = typeof options.theme === "string" ? options.theme : ((_a2 = options.theme) == null ? void 0 : _a2.colorScheme) ?? "light";
2833
+ this.dataset.displayMode = __privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options);
2834
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) !== "pet") {
2835
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2836
+ }
2837
+ };
2838
+ getDisplayMode_fn = function(options = __privateGet(this, _opts)) {
2839
+ return (options == null ? void 0 : options.displayMode) === "pet" ? "pet" : "chat";
2840
+ };
2841
+ getConfiguredPetOptions_fn = function(options = __privateGet(this, _opts)) {
2842
+ if (!options) {
2843
+ return null;
2844
+ }
2845
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this, options) === "pet" && !chatkitTypes.normalizePetOptions(options.pet ?? null)) {
2846
+ return true;
2847
+ }
2848
+ return options.pet ?? null;
2849
+ };
2850
+ mergeConfiguredPetPositionDefaults_fn = function(pet) {
2851
+ if (!pet) {
2852
+ return pet;
2853
+ }
2854
+ const configured = chatkitTypes.normalizePetOptions(
2855
+ __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this) ?? null
2856
+ );
2857
+ if (!configured) {
2858
+ return pet;
2859
+ }
2860
+ if (pet === true) {
2861
+ return { position: configured.position };
2862
+ }
2863
+ if (!pet.position) {
2864
+ return { ...pet, position: configured.position };
2865
+ }
2866
+ return {
2867
+ ...pet,
2868
+ position: {
2869
+ ...configured.position,
2870
+ ...pet.position,
2871
+ boundsPadding: pet.position.boundsPadding ?? configured.position.boundsPadding,
2872
+ pin: "pin" in pet.position ? pet.position.pin : configured.position.pin
2873
+ }
2874
+ };
2875
+ };
2876
+ getOverlayPetOptions_fn = function() {
2877
+ if (__privateGet(this, _petClosedByContextMenu)) {
2878
+ return null;
2879
+ }
2880
+ let pet;
2881
+ if (__privateGet(this, _framePetOptionsOverride) !== void 0) {
2882
+ pet = __privateMethod(this, _ChatKitElementBase_instances, mergeConfiguredPetPositionDefaults_fn).call(this, __privateGet(this, _framePetOptionsOverride));
2883
+ } else {
2884
+ pet = __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this);
2885
+ }
2886
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet" && !chatkitTypes.normalizePetOptions(pet ?? null)) {
2887
+ pet = true;
2888
+ }
2889
+ return __privateMethod(this, _ChatKitElementBase_instances, resolveOverlayPetOptions_fn).call(this, pet);
2890
+ };
2891
+ resolvePetAssetUrl_fn = function(src) {
2892
+ try {
2893
+ const base = new URL(
2894
+ __privateGet(this, _frameUrl) ?? window.location.href,
2895
+ window.location.origin
2896
+ );
2897
+ return new URL(src, base).toString();
2898
+ } catch {
2899
+ return src;
2900
+ }
2901
+ };
2902
+ resolveOverlayPetOptions_fn = function(pet) {
2903
+ const normalized = chatkitTypes.normalizePetOptions(pet ?? null);
2904
+ if (!normalized) {
2905
+ return null;
2906
+ }
2907
+ return {
2908
+ character: {
2909
+ ...normalized.character,
2910
+ src: __privateMethod(this, _ChatKitElementBase_instances, resolvePetAssetUrl_fn).call(this, normalized.character.src)
2911
+ },
2912
+ position: normalized.position,
2913
+ behavior: normalized.behavior,
2914
+ ariaLabel: normalized.ariaLabel,
2915
+ imageRendering: normalized.imageRendering
2916
+ };
2917
+ };
2918
+ getFrameOptions_fn = function(options) {
2919
+ const pet = __privateMethod(this, _ChatKitElementBase_instances, getConfiguredPetOptions_fn).call(this, options);
2920
+ if (pet === (options.pet ?? null)) {
2921
+ return options;
2922
+ }
2923
+ const nextOptions = { ...options };
2924
+ if (pet === null) {
2925
+ delete nextOptions.pet;
2926
+ } else {
2927
+ nextOptions.pet = pet;
2928
+ }
2929
+ return nextOptions;
2930
+ };
2931
+ setLauncherOpen_fn = function(open) {
2932
+ __privateSet(this, _launcherOpen, open);
2933
+ if (open) {
2934
+ this.dataset.chatOpen = "true";
2935
+ } else {
2936
+ delete this.dataset.chatOpen;
2937
+ }
2938
+ };
2939
+ setChatMinimizedToPet_fn = function(minimized) {
2940
+ const next = minimized && Boolean(__privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this));
2941
+ __privateSet(this, _chatMinimizedToPet, next);
2942
+ if (next) {
2943
+ this.dataset.chatMinimizedToPet = "true";
2944
+ } else {
2945
+ delete this.dataset.chatMinimizedToPet;
2946
+ }
2947
+ };
2948
+ syncPetOverlayOptions_fn = function() {
2949
+ var _a2;
2950
+ const overlayPetOptions = __privateMethod(this, _ChatKitElementBase_instances, getOverlayPetOptions_fn).call(this);
2951
+ __privateGet(this, _petOverlay).setOptions(overlayPetOptions, (_a2 = __privateGet(this, _opts)) == null ? void 0 : _a2.theme);
2952
+ if (!overlayPetOptions) {
2953
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2954
+ }
2955
+ };
2956
+ handlePetActivate_fn = function() {
2957
+ if (__privateGet(this, _chatMinimizedToPet)) {
2958
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2959
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2960
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2961
+ }
2962
+ __privateGet(this, _loaded).then(() => this.focusComposer()).catch(() => void 0);
2963
+ return;
2964
+ }
2965
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) !== "pet") {
2966
+ return;
2967
+ }
2968
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2969
+ __privateGet(this, _loaded).then(() => this.focusComposer()).catch(() => void 0);
2970
+ };
2971
+ handlePetClose_fn = function() {
2972
+ __privateSet(this, _petClosedByContextMenu, true);
2973
+ __privateSet(this, _framePetOptionsOverride, null);
2974
+ __privateMethod(this, _ChatKitElementBase_instances, setChatMinimizedToPet_fn).call(this, false);
2975
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, false);
2976
+ __privateGet(this, _petOverlay).setOptions(null);
2977
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2978
+ return;
2979
+ }
2980
+ __privateGet(this, _loaded).then(() => __privateGet(this, _messenger).commands.setPetEnabled({ enabled: false })).catch(() => void 0);
2981
+ };
2982
+ handlePetReply_fn = async function(text) {
2983
+ await this.sendUserMessage({ text });
2984
+ };
2985
+ handlePetThreadSummaryActivate_fn = async function(threadId) {
2986
+ if (__privateMethod(this, _ChatKitElementBase_instances, getDisplayMode_fn).call(this) === "pet") {
2987
+ __privateMethod(this, _ChatKitElementBase_instances, setLauncherOpen_fn).call(this, true);
2988
+ }
2989
+ await this.setThreadId(threadId);
2990
+ await this.focusComposer();
2991
+ };
2992
+ _handleLauncherClose = new WeakMap();
2993
+ getFrameUrl_fn = function() {
2994
+ if (!__privateGet(this, _frameUrl)) {
2995
+ throw new IntegrationError2(
2996
+ "ChatKit frameUrl is not configured. Provide it via setOptions({ frameUrl }) before mounting."
2997
+ );
2998
+ }
2999
+ return __privateGet(this, _frameUrl);
3000
+ };
3001
+ setFrameUrl_fn = function(frameUrl) {
3002
+ if (__privateGet(this, _initialized) && __privateGet(this, _frameUrl) && __privateGet(this, _frameUrl) !== frameUrl) {
3003
+ throw new IntegrationError2(
3004
+ "ChatKit frameUrl cannot be changed after initialization. Create a new element to use a different URL."
3005
+ );
3006
+ }
3007
+ __privateSet(this, _frameUrl, frameUrl);
3008
+ };
3009
+ consumeFrameUrl_fn = function(options) {
3010
+ if (!("frameUrl" in options)) return;
3011
+ const frameUrl = options.frameUrl;
3012
+ delete options.frameUrl;
3013
+ if (frameUrl == null) return;
3014
+ if (typeof frameUrl !== "string" || frameUrl.trim() === "") {
3015
+ throw new IntegrationError2(
3016
+ "ChatKit frameUrl must be a non-empty string."
3017
+ );
3018
+ }
3019
+ __privateMethod(this, _ChatKitElementBase_instances, setFrameUrl_fn).call(this, frameUrl);
3020
+ };
3021
+ _handleFrameLoad = new WeakMap();
3022
+ _initialized = new WeakMap();
3023
+ maybeInit_fn = function() {
3024
+ if (__privateGet(this, _initialized) || !__privateGet(this, _frame) || !__privateGet(this, _opts)) {
3025
+ return;
3026
+ }
3027
+ __privateSet(this, _initialized, true);
3028
+ __privateMethod(this, _ChatKitElementBase_instances, setOptionsDataAttributes_fn).call(this, __privateGet(this, _opts));
3029
+ const frameURL = new URL(__privateMethod(this, _ChatKitElementBase_instances, getFrameUrl_fn).call(this), window.location.origin);
3030
+ __privateGet(this, _messenger).setTargetOrigin(frameURL.origin);
3031
+ frameURL.hash = encodeBase64({
3032
+ options: getInnerOptions(__privateMethod(this, _ChatKitElementBase_instances, getFrameOptions_fn).call(this, __privateGet(this, _opts))),
3033
+ referrer: window.location.origin,
3034
+ profile: this.profile
3035
+ });
3036
+ __privateGet(this, _messenger).connect();
3037
+ __privateGet(this, _frame).src = frameURL.toString();
3038
+ if (__privateGet(this, _wrapper)) {
3039
+ __privateGet(this, _shadow).append(__privateGet(this, _wrapper));
3040
+ }
3041
+ };
3042
+ __decorateElement(_init, 1, "focusComposer", _focusComposer_dec, ChatKitElementBase);
3043
+ __decorateElement(_init, 1, "fetchUpdates", _fetchUpdates_dec, ChatKitElementBase);
3044
+ __decorateElement(_init, 1, "sendUserMessage", _sendUserMessage_dec, ChatKitElementBase);
3045
+ __decorateElement(_init, 1, "setComposerValue", _setComposerValue_dec, ChatKitElementBase);
3046
+ __decorateElement(_init, 1, "setThreadId", _setThreadId_dec, ChatKitElementBase);
3047
+ __decorateElement(_init, 1, "shareThread", _shareThread_dec, ChatKitElementBase);
3048
+ __decorateElement(_init, 1, "sendCustomAction", _sendCustomAction_dec, ChatKitElementBase);
3049
+ __decorateElement(_init, 1, "showHistory", _showHistory_dec, ChatKitElementBase);
3050
+ __decorateElement(_init, 1, "hideHistory", _hideHistory_dec, ChatKitElementBase);
3051
+ __decorateElement(_init, 1, "setTrainingOptOut", _setTrainingOptOut_dec, ChatKitElementBase);
3052
+ __decoratorMetadata(_init, ChatKitElementBase);
3053
+ class ChatKitElement extends ChatKitElementBase {
3054
+ constructor() {
3055
+ super({ profile: "chatkit" });
3056
+ }
3057
+ sanitizeOptions(options) {
3058
+ var _a2;
3059
+ (_a2 = options.threadItemActions) == null ? true : delete _a2.share;
3060
+ return options;
3061
+ }
3062
+ }
3063
+ function registerChatKitElement(tag = "xpertai-chatkit") {
3064
+ if (!("customElements" in globalThis)) return;
3065
+ if (!customElements.get(tag)) {
3066
+ customElements.define(tag, ChatKitElement);
3067
+ }
3068
+ }
3069
+ registerChatKitElement();
3
3070
  const EXCLUDED_HANDLER_KEYS = /* @__PURE__ */ new Set(["onClientTool"]);
4
3071
  const EVENT_HANDLER_MAP = {
5
3072
  "chatkit.error": "onError",
@@ -64,8 +3131,8 @@ function applyOptions(el, options, isCurrent) {
64
3131
  };
65
3132
  }
66
3133
  function getControlBase() {
67
- var _a, _b;
68
- if ((_b = (_a = sap == null ? void 0 : sap.ui) == null ? void 0 : _a.core) == null ? void 0 : _b.Control) {
3134
+ var _a2, _b2;
3135
+ if ((_b2 = (_a2 = sap == null ? void 0 : sap.ui) == null ? void 0 : _a2.core) == null ? void 0 : _b2.Control) {
69
3136
  return sap.ui.core.Control;
70
3137
  }
71
3138
  throw new Error("sap.ui.core.Control is required for @xpert-ai/chatkit-ui5");
@@ -161,10 +3228,10 @@ const ChatKit = ControlBase.extend("xpertai.chatkit.ui5.ChatKit", {
161
3228
  el.addEventListener(
162
3229
  eventName,
163
3230
  (e) => {
164
- var _a;
3231
+ var _a2;
165
3232
  const detail = e.detail;
166
3233
  const handlerName = EVENT_HANDLER_MAP[eventName];
167
- const handler = (_a = this._handlers) == null ? void 0 : _a[handlerName];
3234
+ const handler = (_a2 = this._handlers) == null ? void 0 : _a2[handlerName];
168
3235
  if (typeof handler === "function") {
169
3236
  handler(detail);
170
3237
  }