@athoscommerce/snap-store-mobx 1.4.0 → 1.5.1-beta.110

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 (53) hide show
  1. package/dist/cjs/Autocomplete/AutocompleteStore.d.ts.map +1 -1
  2. package/dist/cjs/Autocomplete/AutocompleteStore.js +4 -1
  3. package/dist/cjs/Autocomplete/Stores/AutocompleteFacetStore.js +2 -1
  4. package/dist/cjs/Chat/ChatStore.d.ts +86 -0
  5. package/dist/cjs/Chat/ChatStore.d.ts.map +1 -0
  6. package/dist/cjs/Chat/ChatStore.js +539 -0
  7. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  8. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  9. package/dist/cjs/Chat/Stores/ChatAttachmentStore.js +314 -0
  10. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts +16 -0
  11. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  12. package/dist/cjs/Chat/Stores/ChatCompareStore.js +65 -0
  13. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +107 -0
  14. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  15. package/dist/cjs/Chat/Stores/ChatSessionStore.js +635 -0
  16. package/dist/cjs/Recommendation/Stores/RecommendationProfileStore.js +1 -1
  17. package/dist/cjs/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  18. package/dist/cjs/Search/Stores/SearchFacetStore.js +13 -10
  19. package/dist/cjs/Search/Stores/index.d.ts +1 -1
  20. package/dist/cjs/Search/Stores/index.d.ts.map +1 -1
  21. package/dist/cjs/Search/Stores/index.js +2 -1
  22. package/dist/cjs/index.d.ts +4 -0
  23. package/dist/cjs/index.d.ts.map +1 -1
  24. package/dist/cjs/index.js +5 -1
  25. package/dist/cjs/types.d.ts +21 -2
  26. package/dist/cjs/types.d.ts.map +1 -1
  27. package/dist/esm/Autocomplete/AutocompleteStore.d.ts.map +1 -1
  28. package/dist/esm/Autocomplete/AutocompleteStore.js +3 -1
  29. package/dist/esm/Autocomplete/Stores/AutocompleteFacetStore.js +1 -1
  30. package/dist/esm/Chat/ChatStore.d.ts +86 -0
  31. package/dist/esm/Chat/ChatStore.d.ts.map +1 -0
  32. package/dist/esm/Chat/ChatStore.js +478 -0
  33. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts +98 -0
  34. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts.map +1 -0
  35. package/dist/esm/Chat/Stores/ChatAttachmentStore.js +222 -0
  36. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts +16 -0
  37. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts.map +1 -0
  38. package/dist/esm/Chat/Stores/ChatCompareStore.js +51 -0
  39. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +107 -0
  40. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  41. package/dist/esm/Chat/Stores/ChatSessionStore.js +601 -0
  42. package/dist/esm/Recommendation/Stores/RecommendationProfileStore.js +1 -1
  43. package/dist/esm/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  44. package/dist/esm/Search/Stores/SearchFacetStore.js +13 -10
  45. package/dist/esm/Search/Stores/index.d.ts +1 -1
  46. package/dist/esm/Search/Stores/index.d.ts.map +1 -1
  47. package/dist/esm/Search/Stores/index.js +1 -1
  48. package/dist/esm/index.d.ts +4 -0
  49. package/dist/esm/index.d.ts.map +1 -1
  50. package/dist/esm/index.js +2 -0
  51. package/dist/esm/types.d.ts +21 -2
  52. package/dist/esm/types.d.ts.map +1 -1
  53. package/package.json +5 -5
