@lichen-ai/chatkit-web-component 0.3.5

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