@athoscommerce/snap-store-mobx 1.5.1-beta.114 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cjs/Autocomplete/Stores/AutocompleteFacetStore.js +1 -2
  2. package/dist/cjs/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  3. package/dist/cjs/Search/Stores/SearchFacetStore.js +10 -13
  4. package/dist/cjs/Search/Stores/SearchResultStore.d.ts.map +1 -1
  5. package/dist/cjs/Search/Stores/SearchResultStore.js +7 -6
  6. package/dist/cjs/Search/Stores/index.d.ts +1 -1
  7. package/dist/cjs/Search/Stores/index.d.ts.map +1 -1
  8. package/dist/cjs/Search/Stores/index.js +1 -2
  9. package/dist/cjs/index.d.ts +0 -4
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js +1 -5
  12. package/dist/cjs/types.d.ts +2 -24
  13. package/dist/cjs/types.d.ts.map +1 -1
  14. package/dist/esm/Autocomplete/Stores/AutocompleteFacetStore.js +1 -1
  15. package/dist/esm/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  16. package/dist/esm/Search/Stores/SearchFacetStore.js +10 -13
  17. package/dist/esm/Search/Stores/SearchResultStore.d.ts.map +1 -1
  18. package/dist/esm/Search/Stores/SearchResultStore.js +7 -6
  19. package/dist/esm/Search/Stores/index.d.ts +1 -1
  20. package/dist/esm/Search/Stores/index.d.ts.map +1 -1
  21. package/dist/esm/Search/Stores/index.js +1 -1
  22. package/dist/esm/index.d.ts +0 -4
  23. package/dist/esm/index.d.ts.map +1 -1
  24. package/dist/esm/index.js +0 -2
  25. package/dist/esm/types.d.ts +2 -24
  26. package/dist/esm/types.d.ts.map +1 -1
  27. package/package.json +5 -5
  28. package/dist/cjs/Chat/ChatStore.d.ts +0 -91
  29. package/dist/cjs/Chat/ChatStore.d.ts.map +0 -1
  30. package/dist/cjs/Chat/ChatStore.js +0 -638
  31. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts +0 -98
  32. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts.map +0 -1
  33. package/dist/cjs/Chat/Stores/ChatAttachmentStore.js +0 -314
  34. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts +0 -16
  35. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts.map +0 -1
  36. package/dist/cjs/Chat/Stores/ChatCompareStore.js +0 -64
  37. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +0 -107
  38. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +0 -1
  39. package/dist/cjs/Chat/Stores/ChatSessionStore.js +0 -644
  40. package/dist/esm/Chat/ChatStore.d.ts +0 -91
  41. package/dist/esm/Chat/ChatStore.d.ts.map +0 -1
  42. package/dist/esm/Chat/ChatStore.js +0 -568
  43. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts +0 -98
  44. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts.map +0 -1
  45. package/dist/esm/Chat/Stores/ChatAttachmentStore.js +0 -222
  46. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts +0 -16
  47. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts.map +0 -1
  48. package/dist/esm/Chat/Stores/ChatCompareStore.js +0 -50
  49. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +0 -107
  50. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +0 -1
  51. package/dist/esm/Chat/Stores/ChatSessionStore.js +0 -609