@@ -0,0 +1,539 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __assign = (this && this.__assign) || function () {
18
+ __assign = Object.assign || function(t) {
19
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
20
+ s = arguments[i];
21
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
+ t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ChatStore = void 0;
30
+ var mobx_1 = require("mobx");
31
+ var MetaStore_1 = require("../Meta/MetaStore");
32
+ var AbstractStore_1 = require("../Abstract/AbstractStore");
33
+ var snap_toolbox_1 = require("@athoscommerce/snap-toolbox");
34
+ var ChatSessionStore_1 = require("./Stores/ChatSessionStore");
35
+ var SearchResultStore_1 = require("../Search/Stores/SearchResultStore");
36
+ var SearchFacetStore_1 = require("../Search/Stores/SearchFacetStore");
37
+ var CHAT_STATUS_EXPIRATION_TIME = 1000 * 60 * 60 * 12; // 12 hours
38
+ var ChatStore = /** @class */ (function (_super) {
39
+ __extends(ChatStore, _super);
40
+ function ChatStore(config, services) {
41
+ var _this = _super.call(this, config) || this;
42
+ _this.meta = undefined;
43
+ _this.inputValue = '';
44
+ _this.open = false;
45
+ _this.chats = [];
46
+ _this.chatEnabled = null;
47
+ _this.initChatLoading = false;
48
+ _this.suggestedQuestions = [];
49
+ _this.welcomeMessage = '';
50
+ _this.features = { imageSearch: { enabled: false }, similarProducts: { enabled: false } };
51
+ _this.productQuickview = null;
52
+ _this.productQuickviewError = null;
53
+ /** Raw meta kept for lazy hydration of inactive chat sessions. */
54
+ _this.storedMetaData = null;
55
+ /** Tracks which message currently owns the displayed facets — guards against redundant rebuilds. */
56
+ _this.activeFacetsMessageId = null;
57
+ /** Bumps on every detached-urlManager change so observers re-evaluate isFacetSelected. */
58
+ _this.urlVersion = 0;
59
+ /** Snapshot of the applied filter state captured the last time the active message was seeded.
60
+ * Compared against the live urlManager state to decide whether there are pending changes. */
61
+ _this.appliedFilterSnapshot = '{}';
62
+ _this.services = services;
63
+ _this.urlManager = services.urlManager.detach(true);
64
+ _this.urlManager.subscribe(function () {
65
+ _this.urlVersion++;
66
+ });
67
+ var legacyKey = "ss-".concat(_this.config.id);
68
+ var storageKey = _this.config.siteId ? "ss-".concat(_this.config.siteId, "-").concat(_this.config.id) : legacyKey;
69
+ _this.storage = new snap_toolbox_1.StorageStore({
70
+ type: 'local',
71
+ key: storageKey,
72
+ });
73
+ _this.facets = _this.buildFacetStore();
74
+ var storedChatStatusResponse = _this.storage.get('chatStatusResponse');
75
+ if (storedChatStatusResponse) {
76
+ try {
77
+ var storedChatStatus = JSON.parse(storedChatStatusResponse);
78
+ if (storedChatStatus.checkTime && Date.now() - storedChatStatus.checkTime > CHAT_STATUS_EXPIRATION_TIME) {
79
+ // chat status is expired, remove from storage to trigger a new check
80
+ _this.storage.set('chatStatusResponse', null);
81
+ }
82
+ else {
83
+ // Apply the stored response without persisting, so the 12-hour
84
+ // checkTime keeps counting from the last real API call rather
85
+ // than resetting on every page load.
86
+ _this.applyChatStatusResponse(storedChatStatus.response);
87
+ }
88
+ }
89
+ catch (_a) {
90
+ _this.storage.set('chatStatusResponse', null);
91
+ }
92
+ }
93
+ // check for entries in storage
94
+ var latestChatId = '';
95
+ var storedChats = _this.storage.get('chats');
96
+ storedChats &&
97
+ Object.keys(storedChats || {}).forEach(function (chatId) {
98
+ var chatData = storedChats[chatId];
99
+ if (chatData) {
100
+ var restoredChat = new ChatSessionStore_1.ChatSessionStore({
101
+ data: __assign(__assign({}, chatData), { id: chatId }),
102
+ stores: {
103
+ storage: _this.storage,
104
+ },
105
+ });
106
+ // Mark as unhydrated — results are still raw JSON from storage.
107
+ // Only the active session will be hydrated below.
108
+ restoredChat.hydrated = false;
109
+ _this.chats.push(restoredChat);
110
+ latestChatId = chatId;
111
+ }
112
+ });
113
+ // Prefer the persisted active chat ID so switching chats survives page reloads.
114
+ // Fall back to the most recently created chat if the stored ID is missing or stale.
115
+ var storedCurrentChatId = _this.storage.get('currentChatId');
116
+ var activeChatId = storedCurrentChatId && _this.chats.some(function (chat) { return chat.id === storedCurrentChatId; }) ? storedCurrentChatId : latestChatId;
117
+ var storedMeta = _this.storage.get('meta');
118
+ if (storedMeta) {
119
+ try {
120
+ var metaData = JSON.parse(storedMeta);
121
+ _this.meta = new MetaStore_1.MetaStore({
122
+ data: {
123
+ meta: metaData,
124
+ },
125
+ });
126
+ // Keep raw meta for lazy hydration of inactive sessions
127
+ _this.storedMetaData = metaData;
128
+ // Only hydrate the active chat session — inactive sessions will be
129
+ // hydrated lazily when switched to via switchChat()
130
+ var activeChat = _this.chats.find(function (chat) { return chat.id === activeChatId; });
131
+ if (activeChat) {
132
+ activeChat.hydrateResults(metaData);
133
+ activeChat.hydrated = true;
134
+ }
135
+ }
136
+ catch (_b) {
137
+ _this.storage.set('meta', null);
138
+ }
139
+ }
140
+ _this.currentChatId = activeChatId;
141
+ (0, mobx_1.makeObservable)(_this, {
142
+ meta: mobx_1.observable,
143
+ inputValue: mobx_1.observable,
144
+ open: mobx_1.observable,
145
+ chats: mobx_1.observable,
146
+ currentChatId: mobx_1.observable,
147
+ chatEnabled: mobx_1.observable,
148
+ initChatLoading: mobx_1.observable,
149
+ blocked: mobx_1.computed,
150
+ currentChat: mobx_1.computed,
151
+ chatsIds: mobx_1.computed,
152
+ features: mobx_1.observable,
153
+ suggestedQuestions: mobx_1.observable,
154
+ welcomeMessage: mobx_1.observable,
155
+ productQuickview: mobx_1.observable,
156
+ productQuickviewError: mobx_1.observable,
157
+ facets: mobx_1.observable,
158
+ urlVersion: mobx_1.observable,
159
+ hasPendingFacetChanges: mobx_1.computed,
160
+ });
161
+ // Sync the root facets display with the active message. Only productSearchResult
162
+ // messages carry facets — for any other active message, clear the display so a
163
+ // stale facet bar from a previous response doesn't linger.
164
+ (0, mobx_1.reaction)(function () {
165
+ var _a;
166
+ var active = (_a = _this.currentChat) === null || _a === void 0 ? void 0 : _a.activeMessage;
167
+ return active && active.messageType === 'productSearchResult' ? active : null;
168
+ }, function (active) {
169
+ if (active && active.id !== _this.activeFacetsMessageId) {
170
+ var facets = active.facets;
171
+ _this.setActiveFacets(facets || [], active.id);
172
+ }
173
+ else if (!active && _this.activeFacetsMessageId !== null) {
174
+ _this.setActiveFacets([], null);
175
+ }
176
+ }, { fireImmediately: true });
177
+ return _this;
178
+ }
179
+ /** Build a SearchFacetStore from raw facet data using the current detached urlManager.
180
+ * Synthesizes meta entries for each facet so SearchFacetStore's display/meta filter
181
+ * doesn't drop chat facets (the chat backend already decided what to send). */
182
+ ChatStore.prototype.buildFacetStore = function (facets) {
183
+ var _a;
184
+ if (facets === void 0) { facets = []; }
185
+ var baseMeta = ((_a = this.meta) === null || _a === void 0 ? void 0 : _a.data) || {};
186
+ var baseFacetMeta = baseMeta.facets || {};
187
+ var facetMeta = __assign({}, baseFacetMeta);
188
+ facets.forEach(function (facet) {
189
+ if (!facet.field)
190
+ return;
191
+ var expectedDisplay = facet.type === 'range' ? 'slider' : 'list';
192
+ var existing = facetMeta[facet.field];
193
+ if (!existing || existing.display !== expectedDisplay) {
194
+ facetMeta[facet.field] = __assign(__assign({}, (existing || {})), { field: facet.field, label: facet.label, display: expectedDisplay });
195
+ }
196
+ });
197
+ return new SearchFacetStore_1.SearchFacetStore({
198
+ config: {},
199
+ services: __assign(__assign({}, this.services), { urlManager: this.urlManager }),
200
+ stores: { storage: this.storage },
201
+ data: {
202
+ search: { facets: facets },
203
+ meta: __assign(__assign({}, baseMeta), { facets: facetMeta }),
204
+ },
205
+ });
206
+ };
207
+ /** Reset the detached urlManager and seed it with this message's filtered facet values,
208
+ * then rebuild the root SearchFacetStore so the UI shows the matching display. */
209
+ ChatStore.prototype.setActiveFacets = function (facets, messageId) {
210
+ var _this = this;
211
+ var _a;
212
+ // reset url state, then seed with the API-reported filtered values
213
+ this.urlManager.reset().go();
214
+ facets.forEach(function (facet) {
215
+ // Slider/range facets carry the active selection on the facet itself rather
216
+ // than on individual bucket values.
217
+ if (facet.type === 'range') {
218
+ var active = facet.active;
219
+ var range = facet.range;
220
+ if (active && range && (active.low !== range.low || active.high !== range.high)) {
221
+ _this.urlManager.set("filter.".concat(facet.field), { low: active.low, high: active.high }).go();
222
+ }
223
+ return;
224
+ }
225
+ var filteredValues = (facet.values || []).filter(function (v) { return v === null || v === void 0 ? void 0 : v.filtered; });
226
+ filteredValues.forEach(function (v) {
227
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
228
+ _this.urlManager.merge("filter.".concat(facet.field), [{ low: v.low, high: v.high }]).go();
229
+ }
230
+ else if (typeof v.value !== 'undefined') {
231
+ _this.urlManager.merge("filter.".concat(facet.field), v.value).go();
232
+ }
233
+ });
234
+ });
235
+ this.facets = this.buildFacetStore(facets);
236
+ this.activeFacetsMessageId = messageId;
237
+ this.appliedFilterSnapshot = stableStringify((_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter);
238
+ };
239
+ Object.defineProperty(ChatStore.prototype, "hasPendingFacetChanges", {
240
+ /** True when the in-progress facet selection differs from the filters that were applied
241
+ * by the active productSearchResult — i.e. the user has selected/removed something that
242
+ * hasn't been sent yet. Used to decide whether to show the Apply button. */
243
+ get: function () {
244
+ var _a;
245
+ // touch the version so mobx re-runs this when urlManager state changes
246
+ void this.urlVersion;
247
+ var current = stableStringify((_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter);
248
+ return current !== this.appliedFilterSnapshot;
249
+ },
250
+ enumerable: false,
251
+ configurable: true
252
+ });
253
+ Object.defineProperty(ChatStore.prototype, "currentChat", {
254
+ get: function () {
255
+ var _this = this;
256
+ return this.chats.find(function (chat) { return chat.id === _this.currentChatId; });
257
+ },
258
+ enumerable: false,
259
+ configurable: true
260
+ });
261
+ Object.defineProperty(ChatStore.prototype, "chatsIds", {
262
+ get: function () {
263
+ return this.chats.map(function (chat) { return chat.id; });
264
+ },
265
+ enumerable: false,
266
+ configurable: true
267
+ });
268
+ Object.defineProperty(ChatStore.prototype, "blocked", {
269
+ get: function () {
270
+ var _a;
271
+ var isBlocked = false;
272
+ var blockedAttachments = (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.items.some(function (item) { return item.type === 'image' && item.state === 'loading'; });
273
+ if (this.loading || blockedAttachments) {
274
+ isBlocked = true;
275
+ }
276
+ return isBlocked;
277
+ },
278
+ enumerable: false,
279
+ configurable: true
280
+ });
281
+ ChatStore.prototype.applyChatStatusResponse = function (response) {
282
+ var chatbot = response.chatbot, features = response.features;
283
+ var status = chatbot.status, suggestedQuestions = chatbot.suggestedQuestions, welcomeMessage = chatbot.welcomeMessage;
284
+ this.chatEnabled = status.enabled === true;
285
+ this.features = features;
286
+ this.suggestedQuestions = suggestedQuestions || [];
287
+ this.welcomeMessage = welcomeMessage || '';
288
+ return this.chatEnabled;
289
+ };
290
+ ChatStore.prototype.handleChatStatusResponse = function (response) {
291
+ var enabled = this.applyChatStatusResponse(response);
292
+ // Always persist on a real API response — restarts the 12-hour expiration
293
+ // so each new chat session refreshes the cache.
294
+ this.storage.set('chatStatusResponse', JSON.stringify({ response: response, checkTime: Date.now() }));
295
+ return enabled;
296
+ };
297
+ ChatStore.prototype.reset = function () {
298
+ this.chats = [];
299
+ this.clearProductQuickview();
300
+ this.storage.clear();
301
+ this.createChat();
302
+ };
303
+ ChatStore.prototype.setProductQuickview = function (product) {
304
+ var _a;
305
+ // Clone the product so variant selections (and the parent-mappings merge done
306
+ // in updateProductQuickview) only affect the quickview — the carousel and any
307
+ // other surfaces still hold the original instance.
308
+ this.productQuickview = cloneProductForQuickview(product, (_a = this.meta) === null || _a === void 0 ? void 0 : _a.data);
309
+ this.productQuickviewError = null;
310
+ };
311
+ ChatStore.prototype.updateProductQuickview = function (response) {
312
+ var _a;
313
+ if (!this.productQuickview) {
314
+ return;
315
+ }
316
+ // merge parent-level mappings from the API response into the Product
317
+ this.productQuickview.mappings = __assign(__assign({}, this.productQuickview.mappings), { core: __assign(__assign({}, this.productQuickview.mappings.core), response.mappings.core) });
318
+ var meta = ((_a = this.meta) === null || _a === void 0 ? void 0 : _a.data) || {};
319
+ if (this.productQuickview.variants) {
320
+ // update existing Variants with new data from the Products API
321
+ this.productQuickview.variants.optionConfig = response.variants.optionConfig;
322
+ this.productQuickview.variants.update(response.variants.data);
323
+ }
324
+ else {
325
+ // create Variants for the first time using the Products API data
326
+ this.productQuickview.variants = new SearchResultStore_1.Variants({
327
+ data: {
328
+ mask: this.productQuickview.mask,
329
+ variants: response.variants.data,
330
+ optionConfig: response.variants.optionConfig,
331
+ meta: meta,
332
+ },
333
+ });
334
+ }
335
+ };
336
+ ChatStore.prototype.setProductQuickviewError = function (message) {
337
+ this.productQuickviewError = message;
338
+ };
339
+ ChatStore.prototype.clearProductQuickview = function () {
340
+ this.productQuickview = null;
341
+ this.productQuickviewError = null;
342
+ };
343
+ ChatStore.prototype.clearHistory = function () {
344
+ // drop previous chats while keeping the conversation the user is currently in;
345
+ // if there is no current chat, fall back to a full reset
346
+ var currentChat = this.currentChat;
347
+ if (!currentChat) {
348
+ this.reset();
349
+ return;
350
+ }
351
+ var storedChats = this.storage.get('chats') || {};
352
+ var filtered = {};
353
+ if (storedChats[currentChat.id]) {
354
+ filtered[currentChat.id] = storedChats[currentChat.id];
355
+ }
356
+ this.storage.set('chats', filtered);
357
+ this.chats = [currentChat];
358
+ };
359
+ ChatStore.prototype.createChat = function (data) {
360
+ // abandon any in-flight request state from the previous chat — its
361
+ // response will be discarded by the controller, so the UI shouldn't
362
+ // keep showing its loading spinner or stale error
363
+ this.loading = false;
364
+ this.error = undefined;
365
+ // Prune old sessions before creating a new one to keep storage bounded
366
+ ChatSessionStore_1.ChatSessionStore.pruneStoredSessions(this.storage);
367
+ var newChat = new ChatSessionStore_1.ChatSessionStore({
368
+ data: {
369
+ sessionId: data === null || data === void 0 ? void 0 : data.sessionId,
370
+ sessionEndTime: data === null || data === void 0 ? void 0 : data.sessionEndTime,
371
+ },
372
+ stores: {
373
+ storage: this.storage,
374
+ },
375
+ });
376
+ this.currentChatId = newChat.id;
377
+ this.storage.set('currentChatId', newChat.id);
378
+ this.chats.push(newChat);
379
+ return newChat;
380
+ };
381
+ ChatStore.prototype.switchChat = function (id) {
382
+ var chatExists = this.chats.find(function (chat) { return chat.id === id; });
383
+ if (chatExists) {
384
+ // Lazily hydrate results when switching to a session for the first time
385
+ if (!chatExists.hydrated && this.storedMetaData) {
386
+ chatExists.hydrateResults(this.storedMetaData);
387
+ chatExists.hydrated = true;
388
+ }
389
+ this.currentChatId = id;
390
+ this.storage.set('currentChatId', id);
391
+ }
392
+ };
393
+ ChatStore.prototype.sendProductQuery = function (result, options) {
394
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
395
+ var display = (result === null || result === void 0 ? void 0 : result.display) || result;
396
+ (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.add({
397
+ type: 'product',
398
+ requestType: options.requestType,
399
+ productId: result.id,
400
+ name: (_c = (_b = display.mappings) === null || _b === void 0 ? void 0 : _b.core) === null || _c === void 0 ? void 0 : _c.name,
401
+ thumbnailUrl: ((_e = (_d = display.mappings) === null || _d === void 0 ? void 0 : _d.core) === null || _e === void 0 ? void 0 : _e.thumbnailImageUrl) || ((_g = (_f = display.mappings) === null || _f === void 0 ? void 0 : _f.core) === null || _g === void 0 ? void 0 : _g.imageUrl) || ((_j = (_h = display.mappings) === null || _h === void 0 ? void 0 : _h.core) === null || _j === void 0 ? void 0 : _j.parentImageUrl),
402
+ });
403
+ // for the productQuery flow we want the secondary chat to immediately
404
+ // show the product details panel — push a productQuery message so it
405
+ // becomes the active side-chat message until a productAnswer arrives
406
+ if (options.requestType === 'productQuery' && this.currentChat) {
407
+ this.currentChat.pushProductQueryMessage(result);
408
+ }
409
+ };
410
+ ChatStore.prototype.compareProduct = function (result) {
411
+ var _a;
412
+ (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.comparisons.add({
413
+ result: result,
414
+ });
415
+ };
416
+ ChatStore.prototype.addFacet = function (facet) {
417
+ var value = parseFacetValue(facet.value);
418
+ this.urlManager.merge("filter.".concat(facet.key), Array.isArray(value) ? value : value).go();
419
+ };
420
+ ChatStore.prototype.removeFacet = function (key, value) {
421
+ var parsed = parseFacetValue(value);
422
+ this.urlManager.remove("filter.".concat(key), parsed).go();
423
+ };
424
+ ChatStore.prototype.clearPendingFacets = function () {
425
+ this.urlManager.remove('filter').go();
426
+ };
427
+ ChatStore.prototype.isFacetSelected = function (key, value) {
428
+ var _a;
429
+ // touch the version so mobx re-runs this when urlManager state changes (the
430
+ // underlying UrlManager isn't a mobx observable, so we mirror its updates here)
431
+ void this.urlVersion;
432
+ var filterState = (_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter;
433
+ if (!filterState || !filterState[key])
434
+ return false;
435
+ var stored = Array.isArray(filterState[key]) ? filterState[key] : [filterState[key]];
436
+ var parsed = parseFacetValue(value);
437
+ return stored.some(function (entry) { return facetValueEquals(entry, parsed); });
438
+ };
439
+ ChatStore.prototype.request = function (request) {
440
+ var _this = this;
441
+ var _a, _b;
442
+ // snapshot facet labels (field + per-value) from the active facets display so the
443
+ // outgoing user message can render "Filter by Color Red" rather than raw keys
444
+ var filterLabels = {};
445
+ var _loop_1 = function (facet) {
446
+ var valueFacet = facet;
447
+ var values = {};
448
+ (valueFacet.values || []).forEach(function (v) {
449
+ var _a, _b;
450
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
451
+ values["".concat((_a = v.low) !== null && _a !== void 0 ? _a : '*', ":").concat((_b = v.high) !== null && _b !== void 0 ? _b : '*')] = v.label;
452
+ }
453
+ else if (typeof v.value !== 'undefined') {
454
+ values[v.value] = v.label;
455
+ }
456
+ });
457
+ filterLabels[valueFacet.field] = { facetLabel: valueFacet.label || valueFacet.field, values: values };
458
+ };
459
+ for (var _i = 0, _c = this.facets; _i < _c.length; _i++) {
460
+ var facet = _c[_i];
461
+ _loop_1(facet);
462
+ }
463
+ (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.request(request, filterLabels);
464
+ // remove any productSimilar attachments after request
465
+ var productSimilarAttachments = ((_b = this.currentChat) === null || _b === void 0 ? void 0 : _b.attachments.attached.filter(function (item) { return item.type === 'product' && item.requestType === 'productSimilar'; })) || [];
466
+ productSimilarAttachments.forEach(function (item) {
467
+ var _a;
468
+ (_a = _this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.remove(item.id);
469
+ });
470
+ };
471
+ ChatStore.prototype.update = function (data) {
472
+ // TODO: handle error
473
+ // if(err?.responseBody?.errorMessage || err?.responseBody?.errorCode) {
474
+ // const errorMessage = err?.responseBody?.errorMessage || 'An unknown error has occurred.';
475
+ // }
476
+ var _a;
477
+ (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.update(data);
478
+ if (!this.meta) {
479
+ this.storage.set('meta', JSON.stringify(data.meta));
480
+ }
481
+ this.meta = new MetaStore_1.MetaStore({
482
+ data: {
483
+ meta: data.meta,
484
+ },
485
+ });
486
+ // Keep raw meta in sync for lazy hydration of inactive sessions
487
+ this.storedMetaData = data.meta;
488
+ };
489
+ return ChatStore;
490
+ }(AbstractStore_1.AbstractStore));
491
+ exports.ChatStore = ChatStore;
492
+ /** Deterministic JSON.stringify — sorts object keys recursively so equality comparisons
493
+ * aren't sensitive to insertion order. */
494
+ function stableStringify(value) {
495
+ if (value === null || value === undefined)
496
+ return 'null';
497
+ if (typeof value !== 'object')
498
+ return JSON.stringify(value);
499
+ if (Array.isArray(value)) {
500
+ return "[".concat(value.map(function (v) { return stableStringify(v); }).join(','), "]");
501
+ }
502
+ var keys = Object.keys(value).sort();
503
+ return "{".concat(keys.map(function (k) { return "".concat(JSON.stringify(k), ":").concat(stableStringify(value[k])); }).join(','), "}");
504
+ }
505
+ /** Convert a chat-facet UI value into the URL-state shape — range buckets arrive as "low:high". */
506
+ function parseFacetValue(value) {
507
+ if (typeof value === 'string' && value.includes(':')) {
508
+ var _a = value.split(':'), low = _a[0], high = _a[1];
509
+ return {
510
+ low: low === '*' ? undefined : Number(low),
511
+ high: high === '*' ? undefined : Number(high),
512
+ };
513
+ }
514
+ return value;
515
+ }
516
+ function facetValueEquals(a, b) {
517
+ if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
518
+ return a.low === b.low && a.high === b.high;
519
+ }
520
+ return a === b;
521
+ }
522
+ /** Build a fresh observable Product from an existing one. Variants are intentionally
523
+ * omitted — `updateProductQuickview` populates them from the products API response. */
524
+ function cloneProductForQuickview(product, meta) {
525
+ var _a, _b, _c;
526
+ var result = {
527
+ id: product.id,
528
+ responseId: product.responseId,
529
+ mappings: JSON.parse(JSON.stringify(product.mappings || {})),
530
+ attributes: JSON.parse(JSON.stringify(product.attributes || {})),
531
+ badges: ((_b = (_a = product.badges) === null || _a === void 0 ? void 0 : _a.all) === null || _b === void 0 ? void 0 : _b.map(function (b) { return ({ tag: b.tag }); })) || [],
532
+ };
533
+ return new SearchResultStore_1.Product({
534
+ config: {},
535
+ data: { result: result, meta: meta || {} },
536
+ position: (_c = product.position) !== null && _c !== void 0 ? _c : 0,
537
+ responseId: product.responseId,
538
+ });
539
+ }
@@ -0,0 +1,98 @@
1
+ type AttachmentState = 'loading' | 'error' | 'attached' | 'active' | 'saved';
2
+ type AttachmentError = {
3
+ message: string;
4
+ };
5
+ export type ChatAttachmentAddAttachment = ChatAttachmentImageConfig | ChatAttachmentProductConfig | ChatAttachmentFacetConfig;
6
+ export declare class ChatAttachmentStore {
7
+ items: ChatAttachments[];
8
+ constructor();
9
+ get attached(): ChatAttachments[];
10
+ get compared(): ChatAttachmentProduct[];
11
+ add<T extends ChatAttachments>(attachment: ChatAttachmentAddAttachment): T;
12
+ remove(id: string): void;
13
+ get(id: string): ChatAttachments | undefined;
14
+ reset(): void;
15
+ hydrate(attachments: ChatAttachmentAddAttachment[]): void;
16
+ }
17
+ type ChatAttachments = ChatAttachmentImage | ChatAttachmentProduct | ChatAttachmentFacet;
18
+ declare abstract class ChatAttachment {
19
+ abstract type: string;
20
+ id: string;
21
+ state: AttachmentState;
22
+ error?: AttachmentError;
23
+ constructor(params?: {
24
+ data?: {
25
+ id?: string;
26
+ state?: AttachmentState;
27
+ error?: AttachmentError;
28
+ };
29
+ });
30
+ save(): void;
31
+ activate(): void;
32
+ }
33
+ type ChatAttachmentImageConfig = {
34
+ type: 'image';
35
+ id?: string;
36
+ base64?: string;
37
+ fileName?: string;
38
+ imageId?: string;
39
+ imageUrl?: string;
40
+ thumbnailUrl?: string;
41
+ state?: AttachmentState;
42
+ error?: AttachmentError;
43
+ };
44
+ type ChatAttachmentProductConfig = {
45
+ type: 'product';
46
+ id?: string;
47
+ productId: string;
48
+ thumbnailUrl: string;
49
+ name: string;
50
+ requestType: 'productQuery' | 'productSimilar' | 'productComparison';
51
+ state?: AttachmentState;
52
+ error?: AttachmentError;
53
+ };
54
+ type ChatAttachmentFacetConfig = {
55
+ type: 'facet';
56
+ id?: string;
57
+ key: string;
58
+ facetLabel: string;
59
+ value: string;
60
+ label: string;
61
+ count: number;
62
+ state?: AttachmentState;
63
+ error?: AttachmentError;
64
+ };
65
+ export declare class ChatAttachmentProduct extends ChatAttachment {
66
+ type: 'product' | never;
67
+ productId: string;
68
+ thumbnailUrl: string;
69
+ name: string;
70
+ requestType: 'productQuery' | 'productSimilar' | 'productComparison';
71
+ constructor({ id, productId, thumbnailUrl, name, requestType, state, error }: ChatAttachmentProductConfig);
72
+ }
73
+ export declare class ChatAttachmentFacet extends ChatAttachment {
74
+ type: 'facet' | never;
75
+ key: string;
76
+ facetLabel: string;
77
+ value: string;
78
+ label: string;
79
+ count: number;
80
+ constructor({ id, key, facetLabel, value, label, count, state, error }: ChatAttachmentFacetConfig);
81
+ }
82
+ export declare class ChatAttachmentImage extends ChatAttachment {
83
+ type: 'image' | never;
84
+ fileName?: string;
85
+ imageId?: string;
86
+ imageUrl?: string;
87
+ thumbnailUrl?: string;
88
+ base64?: string;
89
+ constructor({ id, base64, fileName, imageId, imageUrl, thumbnailUrl, state, error }: ChatAttachmentImageConfig);
90
+ update: ({ imageId, imageUrl, thumbnailUrl, error, }: {
91
+ imageId?: string;
92
+ imageUrl?: string;
93
+ thumbnailUrl?: string;
94
+ error?: AttachmentError;
95
+ }) => Promise<void>;
96
+ }
97
+ export {};
98
+ //# sourceMappingURL=ChatAttachmentStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatAttachmentStore.d.ts","sourceRoot":"","sources":["../../../../src/Chat/Stores/ChatAttachmentStore.ts"],"names":[],"mappings":"AAMA,KAAK,eAAe,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,GAAG,OAAO,CAAC;AAC7E,KAAK,eAAe,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,2BAA2B,GAAG,yBAAyB,GAAG,2BAA2B,GAAG,yBAAyB,CAAC;AAE9H,qBAAa,mBAAmB;IACxB,KAAK,EAAE,eAAe,EAAE,CAAM;;IAUrC,IAAI,QAAQ,sBAEX;IAED,IAAI,QAAQ,4BAKX;IAED,GAAG,CAAC,CAAC,SAAS,eAAe,EAAE,UAAU,EAAE,2BAA2B,GAAG,CAAC;IAgG1E,MAAM,CAAC,EAAE,EAAE,MAAM;IAajB,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS;IAI5C,KAAK,IAAI,IAAI;IAMb,OAAO,CAAC,WAAW,EAAE,2BAA2B,EAAE,GAAG,IAAI;CAezD;AAID,KAAK,eAAe,GAAG,mBAAmB,GAAG,qBAAqB,GAAG,mBAAmB,CAAC;AAEzF,uBAAe,cAAc;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