@athoscommerce/snap-store-mobx 1.6.0 → 1.7.1-beta.121

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 (47) hide show
  1. package/dist/cjs/Autocomplete/Stores/AutocompleteFacetStore.js +2 -1
  2. package/dist/cjs/Chat/ChatStore.d.ts +107 -0
  3. package/dist/cjs/Chat/ChatStore.d.ts.map +1 -0
  4. package/dist/cjs/Chat/ChatStore.js +680 -0
  5. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  6. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  7. package/dist/cjs/Chat/Stores/ChatAttachmentStore.js +316 -0
  8. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts +16 -0
  9. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  10. package/dist/cjs/Chat/Stores/ChatCompareStore.js +64 -0
  11. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +104 -0
  12. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  13. package/dist/cjs/Chat/Stores/ChatSessionStore.js +637 -0
  14. package/dist/cjs/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  15. package/dist/cjs/Search/Stores/SearchFacetStore.js +13 -10
  16. package/dist/cjs/Search/Stores/index.d.ts +1 -1
  17. package/dist/cjs/Search/Stores/index.d.ts.map +1 -1
  18. package/dist/cjs/Search/Stores/index.js +2 -1
  19. package/dist/cjs/index.d.ts +4 -0
  20. package/dist/cjs/index.d.ts.map +1 -1
  21. package/dist/cjs/index.js +5 -1
  22. package/dist/cjs/types.d.ts +24 -2
  23. package/dist/cjs/types.d.ts.map +1 -1
  24. package/dist/esm/Autocomplete/Stores/AutocompleteFacetStore.js +1 -1
  25. package/dist/esm/Chat/ChatStore.d.ts +107 -0
  26. package/dist/esm/Chat/ChatStore.d.ts.map +1 -0
  27. package/dist/esm/Chat/ChatStore.js +605 -0
  28. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  29. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  30. package/dist/esm/Chat/Stores/ChatAttachmentStore.js +224 -0
  31. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts +16 -0
  32. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  33. package/dist/esm/Chat/Stores/ChatCompareStore.js +50 -0
  34. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +104 -0
  35. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  36. package/dist/esm/Chat/Stores/ChatSessionStore.js +602 -0
  37. package/dist/esm/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  38. package/dist/esm/Search/Stores/SearchFacetStore.js +13 -10
  39. package/dist/esm/Search/Stores/index.d.ts +1 -1
  40. package/dist/esm/Search/Stores/index.d.ts.map +1 -1
  41. package/dist/esm/Search/Stores/index.js +1 -1
  42. package/dist/esm/index.d.ts +4 -0
  43. package/dist/esm/index.d.ts.map +1 -1
  44. package/dist/esm/index.js +2 -0
  45. package/dist/esm/types.d.ts +24 -2
  46. package/dist/esm/types.d.ts.map +1 -1
  47. package/package.json +5 -5