@@ -1,609 +0,0 @@
1
- import { makeObservable, observable, computed } from 'mobx';
2
- import { v4 as uuidv4 } from 'uuid';
3
- import { ChatAttachmentStore, } from '../Stores/ChatAttachmentStore';
4
- import { ChatCompareStore } from './ChatCompareStore';
5
- import { SearchResultStore, Product } from '../../Search/Stores/SearchResultStore';
6
- function createChatResultStore(results, meta) {
7
- return new SearchResultStore({
8
- config: {},
9
- state: { loaded: true },
10
- data: {
11
- search: { results },
12
- meta,
13
- },
14
- });
15
- }
16
- function createChatProduct(result, meta) {
17
- return new Product({
18
- config: {},
19
- data: { result, meta },
20
- position: 0,
21
- responseId: '',
22
- });
23
- }
24
- /** Extract raw serializable data from a Product instance for storage. */
25
- function serializeProduct(product) {
26
- if (!(product instanceof Product))
27
- return product;
28
- const raw = {
29
- id: product.id,
30
- responseId: product.responseId,
31
- mappings: product.mappings,
32
- attributes: product.attributes,
33
- badges: product.badges?.all?.map((b) => ({ tag: b.tag })) || [],
34
- };
35
- if (product.variants) {
36
- raw.variants = {
37
- data: product.variants.data.map((v) => ({
38
- mappings: v.mappings,
39
- attributes: v.attributes,
40
- options: v.options,
41
- badges: v.badges,
42
- })),
43
- optionConfig: product.variants.optionConfig,
44
- };
45
- }
46
- return raw;
47
- }
48
- /** Serialize attachments for localStorage. Strips base64 from images (kept only at runtime). */
49
- function serializeAttachmentsForStorage(items) {
50
- return items.map((item) => {
51
- if (item.type === 'image') {
52
- return {
53
- type: 'image',
54
- id: item.id,
55
- fileName: item.fileName,
56
- imageId: item.imageId,
57
- imageUrl: item.imageUrl,
58
- thumbnailUrl: item.thumbnailUrl,
59
- state: item.state,
60
- error: item.error,
61
- };
62
- }
63
- if (item.type === 'product') {
64
- return {
65
- type: 'product',
66
- id: item.id,
67
- productId: item.productId,
68
- thumbnailUrl: item.thumbnailUrl,
69
- name: item.name,
70
- requestType: item.requestType,
71
- state: item.state,
72
- error: item.error,
73
- };
74
- }
75
- return {
76
- type: 'facet',
77
- id: item.id,
78
- key: item.key,
79
- facetLabel: item.facetLabel,
80
- value: item.value,
81
- label: item.label,
82
- count: item.count,
83
- state: item.state,
84
- error: item.error,
85
- };
86
- });
87
- }
88
- /** Convert a chat message array to a plain serializable form for localStorage. */
89
- function serializeChatForStorage(chat) {
90
- return chat.map((message) => {
91
- switch (message.messageType) {
92
- case 'productSearchResult': {
93
- const msg = message;
94
- return { ...msg, results: Array.from(msg.results || []).map(serializeProduct) };
95
- }
96
- case 'inspirationResult': {
97
- const msg = message;
98
- return {
99
- ...msg,
100
- inspirationSections: msg.inspirationSections?.map((section) => ({
101
- ...section,
102
- products: Array.from(section.products || []).map(serializeProduct),
103
- })),
104
- };
105
- }
106
- case 'productAnswer': {
107
- const msg = message;
108
- return { ...msg, sourceProduct: serializeProduct(msg.sourceProduct) };
109
- }
110
- case 'productComparison': {
111
- const msg = message;
112
- return { ...msg, searchResults: Array.from(msg.searchResults || []).map(serializeProduct) };
113
- }
114
- case 'productRecommendation': {
115
- const msg = message;
116
- return {
117
- ...msg,
118
- recommendationResult: msg.recommendationResult?.map((rec) => ({
119
- ...rec,
120
- results: Array.from(rec.results || []).map(serializeProduct),
121
- })),
122
- };
123
- }
124
- case 'productQuery': {
125
- const msg = message;
126
- return { ...msg, sourceProduct: serializeProduct(msg.sourceProduct) };
127
- }
128
- default:
129
- return message;
130
- }
131
- });
132
- }
133
- export class ChatSessionStore {
134
- constructor(params) {
135
- this.chat = [];
136
- this.actions = [];
137
- this.attachments = new ChatAttachmentStore();
138
- this.comparisons = new ChatCompareStore();
139
- this.feedbacks = [];
140
- this.sessionFeedback = null;
141
- this.feedbackDismissed = false;
142
- this.feedbackJustGiven = false;
143
- this.createdAt = new Date();
144
- this.requestType = '';
145
- this.dismissedSideChatMessageId = null;
146
- this.activeMessageId = null;
147
- this.sessionLimitReached = false;
148
- /** Whether raw stored results have been hydrated into Product/SearchResultStore instances. */
149
- this.hydrated = true;
150
- this.saveTimerId = null;
151
- const { id, sessionId, chat, attachments, actions, feedbacks, sessionFeedback, feedbackDismissed, createdAt, sessionEndTime, committedComparisons, } = params.data || {};
152
- const { stores } = params;
153
- this.id = id || uuidv4();
154
- this.sessionId = sessionId;
155
- this.storage = stores.storage;
156
- this.actions = actions || [];
157
- this.createdAt = createdAt ? new Date(createdAt) : new Date();
158
- this.sessionEndTime = sessionEndTime ? new Date(sessionEndTime) : undefined;
159
- this.feedbacks = feedbacks || [];
160
- this.sessionFeedback = sessionFeedback || null;
161
- this.feedbackDismissed = feedbackDismissed || false;
162
- // if chat and attachments are passed, load them
163
- if (chat && chat.length > 0) {
164
- // productQuery messages only exist to drive the side-chat panel for an
165
- // in-flight productQuery click; they must not be rehydrated on reload
166
- // or the side chat would re-open without the matching primary-chat state
167
- this.chat = chat.filter((message) => message.messageType !== 'productQuery');
168
- }
169
- if (attachments && attachments.length > 0) {
170
- this.attachments.hydrate(attachments);
171
- // Any attachment already referenced by a sent user message is no longer
172
- // pending — transition it from 'active' to 'saved' so it stops appearing
173
- // in the attachment context bar while remaining available via get(id) for
174
- // rendering inside historical user messages.
175
- const usedAttachmentIds = new Set();
176
- this.chat.forEach((msg) => {
177
- if (msg.messageType === 'user' && msg.attachments) {
178
- msg.attachments.forEach((id) => usedAttachmentIds.add(id));
179
- }
180
- });
181
- this.attachments.items.forEach((item) => {
182
- if ((item.state === 'active' || item.state === 'attached') && usedAttachmentIds.has(item.id)) {
183
- item.save();
184
- }
185
- });
186
- }
187
- // restore committed comparisons only if the thread is still anchored
188
- // to a product comparison — either the last response was a
189
- // productComparison or the user sent a follow-up before a response
190
- // arrived (pending state)
191
- if (committedComparisons && committedComparisons.length > 0) {
192
- const EXCLUDED_MESSAGE_TYPES = ['topicDrift'];
193
- const visibleMessages = this.chat.filter((message) => !EXCLUDED_MESSAGE_TYPES.includes(message.messageType));
194
- const lastMessage = visibleMessages[visibleMessages.length - 1];
195
- if (lastMessage?.messageType === 'productComparison' || lastMessage?.messageType === 'user') {
196
- this.comparisons.committedItems = committedComparisons;
197
- }
198
- }
199
- makeObservable(this, {
200
- chat: observable,
201
- requestType: observable,
202
- actions: observable,
203
- attachments: observable,
204
- feedbacks: observable,
205
- sessionFeedback: observable,
206
- feedbackDismissed: observable,
207
- feedbackJustGiven: observable,
208
- dismissedSideChatMessageId: observable,
209
- activeMessageId: observable,
210
- sessionLimitReached: observable,
211
- activeMessage: computed,
212
- });
213
- }
214
- dismissSideChat() {
215
- // clear the override first so the fallback (last eligible message) is what we
216
- // dismiss — otherwise closing while viewing an older message would leave the
217
- // last message undismissed and the side chat would auto-reopen on it
218
- this.activeMessageId = null;
219
- const fallback = this.activeMessage;
220
- if (fallback) {
221
- this.dismissedSideChatMessageId = fallback.id;
222
- }
223
- }
224
- setActiveMessage(id) {
225
- this.activeMessageId = id;
226
- this.dismissedSideChatMessageId = null;
227
- // Reopening a previous productComparison switches the conversation context
228
- // back to the comparison — drop any lingering 'discuss product' (productQuery)
229
- // attachment so the footer reflects only the comparison products.
230
- const target = this.chat.find((m) => m.id === id);
231
- if (target?.messageType === 'productComparison') {
232
- const productQueryAttachments = this.attachments.attached.filter((item) => item.type === 'product' && item.requestType === 'productQuery');
233
- productQueryAttachments.forEach((item) => this.attachments.remove(item.id));
234
- }
235
- }
236
- pushProductQueryMessage(result) {
237
- // capture the side-chat message that was active at click time so a back action
238
- // can restore it even when it's not the last message in the chat
239
- const sourceMessageId = this.activeMessage?.id;
240
- // drop any trailing productQuery so a fresh productQuery click replaces
241
- // the side-chat target rather than stacking up
242
- while (this.chat.length > 0 && this.chat[this.chat.length - 1]?.messageType === 'productQuery') {
243
- this.chat.pop();
244
- }
245
- this.chat.push({
246
- id: uuidv4(),
247
- messageType: 'productQuery',
248
- sourceProduct: result,
249
- sourceMessageId,
250
- });
251
- // re-show the side chat in case the user previously dismissed it
252
- this.dismissedSideChatMessageId = null;
253
- this.activeMessageId = null;
254
- this.save();
255
- }
256
- popProductQueryMessage(restoreActiveMessageId) {
257
- while (this.chat.length > 0 && this.chat[this.chat.length - 1]?.messageType === 'productQuery') {
258
- this.chat.pop();
259
- }
260
- this.activeMessageId = restoreActiveMessageId || null;
261
- this.save();
262
- }
263
- get isExpired() {
264
- // Prefer the server-provided end time (returned by chatInit); fall back to a
265
- // 24-hour window from createdAt for sessions persisted before that field existed.
266
- if (this.sessionEndTime) {
267
- return Date.now() > this.sessionEndTime.getTime();
268
- }
269
- const ONE_DAY = 24 * 60 * 60 * 1000;
270
- return Date.now() - this.createdAt.getTime() > ONE_DAY;
271
- }
272
- get topicDrift() {
273
- const lastMessage = this.chat[this.chat.length - 1];
274
- return lastMessage?.messageType === 'topicDrift' ? lastMessage : null;
275
- }
276
- get activeMessage() {
277
- const EXCLUDED_MESSAGE_TYPES = ['topicDrift', 'productAnswer'];
278
- if (this.activeMessageId) {
279
- // Walk backward — the override is usually near the end
280
- for (let i = this.chat.length - 1; i >= 0; i--) {
281
- const m = this.chat[i];
282
- if (m.id === this.activeMessageId && !EXCLUDED_MESSAGE_TYPES.includes(m.messageType)) {
283
- return m;
284
- }
285
- }
286
- }
287
- // Find the last eligible message by iterating backwards
288
- let lastMessage = null;
289
- for (let i = this.chat.length - 1; i >= 0; i--) {
290
- if (!EXCLUDED_MESSAGE_TYPES.includes(this.chat[i].messageType)) {
291
- lastMessage = this.chat[i];
292
- break;
293
- }
294
- }
295
- // When the user sends a follow-up while in a productQuery flow (e.g. "discuss product"),
296
- // the last visible message becomes a 'user' message which would close the secondary panel.
297
- // Instead, keep the productQuery message as the active side-chat target so the product
298
- // information panel stays open during and after the request.
299
- if (lastMessage?.messageType === 'user' && this.requestType === 'productQuery') {
300
- for (let i = this.chat.length - 1; i >= 0; i--) {
301
- const m = this.chat[i];
302
- if (m.messageType === 'productQuery' && !EXCLUDED_MESSAGE_TYPES.includes(m.messageType)) {
303
- return m;
304
- }
305
- }
306
- }
307
- return lastMessage || null;
308
- }
309
- dismissTopicDrift() {
310
- this.chat = this.chat.filter((m) => m.messageType !== 'topicDrift');
311
- this.save();
312
- }
313
- handleTopicDrift() {
314
- let lastUserMessage;
315
- for (let i = this.chat.length - 1; i >= 0; i--) {
316
- if (this.chat[i].messageType === 'user') {
317
- lastUserMessage = this.chat[i];
318
- break;
319
- }
320
- }
321
- const messageText = lastUserMessage?.text;
322
- // remove all topicDrift messages and the last user message that triggered the drift
323
- if (lastUserMessage) {
324
- const lastUserIndex = this.chat.lastIndexOf(lastUserMessage);
325
- this.chat = this.chat.slice(0, lastUserIndex);
326
- }
327
- else {
328
- this.chat = this.chat.filter((m) => m.messageType !== 'topicDrift');
329
- }
330
- this.save();
331
- return messageText;
332
- }
333
- reset() {
334
- this.attachments.reset();
335
- this.chat = [];
336
- this.actions = [];
337
- this.feedbacks = [];
338
- this.sessionFeedback = null;
339
- }
340
- /** Persist the session to storage immediately (synchronous). */
341
- saveImmediate() {
342
- if (this.saveTimerId !== null) {
343
- clearTimeout(this.saveTimerId);
344
- this.saveTimerId = null;
345
- }
346
- this.storage.set(`chats.${this.id}`, {
347
- sessionId: this.sessionId,
348
- chat: serializeChatForStorage(this.chat),
349
- attachments: serializeAttachmentsForStorage(this.attachments.items),
350
- actions: this.actions,
351
- feedbacks: this.feedbacks,
352
- sessionFeedback: this.sessionFeedback,
353
- feedbackDismissed: this.feedbackDismissed,
354
- createdAt: this.createdAt,
355
- sessionEndTime: this.sessionEndTime,
356
- committedComparisons: this.comparisons.committedItems,
357
- });
358
- }
359
- /**
360
- * Schedule a save — multiple calls within the debounce window are coalesced
361
- * into a single localStorage write.
362
- */
363
- save() {
364
- if (this.saveTimerId !== null) {
365
- clearTimeout(this.saveTimerId);
366
- }
367
- this.saveTimerId = setTimeout(() => {
368
- this.saveTimerId = null;
369
- this.saveImmediate();
370
- }, 0);
371
- }
372
- /** Remove oldest stored sessions when exceeding the limit. */
373
- static pruneStoredSessions(storage, maxSessions = 10) {
374
- const storedChats = storage.get('chats');
375
- if (storedChats) {
376
- const chatIds = Object.keys(storedChats);
377
- if (chatIds.length > maxSessions) {
378
- chatIds
379
- .sort((a, b) => {
380
- const aTime = new Date(storedChats[a]?.createdAt || 0).getTime();
381
- const bTime = new Date(storedChats[b]?.createdAt || 0).getTime();
382
- return aTime - bTime;
383
- })
384
- .slice(0, chatIds.length - maxSessions)
385
- .forEach((id) => {
386
- storage.set(`chats.${id}`, null);
387
- });
388
- }
389
- }
390
- }
391
- /** Re-wrap raw stored results as Product / SearchResultStore instances. */
392
- hydrateResults(meta) {
393
- this.chat.forEach((message) => {
394
- if (message.messageType === 'productSearchResult') {
395
- const msg = message;
396
- if (msg.results?.length && !(msg.results[0] instanceof Product)) {
397
- msg.results = createChatResultStore(msg.results, meta);
398
- }
399
- }
400
- else if (message.messageType === 'inspirationResult') {
401
- const msg = message;
402
- msg.inspirationSections?.forEach((section) => {
403
- if (section.products?.length && !(section.products[0] instanceof Product)) {
404
- section.products = createChatResultStore(section.products, meta);
405
- }
406
- });
407
- }
408
- else if (message.messageType === 'productAnswer') {
409
- const msg = message;
410
- if (msg.sourceProduct && !(msg.sourceProduct instanceof Product)) {
411
- msg.sourceProduct = createChatProduct(msg.sourceProduct, meta);
412
- }
413
- }
414
- else if (message.messageType === 'productComparison') {
415
- const msg = message;
416
- if (msg.searchResults?.length && !(msg.searchResults[0] instanceof Product)) {
417
- msg.searchResults = createChatResultStore(msg.searchResults, meta);
418
- }
419
- }
420
- else if (message.messageType === 'productRecommendation') {
421
- const msg = message;
422
- msg.recommendationResult?.forEach((rec) => {
423
- if (rec.results?.length && !(rec.results[0] instanceof Product)) {
424
- rec.results = createChatResultStore(rec.results, meta);
425
- }
426
- });
427
- }
428
- });
429
- }
430
- request(request, filterLabels) {
431
- // clear the questions on new request
432
- this.actions = [];
433
- this.requestType = request.data.requestType;
434
- this.activeMessageId = null;
435
- // remove any attachments that failed to upload
436
- const errorAttachments = this.attachments.items.filter((item) => item.state === 'error');
437
- errorAttachments.forEach((item) => this.attachments.items.splice(this.attachments.items.indexOf(item), 1));
438
- const attachments = [];
439
- if (request.data.requestType === 'productSearch') {
440
- const searchFilters = request.data.searchFilters;
441
- if (searchFilters && searchFilters.length > 0) {
442
- const filterTextArray = [];
443
- searchFilters.forEach((filter) => {
444
- const labelEntry = filterLabels?.[filter.key];
445
- filter.options?.forEach((option) => {
446
- const facetLabel = labelEntry?.facetLabel || filter.key;
447
- if ('low' in option || 'high' in option) {
448
- const low = option.low ?? '*';
449
- const high = option.high ?? '*';
450
- filterTextArray.push(`${facetLabel} ${low}-${high}`);
451
- }
452
- else {
453
- const key = option.key;
454
- const optionLabel = labelEntry?.values[key] || key;
455
- filterTextArray.push(`${facetLabel} ${optionLabel}`);
456
- }
457
- });
458
- });
459
- this.chat.push({
460
- id: uuidv4(),
461
- messageType: 'user',
462
- attachments: attachments.length > 0 ? attachments : undefined,
463
- text: `Filter by ${filterTextArray.join(' and ')}`,
464
- requestType: request.data.requestType,
465
- request: request.data, // request is added here to conditionally display different text in MessageUser
466
- });
467
- }
468
- else if (request.data.searchTerm) {
469
- // for when a query is clicked from ChatInspirationResultMessage
470
- this.chat.push({
471
- id: uuidv4(),
472
- messageType: 'user',
473
- text: request.data.searchTerm,
474
- requestType: request.data.requestType,
475
- request: request.data, // request is added here to conditionally display different text in MessageUser
476
- });
477
- }
478
- }
479
- else if ('message' in request.data && request.data.message) {
480
- if (request.data.requestType === 'imageSearch') {
481
- const imageId = request.data.attachedImageId;
482
- const attachedImage = this.attachments.attached.find((item) => item.type == 'image' && item.imageId == imageId);
483
- if (attachedImage) {
484
- attachments.push(attachedImage.id);
485
- attachedImage.activate();
486
- }
487
- }
488
- else if (request.data.requestType === 'productQuery') {
489
- const productId = request.data.productId;
490
- const attachedProduct = this.attachments.attached.find((item) => item.type == 'product' && item.productId == productId);
491
- if (attachedProduct) {
492
- attachments.push(attachedProduct.id);
493
- attachedProduct.activate();
494
- }
495
- }
496
- else if (request.data.requestType === 'productComparison') {
497
- this.comparisons.compared.forEach((item) => {
498
- const d = item.result?.display || item.result;
499
- const attachment = this.attachments.add({
500
- type: 'product',
501
- requestType: 'productComparison',
502
- productId: item.result.id,
503
- name: d.mappings?.core?.name,
504
- thumbnailUrl: d.mappings?.core?.thumbnailImageUrl || d.mappings?.core?.imageUrl || d.mappings?.core?.parentImageUrl,
505
- });
506
- if (attachment) {
507
- attachments.push(attachment.id);
508
- attachment.activate();
509
- }
510
- });
511
- }
512
- this.chat.push({
513
- id: uuidv4(),
514
- messageType: 'user',
515
- attachments: attachments.length > 0 ? attachments : undefined,
516
- text: request.data.message,
517
- requestType: request.data.requestType,
518
- });
519
- }
520
- else if (request.data?.requestType === 'productSimilar') {
521
- const attachedSimilarProduct = this.attachments.attached.find((item) => item.type == 'product' && item.requestType == 'productSimilar');
522
- if (attachedSimilarProduct) {
523
- attachments.push(attachedSimilarProduct.id);
524
- attachedSimilarProduct.activate();
525
- this.chat.push({
526
- id: uuidv4(),
527
- messageType: 'user',
528
- attachments: attachments.length > 0 ? attachments : undefined,
529
- text: `Show similar products to "${attachedSimilarProduct.name || attachedSimilarProduct.productId}"`,
530
- requestType: request.data.requestType,
531
- });
532
- }
533
- }
534
- else if (request.data?.requestType === 'productComparison') {
535
- const productNames = [];
536
- this.comparisons.compared.forEach((item) => {
537
- const d = item.result?.display || item.result;
538
- const attachment = this.attachments.add({
539
- type: 'product',
540
- requestType: 'productComparison',
541
- productId: item.result.id,
542
- name: d.mappings?.core?.name,
543
- thumbnailUrl: d.mappings?.core?.thumbnailImageUrl || d.mappings?.core?.imageUrl || d.mappings?.core?.parentImageUrl,
544
- });
545
- if (attachment) {
546
- attachments.push(attachment.id);
547
- attachment.activate();
548
- productNames.push(attachment.name || attachment.productId);
549
- }
550
- });
551
- if (attachments.length > 0) {
552
- this.chat.push({
553
- id: uuidv4(),
554
- messageType: 'user',
555
- attachments: attachments,
556
- text: `Compare ${productNames.map((name) => `"${name}"`).join(' and ')}`,
557
- requestType: request.data.requestType,
558
- });
559
- }
560
- }
561
- // snapshot the comparison list into the committed list so the
562
- // header section can clear and the footer can display them
563
- if (request.data.requestType === 'productComparison') {
564
- this.comparisons.commit();
565
- }
566
- this.save();
567
- }
568
- update(data) {
569
- this.sessionId = data.chat.context.sessionId;
570
- const meta = data.meta;
571
- data.chat.data.forEach((messageData) => {
572
- // check if the data has questions?
573
- if (messageData.messageType === 'actions') {
574
- this.actions.push({
575
- type: 'actions',
576
- data: messageData.actions,
577
- });
578
- return;
579
- }
580
- // convert raw results to Product instances (via SearchResultStore) so
581
- // display components can use result.display for mask-aware rendering
582
- if (messageData.messageType === 'productSearchResult' && messageData.results?.length) {
583
- messageData.results = createChatResultStore(messageData.results, meta);
584
- }
585
- else if (messageData.messageType === 'inspirationResult' && messageData.inspirationSections?.length) {
586
- messageData.inspirationSections = messageData.inspirationSections.map((section) => ({
587
- ...section,
588
- products: section.products?.length
589
- ? createChatResultStore(section.products, meta)
590
- : section.products,
591
- }));
592
- }
593
- else if (messageData.messageType === 'productAnswer' && messageData.sourceProduct) {
594
- messageData.sourceProduct = createChatProduct(messageData.sourceProduct, meta);
595
- }
596
- else if (messageData.messageType === 'productComparison' && messageData.searchResults?.length) {
597
- messageData.searchResults = createChatResultStore(messageData.searchResults, meta);
598
- }
599
- else if (messageData.messageType === 'productRecommendation' && messageData.recommendationResult?.length) {
600
- messageData.recommendationResult = messageData.recommendationResult.map((rec) => ({
601
- ...rec,
602
- results: rec.results?.length ? createChatResultStore(rec.results, meta) : rec.results,
603
- }));
604
- }
605
- this.chat.push(messageData);
606
- });
607
- this.save();
608
- }
609
- }