@lichen-ai/chatkit-web-component 0.4.0

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