@@ -0,0 +1,605 @@
1
+ import { makeObservable, observable, computed, reaction } from 'mobx';
2
+ import { MetaStore } from '../Meta/MetaStore';
3
+ import { AbstractStore } from '../Abstract/AbstractStore';
4
+ import { StorageStore } from '@athoscommerce/snap-toolbox';
5
+ import { ChatSessionStore } from './Stores/ChatSessionStore';
6
+ import { Product, Variants } from '../Search/Stores/SearchResultStore';
7
+ import { SearchFacetStore } from '../Search/Stores/SearchFacetStore';
8
+ const CHAT_STATUS_EXPIRATION_TIME = 1000 * 60 * 10; // 10 minutes
9
+ export class ChatStore extends AbstractStore {
10
+ constructor(config, services) {
11
+ super(config);
12
+ this.meta = undefined;
13
+ this.inputValue = '';
14
+ this.open = false;
15
+ this.chats = [];
16
+ this.chatEnabled = null;
17
+ this.initChatLoading = false;
18
+ this.suggestedQuestions = [];
19
+ this.welcomeMessage = '';
20
+ this.features = { imageSearch: { enabled: false }, similarProducts: { enabled: false } };
21
+ this.productQuickview = null;
22
+ this.productQuickviewError = null;
23
+ /** Raw meta kept for lazy hydration of inactive chat sessions. */
24
+ this.storedMetaData = null;
25
+ /** Tracks which message currently owns the displayed facets — guards against redundant rebuilds. */
26
+ this.activeFacetsMessageId = null;
27
+ /** Bumps on every detached-urlManager change so observers re-evaluate isFacetSelected. */
28
+ this.urlVersion = 0;
29
+ /** Snapshot of the applied filter state captured the last time the active message was seeded.
30
+ * Compared against the live urlManager state to decide whether there are pending changes.
31
+ * `null` means no facets have been seeded yet — there are no pending changes in that case. */
32
+ this.appliedFilterSnapshot = null;
33
+ this.services = services;
34
+ this.urlManager = services.urlManager.detach(true);
35
+ this.urlManager.subscribe(() => {
36
+ this.urlVersion++;
37
+ });
38
+ const legacyKey = `ss-${this.config.id}`;
39
+ const storageKey = this.config.siteId ? `ss-${this.config.siteId}-${this.config.id}` : legacyKey;
40
+ this.storage = new StorageStore({
41
+ type: 'local',
42
+ key: storageKey,
43
+ });
44
+ this.statusStorage = new StorageStore({
45
+ type: 'session',
46
+ key: `${storageKey}-status`,
47
+ });
48
+ this.facets = this.buildFacetStore();
49
+ const storedChatStatusResponse = this.statusStorage.get('chatStatusResponse');
50
+ if (storedChatStatusResponse) {
51
+ try {
52
+ const storedChatStatus = JSON.parse(storedChatStatusResponse);
53
+ if (storedChatStatus.checkTime && Date.now() - storedChatStatus.checkTime > CHAT_STATUS_EXPIRATION_TIME) {
54
+ // chat status is expired, remove from storage to trigger a new check
55
+ this.statusStorage.set('chatStatusResponse', null);
56
+ }
57
+ else {
58
+ // Apply the stored response without persisting, so the
59
+ // checkTime keeps counting from the last real API call rather
60
+ // than resetting on every page load.
61
+ this.applyChatStatusResponse(storedChatStatus.response);
62
+ }
63
+ }
64
+ catch {
65
+ this.statusStorage.set('chatStatusResponse', null);
66
+ }
67
+ }
68
+ // check for entries in storage
69
+ let latestChatId = '';
70
+ const storedChats = this.storage.get('chats');
71
+ storedChats &&
72
+ Object.keys(storedChats || {}).forEach((chatId) => {
73
+ const chatData = storedChats[chatId];
74
+ if (chatData) {
75
+ const restoredChat = new ChatSessionStore({
76
+ data: {
77
+ ...chatData,
78
+ id: chatId,
79
+ },
80
+ stores: {
81
+ storage: this.storage,
82
+ },
83
+ });
84
+ // Mark as unhydrated — results are still raw JSON from storage.
85
+ // Only the active session will be hydrated below.
86
+ restoredChat.hydrated = false;
87
+ this.chats.push(restoredChat);
88
+ latestChatId = chatId;
89
+ }
90
+ });
91
+ // Prefer the persisted active chat ID so switching chats survives page reloads.
92
+ // Fall back to the most recently created chat if the stored ID is missing or stale.
93
+ const storedCurrentChatId = this.storage.get('currentChatId');
94
+ const activeChatId = storedCurrentChatId && this.chats.some((chat) => chat.id === storedCurrentChatId) ? storedCurrentChatId : latestChatId;
95
+ const storedMeta = this.storage.get('meta');
96
+ if (storedMeta) {
97
+ try {
98
+ const metaData = JSON.parse(storedMeta);
99
+ this.meta = new MetaStore({
100
+ data: {
101
+ meta: metaData,
102
+ },
103
+ });
104
+ // Keep raw meta for lazy hydration of inactive sessions
105
+ this.storedMetaData = metaData;
106
+ // Only hydrate the active chat session — inactive sessions will be
107
+ // hydrated lazily when switched to via switchChat()
108
+ const activeChat = this.chats.find((chat) => chat.id === activeChatId);
109
+ if (activeChat) {
110
+ activeChat.hydrateResults(metaData);
111
+ activeChat.hydrated = true;
112
+ }
113
+ }
114
+ catch {
115
+ this.storage.set('meta', null);
116
+ }
117
+ }
118
+ this.currentChatId = activeChatId;
119
+ makeObservable(this, {
120
+ meta: observable,
121
+ inputValue: observable,
122
+ open: observable,
123
+ chats: observable,
124
+ currentChatId: observable,
125
+ chatEnabled: observable,
126
+ initChatLoading: observable,
127
+ blocked: computed,
128
+ currentChat: computed,
129
+ chatsIds: computed,
130
+ features: observable,
131
+ suggestedQuestions: observable,
132
+ welcomeMessage: observable,
133
+ productQuickview: observable,
134
+ productQuickviewError: observable,
135
+ facets: observable,
136
+ urlVersion: observable,
137
+ hasPendingFacetChanges: computed,
138
+ pendingFacetCount: computed,
139
+ searchFilters: computed,
140
+ });
141
+ // Sync the root facets display with the active message. Only productSearchResult
142
+ // messages carry facets — for any other active message, clear the display so a
143
+ // stale facet bar from a previous response doesn't linger.
144
+ // Exception: when the user clicks "discuss product" on a carousel result, the
145
+ // active message becomes the productQuery side-chat, but the carousel is still
146
+ // the last real message — keep its facets visible alongside the product context.
147
+ reaction(() => {
148
+ const chat = this.currentChat;
149
+ const active = chat?.activeMessage;
150
+ if (active?.messageType === 'productSearchResult')
151
+ return active;
152
+ if (active?.messageType === 'productQuery' && chat) {
153
+ const messages = chat.chat;
154
+ const activeIdx = messages.findIndex((m) => m.id === active.id);
155
+ if (activeIdx > 0 && messages[activeIdx - 1].messageType === 'productSearchResult') {
156
+ return messages[activeIdx - 1];
157
+ }
158
+ }
159
+ return null;
160
+ }, (active) => {
161
+ if (active && active.id !== this.activeFacetsMessageId) {
162
+ const facets = active.facets;
163
+ this.setActiveFacets(facets || [], active.id);
164
+ }
165
+ else if (!active && this.activeFacetsMessageId !== null) {
166
+ this.setActiveFacets([], null);
167
+ }
168
+ }, { fireImmediately: true });
169
+ // Mirror the urlManager's pending range filters into each RangeFacet's `active`.
170
+ // Slider facets are remounted whenever their dropdown closes/reopens and the
171
+ // FacetSlider seeds its state from facet.active — without this sync the slider
172
+ // would snap back to the server-provided active on every reopen, losing the
173
+ // user's pending selection until Apply is clicked.
174
+ // Note: range filters round-trip through the detached urlManager's URL form,
175
+ // so they come back as `[{low, high}]` arrays even though they were set as objects.
176
+ const readRangeFilter = (raw) => {
177
+ const entry = Array.isArray(raw) ? raw[raw.length - 1] : raw;
178
+ if (!entry || typeof entry !== 'object')
179
+ return null;
180
+ if (typeof entry.low === 'undefined' && typeof entry.high === 'undefined')
181
+ return null;
182
+ return {
183
+ low: entry.low === null || typeof entry.low === 'undefined' ? undefined : Number(entry.low),
184
+ high: entry.high === null || typeof entry.high === 'undefined' ? undefined : Number(entry.high),
185
+ };
186
+ };
187
+ reaction(() => {
188
+ void this.urlVersion;
189
+ const filterState = this.urlManager.state?.filter || {};
190
+ return this.facets
191
+ .filter((f) => f.type === 'range')
192
+ .map((f) => {
193
+ const pending = readRangeFilter(filterState[f.field]);
194
+ return `${f.field}:${pending?.low ?? '*'}:${pending?.high ?? '*'}`;
195
+ })
196
+ .join('|');
197
+ }, () => {
198
+ const filterState = this.urlManager.state?.filter || {};
199
+ for (const facet of this.facets) {
200
+ if (facet.type !== 'range')
201
+ continue;
202
+ const rangeFacet = facet;
203
+ const pending = readRangeFilter(filterState[rangeFacet.field]);
204
+ const desired = pending
205
+ ? {
206
+ low: typeof pending.low !== 'undefined' ? pending.low : rangeFacet.range?.low,
207
+ high: typeof pending.high !== 'undefined' ? pending.high : rangeFacet.range?.high,
208
+ }
209
+ : rangeFacet.range
210
+ ? { low: rangeFacet.range.low, high: rangeFacet.range.high }
211
+ : null;
212
+ if (!desired)
213
+ continue;
214
+ if (rangeFacet.active?.low !== desired.low || rangeFacet.active?.high !== desired.high) {
215
+ rangeFacet.active = desired;
216
+ }
217
+ }
218
+ }, { fireImmediately: true });
219
+ }
220
+ /** Build a SearchFacetStore from raw facet data using the current detached urlManager.
221
+ * Synthesizes meta entries for each facet so SearchFacetStore's display/meta filter
222
+ * doesn't drop chat facets (the chat backend already decided what to send). */
223
+ buildFacetStore(facets = []) {
224
+ const baseMeta = this.meta?.data || {};
225
+ const baseFacetMeta = baseMeta.facets || {};
226
+ const facetMeta = { ...baseFacetMeta };
227
+ facets.forEach((facet) => {
228
+ if (!facet.field)
229
+ return;
230
+ const expectedDisplay = facet.type === 'range' ? 'slider' : 'list';
231
+ const existing = facetMeta[facet.field];
232
+ if (!existing || existing.display !== expectedDisplay) {
233
+ facetMeta[facet.field] = {
234
+ ...(existing || {}),
235
+ field: facet.field,
236
+ label: facet.label,
237
+ display: expectedDisplay,
238
+ };
239
+ }
240
+ });
241
+ return new SearchFacetStore({
242
+ config: {},
243
+ services: { ...this.services, urlManager: this.urlManager },
244
+ stores: { storage: this.storage },
245
+ data: {
246
+ search: { facets },
247
+ meta: { ...baseMeta, facets: facetMeta },
248
+ },
249
+ });
250
+ }
251
+ /** Reset the detached urlManager and seed it with this message's filtered facet values,
252
+ * then rebuild the root SearchFacetStore so the UI shows the matching display. */
253
+ setActiveFacets(facets, messageId) {
254
+ // reset url state, then seed with the API-reported filtered values
255
+ this.urlManager.reset().go();
256
+ facets.forEach((facet) => {
257
+ // Slider/range facets carry the active selection on the facet itself rather
258
+ // than on individual bucket values.
259
+ if (facet.type === 'range') {
260
+ const active = facet.active;
261
+ const range = facet.range;
262
+ if (active && range && (active.low !== range.low || active.high !== range.high)) {
263
+ this.urlManager.set(`filter.${facet.field}`, { low: active.low, high: active.high }).go();
264
+ }
265
+ return;
266
+ }
267
+ const filteredValues = (facet.values || []).filter((v) => v?.filtered);
268
+ filteredValues.forEach((v) => {
269
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
270
+ this.urlManager.merge(`filter.${facet.field}`, [{ low: v.low, high: v.high }]).go();
271
+ }
272
+ else if (typeof v.value !== 'undefined') {
273
+ this.urlManager.merge(`filter.${facet.field}`, v.value).go();
274
+ }
275
+ });
276
+ });
277
+ this.facets = this.buildFacetStore(facets);
278
+ this.activeFacetsMessageId = messageId;
279
+ this.appliedFilterSnapshot = stableStringify(this.urlManager.state?.filter);
280
+ }
281
+ /** Total number of selected facet values in the in-progress urlManager state, summed
282
+ * across all filter fields. Each value in a value facet, each range in a range-bucket
283
+ * facet, and the single range on a slider facet each count as one. */
284
+ get pendingFacetCount() {
285
+ void this.urlVersion;
286
+ const filterState = this.urlManager.state?.filter;
287
+ if (!filterState)
288
+ return 0;
289
+ let count = 0;
290
+ for (const key of Object.keys(filterState)) {
291
+ const value = filterState[key];
292
+ if (Array.isArray(value)) {
293
+ count += value.length;
294
+ }
295
+ else if (typeof value !== 'undefined') {
296
+ count += 1;
297
+ }
298
+ }
299
+ return count;
300
+ }
301
+ /** Current in-progress facet selection translated into the API's `searchFilters` shape.
302
+ * Returned unconditionally (not gated on `hasPendingFacetChanges`) so callers that need
303
+ * to explicitly force a `productSearch` request — e.g. the non-multiselect facet
304
+ * click handlers — can attach the current filters without re-implementing the mapping. */
305
+ get searchFilters() {
306
+ void this.urlVersion;
307
+ const filterState = this.urlManager.state?.filter;
308
+ const result = [];
309
+ if (!filterState)
310
+ return result;
311
+ Object.keys(filterState).forEach((field) => {
312
+ const raw = filterState[field];
313
+ const values = Array.isArray(raw) ? raw : [raw];
314
+ const options = [];
315
+ values.forEach((v) => {
316
+ if (typeof v === 'object' && v !== null) {
317
+ const low = v.low;
318
+ const high = v.high;
319
+ if (low == null && high == null)
320
+ return;
321
+ options.push({ low: low == null ? '*' : String(low), high: high == null ? '*' : String(high) });
322
+ }
323
+ else {
324
+ options.push({ key: String(v) });
325
+ }
326
+ });
327
+ if (options.length > 0) {
328
+ result.push({ key: field, options });
329
+ }
330
+ });
331
+ return result;
332
+ }
333
+ /** True when the in-progress facet selection differs from the filters that were applied
334
+ * by the active productSearchResult — i.e. the user has selected/removed something that
335
+ * hasn't been sent yet. Used to decide whether to show the Apply button. */
336
+ get hasPendingFacetChanges() {
337
+ // touch the version so mobx re-runs this when urlManager state changes
338
+ void this.urlVersion;
339
+ const filterState = this.urlManager.state?.filter;
340
+ if (this.appliedFilterSnapshot === null) {
341
+ // No facets have been seeded — pending changes exist only if
342
+ // the user has manually added filters via addFacet.
343
+ return filterState !== undefined && Object.keys(filterState).length > 0;
344
+ }
345
+ return stableStringify(filterState) !== this.appliedFilterSnapshot;
346
+ }
347
+ get currentChat() {
348
+ return this.chats.find((chat) => chat.id === this.currentChatId);
349
+ }
350
+ get chatsIds() {
351
+ return this.chats.map((chat) => chat.id);
352
+ }
353
+ get blocked() {
354
+ let isBlocked = false;
355
+ const blockedAttachments = this.currentChat?.attachments.items.some((item) => item.type === 'image' && item.state === 'loading');
356
+ if (this.loading || blockedAttachments) {
357
+ isBlocked = true;
358
+ }
359
+ return isBlocked;
360
+ }
361
+ applyChatStatusResponse(response) {
362
+ const { chatbot, features } = response;
363
+ const { status, suggestedQuestions, welcomeMessage } = chatbot;
364
+ this.chatEnabled = status.enabled === true;
365
+ this.features = features;
366
+ this.suggestedQuestions = suggestedQuestions || [];
367
+ this.welcomeMessage = welcomeMessage || '';
368
+ return this.chatEnabled;
369
+ }
370
+ handleChatStatusResponse(response) {
371
+ const enabled = this.applyChatStatusResponse(response);
372
+ // Always persist on a real API response — restarts the 10-minute expiration
373
+ // so each new chat session refreshes the cache.
374
+ this.statusStorage.set('chatStatusResponse', JSON.stringify({ response, checkTime: Date.now() }));
375
+ return enabled;
376
+ }
377
+ reset() {
378
+ this.chats = [];
379
+ this.clearProductQuickview();
380
+ this.storage.clear();
381
+ this.createChat();
382
+ }
383
+ setProductQuickview(product) {
384
+ // Clone the product so variant selections (and the parent-mappings merge done
385
+ // in updateProductQuickview) only affect the quickview — the carousel and any
386
+ // other surfaces still hold the original instance.
387
+ this.productQuickview = cloneProductForQuickview(product, this.meta?.data);
388
+ this.productQuickviewError = null;
389
+ }
390
+ updateProductQuickview(response) {
391
+ if (!this.productQuickview) {
392
+ return;
393
+ }
394
+ // merge parent-level mappings from the API response into the Product
395
+ this.productQuickview.mappings = {
396
+ ...this.productQuickview.mappings,
397
+ core: { ...this.productQuickview.mappings.core, ...response.mappings.core },
398
+ };
399
+ const meta = this.meta?.data || {};
400
+ if (this.productQuickview.variants) {
401
+ // update existing Variants with new data from the Products API
402
+ this.productQuickview.variants.optionConfig = response.variants.optionConfig;
403
+ this.productQuickview.variants.update(response.variants.data);
404
+ }
405
+ else {
406
+ // create Variants for the first time using the Products API data
407
+ this.productQuickview.variants = new Variants({
408
+ data: {
409
+ mask: this.productQuickview.mask,
410
+ variants: response.variants.data,
411
+ optionConfig: response.variants.optionConfig,
412
+ meta,
413
+ },
414
+ });
415
+ }
416
+ }
417
+ setProductQuickviewError(message) {
418
+ this.productQuickviewError = message;
419
+ }
420
+ clearProductQuickview() {
421
+ this.productQuickview = null;
422
+ this.productQuickviewError = null;
423
+ }
424
+ clearHistory() {
425
+ // drop previous chats while keeping the conversation the user is currently in;
426
+ // if there is no current chat, fall back to a full reset
427
+ const currentChat = this.currentChat;
428
+ if (!currentChat) {
429
+ this.reset();
430
+ return;
431
+ }
432
+ const storedChats = this.storage.get('chats') || {};
433
+ const filtered = {};
434
+ if (storedChats[currentChat.id]) {
435
+ filtered[currentChat.id] = storedChats[currentChat.id];
436
+ }
437
+ this.storage.set('chats', filtered);
438
+ this.chats = [currentChat];
439
+ }
440
+ createChat(data) {
441
+ // abandon any in-flight request state from the previous chat — its
442
+ // response will be discarded by the controller, so the UI shouldn't
443
+ // keep showing its loading spinner or stale error
444
+ this.loading = false;
445
+ this.error = undefined;
446
+ // Prune old sessions before creating a new one to keep storage bounded
447
+ ChatSessionStore.pruneStoredSessions(this.storage);
448
+ const newChat = new ChatSessionStore({
449
+ data: {
450
+ sessionId: data?.sessionId,
451
+ sessionEndTime: data?.sessionEndTime,
452
+ },
453
+ stores: {
454
+ storage: this.storage,
455
+ },
456
+ });
457
+ this.currentChatId = newChat.id;
458
+ this.storage.set('currentChatId', newChat.id);
459
+ this.chats.push(newChat);
460
+ return newChat;
461
+ }
462
+ switchChat(id) {
463
+ const chatExists = this.chats.find((chat) => chat.id === id);
464
+ if (chatExists) {
465
+ // Lazily hydrate results when switching to a session for the first time
466
+ if (!chatExists.hydrated && this.storedMetaData) {
467
+ chatExists.hydrateResults(this.storedMetaData);
468
+ chatExists.hydrated = true;
469
+ }
470
+ this.currentChatId = id;
471
+ this.storage.set('currentChatId', id);
472
+ }
473
+ }
474
+ sendProductQuery(result, options) {
475
+ const display = result?.display || result;
476
+ this.currentChat?.attachments.add({
477
+ type: 'product',
478
+ requestType: options.requestType,
479
+ productId: result.id,
480
+ name: display.mappings?.core?.name,
481
+ thumbnailUrl: display.mappings?.core?.thumbnailImageUrl || display.mappings?.core?.imageUrl || display.mappings?.core?.parentImageUrl,
482
+ });
483
+ // for the productQuery flow we want the secondary chat to immediately
484
+ // show the product details panel — push a productQuery message so it
485
+ // becomes the active side-chat message until a productAnswer arrives
486
+ if (options.requestType === 'productQuery' && this.currentChat) {
487
+ this.currentChat.pushProductQueryMessage(result);
488
+ }
489
+ }
490
+ compareProduct(result) {
491
+ this.currentChat?.comparisons.add({
492
+ result,
493
+ });
494
+ }
495
+ addFacet(facet) {
496
+ const value = parseFacetValue(facet.value);
497
+ this.urlManager.merge(`filter.${facet.key}`, Array.isArray(value) ? value : value).go();
498
+ }
499
+ removeFacet(key, value) {
500
+ const parsed = parseFacetValue(value);
501
+ this.urlManager.remove(`filter.${key}`, parsed).go();
502
+ }
503
+ clearPendingFacets() {
504
+ this.urlManager.remove('filter').go();
505
+ }
506
+ isFacetSelected(key, value) {
507
+ // touch the version so mobx re-runs this when urlManager state changes (the
508
+ // underlying UrlManager isn't a mobx observable, so we mirror its updates here)
509
+ void this.urlVersion;
510
+ const filterState = this.urlManager.state?.filter;
511
+ if (!filterState || !filterState[key])
512
+ return false;
513
+ const stored = Array.isArray(filterState[key]) ? filterState[key] : [filterState[key]];
514
+ const parsed = parseFacetValue(value);
515
+ return stored.some((entry) => facetValueEquals(entry, parsed));
516
+ }
517
+ request(request) {
518
+ // snapshot facet labels (field + per-value) from the active facets display so the
519
+ // outgoing user message can render "Filter by Color Red" rather than raw keys
520
+ const filterLabels = {};
521
+ for (const facet of this.facets) {
522
+ const valueFacet = facet;
523
+ const values = {};
524
+ (valueFacet.values || []).forEach((v) => {
525
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
526
+ values[`${v.low ?? '*'}:${v.high ?? '*'}`] = v.label;
527
+ }
528
+ else if (typeof v.value !== 'undefined') {
529
+ values[v.value] = v.label;
530
+ }
531
+ });
532
+ filterLabels[valueFacet.field] = { facetLabel: valueFacet.label || valueFacet.field, values };
533
+ }
534
+ this.currentChat?.request(request, filterLabels);
535
+ // remove any productSimilar attachments after request
536
+ const productSimilarAttachments = this.currentChat?.attachments.attached.filter((item) => item.type === 'product' && item.requestType === 'productSimilar') || [];
537
+ productSimilarAttachments.forEach((item) => {
538
+ this.currentChat?.attachments.remove(item.id);
539
+ });
540
+ }
541
+ update(data) {
542
+ // TODO: handle error
543
+ // if(err?.responseBody?.errorMessage || err?.responseBody?.errorCode) {
544
+ // const errorMessage = err?.responseBody?.errorMessage || 'An unknown error has occurred.';
545
+ // }
546
+ this.currentChat?.update(data);
547
+ if (!this.meta) {
548
+ this.storage.set('meta', JSON.stringify(data.meta));
549
+ }
550
+ this.meta = new MetaStore({
551
+ data: {
552
+ meta: data.meta,
553
+ },
554
+ });
555
+ // Keep raw meta in sync for lazy hydration of inactive sessions
556
+ this.storedMetaData = data.meta;
557
+ }
558
+ }
559
+ /** Deterministic JSON.stringify — sorts object keys recursively so equality comparisons
560
+ * aren't sensitive to insertion order. */
561
+ function stableStringify(value) {
562
+ if (value === null || value === undefined)
563
+ return 'null';
564
+ if (typeof value !== 'object')
565
+ return JSON.stringify(value);
566
+ if (Array.isArray(value)) {
567
+ return `[${value.map((v) => stableStringify(v)).join(',')}]`;
568
+ }
569
+ const keys = Object.keys(value).sort();
570
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
571
+ }
572
+ /** Convert a chat-facet UI value into the URL-state shape — range buckets arrive as "low:high". */
573
+ function parseFacetValue(value) {
574
+ if (typeof value === 'string' && value.includes(':')) {
575
+ const [low, high] = value.split(':');
576
+ return {
577
+ low: low === '*' ? undefined : Number(low),
578
+ high: high === '*' ? undefined : Number(high),
579
+ };
580
+ }
581
+ return value;
582
+ }
583
+ function facetValueEquals(a, b) {
584
+ if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
585
+ return a.low === b.low && a.high === b.high;
586
+ }
587
+ return a === b;
588
+ }
589
+ /** Build a fresh observable Product from an existing one. Variants are intentionally
590
+ * omitted — `updateProductQuickview` populates them from the products API response. */
591
+ function cloneProductForQuickview(product, meta) {
592
+ const result = {
593
+ id: product.id,
594
+ responseId: product.responseId,
595
+ mappings: JSON.parse(JSON.stringify(product.mappings || {})),
596
+ attributes: JSON.parse(JSON.stringify(product.attributes || {})),
597
+ badges: product.badges?.all?.map((b) => ({ tag: b.tag, value: b.value })) || [],
598
+ };
599
+ return new Product({
600
+ config: {},
601
+ data: { result, meta: meta || {} },
602
+ position: product.position ?? 0,
603
+ responseId: product.responseId,
604
+ });
605
+ }