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