@nuskin/react-search-sdk 1.0.0-comx-2233.4 → 1.0.0-trying-again.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.
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import React, { useState, useRef, useCallback, useEffect } from 'react';
1
+ import { lazy, useState, useRef, useCallback, useEffect, Suspense, Component } from 'react';
2
+ import { SearchModal } from '@nuskin/react-search-components';
3
+ import { jsx } from 'react/jsx-runtime';
2
4
 
3
5
  // src/constants.ts
4
6
  var STOREFRONT_SHOPPING_CONTEXT = "storefront";
@@ -12,9 +14,6 @@ var DEBOUNCE_MS = 220;
12
14
  var MAX_VISIBLE_SUGGESTIONS = 6;
13
15
  var SEARCH_PLACEHOLDER = "Search by product name, ingredient, benefits, or SKU";
14
16
  var TRIGGER_PLACEHOLDER = "Product Search";
15
- var DEFAULT_AI_CHAT_BASE_URL = "https://admin.tst.nuskin.ai/api/analytics/v1/embed";
16
- var DEFAULT_AI_CHAT_CONVERSATIONS_URL = `${DEFAULT_AI_CHAT_BASE_URL}/conversations`;
17
- var DEFAULT_AI_CHAT_MESSAGES_URL = `${DEFAULT_AI_CHAT_BASE_URL}/messages`;
18
17
 
19
18
  // src/services/SearchApiService.ts
20
19
  var DEFAULT_SEARCH_PLACEHOLDER = TRIGGER_PLACEHOLDER;
@@ -400,549 +399,6 @@ function createSearchService(options = {}) {
400
399
  return service;
401
400
  }
402
401
 
403
- // node_modules/eventsource-parser/dist/errors.js
404
- var ParseError = class extends Error {
405
- constructor(message, options) {
406
- super(message);
407
- this.name = "ParseError";
408
- this.type = options.type;
409
- this.field = options.field;
410
- this.value = options.value;
411
- this.line = options.line;
412
- }
413
- };
414
-
415
- // node_modules/eventsource-parser/dist/parse.js
416
- var LF = 10;
417
- var CR = 13;
418
- var SPACE = 32;
419
- var MAX_FIELD_PREFIX_LENGTH = 6;
420
- function noop(_arg) {
421
- }
422
- function createParser(config) {
423
- if (typeof config === "function") {
424
- throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
425
- }
426
- const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config;
427
- const pendingFragments = [];
428
- let pendingFragmentsLength = 0;
429
- let isFirstChunk = true;
430
- let id;
431
- let data = "";
432
- let dataLines = 0;
433
- let eventType;
434
- let terminated = false;
435
- let skippingLine = false;
436
- let skipNextLineFeed = false;
437
- function feed(chunk) {
438
- if (terminated) {
439
- throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
440
- }
441
- if (isFirstChunk) {
442
- isFirstChunk = false;
443
- if (chunk.charCodeAt(0) === 65279) {
444
- chunk = chunk.slice(1);
445
- } else if (chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191) {
446
- chunk = chunk.slice(3);
447
- }
448
- }
449
- if (skippingLine || skipNextLineFeed) {
450
- chunk = resumeAfterSkip(chunk);
451
- if (!chunk) {
452
- return;
453
- }
454
- }
455
- if (!pendingFragments.length) {
456
- const trailing = processLines(chunk);
457
- if (trailing !== "") {
458
- storeTrailing(trailing);
459
- }
460
- checkBufferSize();
461
- return;
462
- }
463
- if (chunk.indexOf("\n") === -1 && chunk.indexOf("\r") === -1) {
464
- if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {
465
- const head = pendingFragments.join("") + chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);
466
- if (!shouldBufferTrailing(head)) {
467
- pendingFragments.length = 0;
468
- pendingFragmentsLength = 0;
469
- skippingLine = true;
470
- return;
471
- }
472
- }
473
- pendingFragments.push(chunk);
474
- pendingFragmentsLength += chunk.length;
475
- checkBufferSize();
476
- return;
477
- }
478
- pendingFragments.push(chunk);
479
- const input = pendingFragments.join("");
480
- pendingFragments.length = 0;
481
- pendingFragmentsLength = 0;
482
- storeTrailing(processLines(input));
483
- checkBufferSize();
484
- }
485
- function resumeAfterSkip(chunk) {
486
- if (chunk.length === 0) {
487
- return chunk;
488
- }
489
- if (skipNextLineFeed) {
490
- skipNextLineFeed = false;
491
- return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;
492
- }
493
- const crIndex = chunk.indexOf("\r");
494
- const lfIndex = chunk.indexOf("\n");
495
- const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;
496
- if (lineEnd === -1) {
497
- return "";
498
- }
499
- if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {
500
- skippingLine = false;
501
- skipNextLineFeed = true;
502
- return "";
503
- }
504
- skippingLine = false;
505
- return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));
506
- }
507
- function storeTrailing(trailing) {
508
- if (!trailing)
509
- return;
510
- if (trailing.charCodeAt(trailing.length - 1) === CR) {
511
- parseLine(trailing, 0, trailing.length - 1);
512
- skipNextLineFeed = true;
513
- return;
514
- }
515
- if (shouldBufferTrailing(trailing)) {
516
- pendingFragments.push(trailing);
517
- pendingFragmentsLength = trailing.length;
518
- return;
519
- }
520
- skippingLine = true;
521
- }
522
- function shouldBufferTrailing(trailing) {
523
- const firstCharCode = trailing.charCodeAt(0);
524
- return firstCharCode === 58 && !!onComment || firstCharCode === 100 && isPotentialField(trailing, "data") || firstCharCode === 101 && isPotentialField(trailing, "event") || firstCharCode === 105 && isPotentialField(trailing, "id") || firstCharCode === 114 && isPotentialField(trailing, "retry");
525
- }
526
- function checkBufferSize() {
527
- if (maxBufferSize === void 0)
528
- return;
529
- if (pendingFragmentsLength + data.length <= maxBufferSize)
530
- return;
531
- terminated = true;
532
- pendingFragments.length = 0;
533
- pendingFragmentsLength = 0;
534
- id = void 0;
535
- data = "";
536
- dataLines = 0;
537
- eventType = void 0;
538
- skippingLine = false;
539
- skipNextLineFeed = false;
540
- onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
541
- type: "max-buffer-size-exceeded"
542
- }));
543
- }
544
- function processLines(chunk) {
545
- let searchIndex = 0;
546
- if (chunk.indexOf("\r") === -1) {
547
- let lfIndex = chunk.indexOf("\n", searchIndex);
548
- while (lfIndex !== -1) {
549
- if (searchIndex === lfIndex) {
550
- if (dataLines > 0) {
551
- onEvent({ id, event: eventType, data });
552
- }
553
- id = void 0;
554
- data = "";
555
- dataLines = 0;
556
- eventType = void 0;
557
- searchIndex = lfIndex + 1;
558
- lfIndex = chunk.indexOf("\n", searchIndex);
559
- continue;
560
- }
561
- const firstCharCode = chunk.charCodeAt(searchIndex);
562
- if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
563
- const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;
564
- const value = chunk.slice(valueStart, lfIndex);
565
- if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
566
- onEvent({ id, event: eventType, data: value });
567
- id = void 0;
568
- data = "";
569
- eventType = void 0;
570
- searchIndex = lfIndex + 2;
571
- lfIndex = chunk.indexOf("\n", searchIndex);
572
- continue;
573
- }
574
- data = dataLines === 0 ? value : `${data}
575
- ${value}`;
576
- dataLines++;
577
- } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {
578
- eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0;
579
- } else {
580
- parseLine(chunk, searchIndex, lfIndex);
581
- }
582
- searchIndex = lfIndex + 1;
583
- lfIndex = chunk.indexOf("\n", searchIndex);
584
- }
585
- return chunk.slice(searchIndex);
586
- }
587
- while (searchIndex < chunk.length) {
588
- const crIndex = chunk.indexOf("\r", searchIndex);
589
- const lfIndex = chunk.indexOf("\n", searchIndex);
590
- let lineEnd = -1;
591
- if (crIndex !== -1 && lfIndex !== -1) {
592
- lineEnd = crIndex < lfIndex ? crIndex : lfIndex;
593
- } else if (crIndex !== -1) {
594
- if (crIndex === chunk.length - 1) {
595
- lineEnd = -1;
596
- } else {
597
- lineEnd = crIndex;
598
- }
599
- } else if (lfIndex !== -1) {
600
- lineEnd = lfIndex;
601
- }
602
- if (lineEnd === -1) {
603
- break;
604
- }
605
- parseLine(chunk, searchIndex, lineEnd);
606
- searchIndex = lineEnd + 1;
607
- if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {
608
- searchIndex++;
609
- }
610
- }
611
- return chunk.slice(searchIndex);
612
- }
613
- function parseLine(chunk, start, end) {
614
- if (start === end) {
615
- dispatchEvent();
616
- return;
617
- }
618
- const firstCharCode = chunk.charCodeAt(start);
619
- if (isDataPrefix(chunk, start, firstCharCode)) {
620
- const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;
621
- const value2 = chunk.slice(valueStart, end);
622
- data = dataLines === 0 ? value2 : `${data}
623
- ${value2}`;
624
- dataLines++;
625
- return;
626
- }
627
- if (isEventPrefix(chunk, start, firstCharCode)) {
628
- eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
629
- return;
630
- }
631
- if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
632
- const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
633
- if (!value2.includes("\0"))
634
- id = value2;
635
- return;
636
- }
637
- if (firstCharCode === 58) {
638
- if (onComment) {
639
- const line2 = chunk.slice(start, end);
640
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
641
- }
642
- return;
643
- }
644
- const line = chunk.slice(start, end);
645
- const fieldSeparatorIndex = line.indexOf(":");
646
- if (fieldSeparatorIndex === -1) {
647
- processField(line, "", line);
648
- return;
649
- }
650
- const field = line.slice(0, fieldSeparatorIndex);
651
- const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
652
- const value = line.slice(fieldSeparatorIndex + offset);
653
- processField(field, value, line);
654
- }
655
- function processField(field, value, line) {
656
- switch (field) {
657
- case "event":
658
- eventType = value || void 0;
659
- break;
660
- case "data":
661
- data = dataLines === 0 ? value : `${data}
662
- ${value}`;
663
- dataLines++;
664
- break;
665
- case "id":
666
- if (!value.includes("\0"))
667
- id = value;
668
- break;
669
- case "retry":
670
- if (/^\d+$/.test(value)) {
671
- onRetry(parseInt(value, 10));
672
- } else {
673
- onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
674
- type: "invalid-retry",
675
- value,
676
- line
677
- }));
678
- }
679
- break;
680
- default:
681
- onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line }));
682
- break;
683
- }
684
- }
685
- function dispatchEvent() {
686
- if (dataLines > 0) {
687
- onEvent({
688
- id,
689
- event: eventType,
690
- data
691
- });
692
- }
693
- id = void 0;
694
- data = "";
695
- dataLines = 0;
696
- eventType = void 0;
697
- }
698
- function reset(options = {}) {
699
- if (options.consume && pendingFragments.length > 0) {
700
- const incompleteLine = pendingFragments.join("");
701
- parseLine(incompleteLine, 0, incompleteLine.length);
702
- }
703
- isFirstChunk = true;
704
- id = void 0;
705
- data = "";
706
- dataLines = 0;
707
- eventType = void 0;
708
- pendingFragments.length = 0;
709
- pendingFragmentsLength = 0;
710
- terminated = false;
711
- skippingLine = false;
712
- skipNextLineFeed = false;
713
- }
714
- return { feed, reset };
715
- }
716
- function isDataPrefix(chunk, i, firstCharCode) {
717
- return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
718
- }
719
- function isEventPrefix(chunk, i, firstCharCode) {
720
- return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
721
- }
722
- function isPotentialField(line, field) {
723
- let i = 1;
724
- while (i < line.length && i < field.length) {
725
- if (line.charCodeAt(i) !== field.charCodeAt(i)) {
726
- return false;
727
- }
728
- i++;
729
- }
730
- return line.length <= field.length || line.charCodeAt(field.length) === 58;
731
- }
732
-
733
- // src/services/ChatService.ts
734
- var PRODUCTS_OPENING_FENCE = "```products";
735
- var MARKDOWN_CLOSING_FENCE = "\n```";
736
- function findProductsBlockStart(content, openingFenceIndex) {
737
- let blockStart = openingFenceIndex + PRODUCTS_OPENING_FENCE.length;
738
- while (blockStart < content.length && (content[blockStart] === " " || content[blockStart] === " " || content[blockStart] === "\r")) {
739
- blockStart += 1;
740
- }
741
- return content[blockStart] === "\n" ? blockStart + 1 : null;
742
- }
743
- function isStandaloneClosingFence(content, fenceEnd) {
744
- const lineEnd = content.indexOf("\n", fenceEnd);
745
- const suffixEnd = lineEnd === -1 ? content.length : lineEnd;
746
- return content.slice(fenceEnd, suffixEnd).trim() === "";
747
- }
748
- function findClosingFence(content, fromIndex) {
749
- let candidate = content.indexOf(MARKDOWN_CLOSING_FENCE, fromIndex);
750
- while (candidate !== -1) {
751
- const fenceEnd = candidate + MARKDOWN_CLOSING_FENCE.length;
752
- if (isStandaloneClosingFence(content, fenceEnd)) {
753
- return candidate;
754
- }
755
- candidate = content.indexOf(MARKDOWN_CLOSING_FENCE, fenceEnd);
756
- }
757
- return -1;
758
- }
759
- function isRecord(value) {
760
- return value !== null && typeof value === "object";
761
- }
762
- function getRenderProductListItems(event) {
763
- if (event["type"] !== "render" || event["pattern"] !== "product_list") {
764
- return [];
765
- }
766
- const data = event["data"];
767
- if (!isRecord(data) || !Array.isArray(data["items"])) {
768
- return [];
769
- }
770
- return data["items"].filter(isRecord);
771
- }
772
- function extractProductsFromMarkdown(content) {
773
- const products = [];
774
- const summaryParts = [];
775
- let summaryCursor = 0;
776
- let searchCursor = 0;
777
- while (searchCursor < content.length) {
778
- const start = content.indexOf(PRODUCTS_OPENING_FENCE, searchCursor);
779
- if (start === -1) break;
780
- const blockStart = findProductsBlockStart(content, start);
781
- if (blockStart === null) {
782
- searchCursor = start + PRODUCTS_OPENING_FENCE.length;
783
- continue;
784
- }
785
- const nextOpeningFence = content.indexOf(
786
- PRODUCTS_OPENING_FENCE,
787
- blockStart
788
- );
789
- const end = findClosingFence(content, blockStart);
790
- if (end === -1) break;
791
- if (nextOpeningFence !== -1 && nextOpeningFence < end) {
792
- searchCursor = nextOpeningFence;
793
- continue;
794
- }
795
- try {
796
- const parsed = JSON.parse(content.slice(blockStart, end));
797
- if (Array.isArray(parsed)) {
798
- products.push(...parsed);
799
- }
800
- } catch (e) {
801
- console.error("Failed to parse products block:", e);
802
- }
803
- summaryParts.push(content.slice(summaryCursor, start));
804
- summaryCursor = end + MARKDOWN_CLOSING_FENCE.length;
805
- searchCursor = summaryCursor;
806
- }
807
- summaryParts.push(content.slice(summaryCursor));
808
- return { summary: summaryParts.join("").trim(), products };
809
- }
810
- function createChatService(options) {
811
- const {
812
- conversationsUrl = DEFAULT_AI_CHAT_CONVERSATIONS_URL,
813
- messagesUrl = DEFAULT_AI_CHAT_MESSAGES_URL,
814
- salesAiAppKey,
815
- salesAiParentOrigin,
816
- market,
817
- language,
818
- fetchImpl: fetchImplOption
819
- } = options;
820
- let fetchImpl;
821
- if (fetchImplOption !== void 0) {
822
- fetchImpl = fetchImplOption;
823
- } else if (typeof fetch === "function") {
824
- fetchImpl = fetch.bind(globalThis);
825
- } else {
826
- fetchImpl = () => {
827
- throw new Error("ChatService: no fetch implementation available");
828
- };
829
- }
830
- function buildHeaders(extra, includeJsonContentType = true) {
831
- const headers = {
832
- ...extra
833
- };
834
- if (includeJsonContentType) {
835
- headers["Content-Type"] = "application/json";
836
- }
837
- const accessToken = typeof window !== "undefined" ? window.localStorage?.getItem("accessToken") : null;
838
- if (accessToken) {
839
- headers["Authorization"] = `Bearer ${accessToken}`;
840
- }
841
- if (salesAiAppKey) {
842
- headers["X-Sales-AI-App-Key"] = salesAiAppKey;
843
- }
844
- if (salesAiParentOrigin) {
845
- headers["X-Sales-AI-Parent-Origin"] = salesAiParentOrigin;
846
- }
847
- return headers;
848
- }
849
- return {
850
- async createConversation() {
851
- const res = await fetchImpl(conversationsUrl, {
852
- method: "POST",
853
- headers: buildHeaders(void 0, false)
854
- });
855
- if (!res.ok) {
856
- throw new Error(
857
- `ChatService.createConversation: ${res.status} ${res.statusText}`
858
- );
859
- }
860
- const data = await res.json();
861
- const id = data["id"] ?? data["conversation_id"];
862
- if (typeof id !== "number") {
863
- throw new TypeError(
864
- "ChatService.createConversation: response missing numeric id"
865
- );
866
- }
867
- return id;
868
- },
869
- async sendMessage(conversationId, content, onChunk) {
870
- const requestBody = {
871
- conversation_id: conversationId,
872
- content
873
- };
874
- if (market || language) {
875
- requestBody.scope_context = {
876
- market: market ?? "US",
877
- language: language ?? "en"
878
- };
879
- }
880
- requestBody.client_capabilities = {
881
- patterns: {
882
- product_list: [1],
883
- follow_up: [1]
884
- }
885
- };
886
- const res = await fetchImpl(messagesUrl, {
887
- method: "POST",
888
- headers: buildHeaders({ Accept: "text/event-stream" }),
889
- body: JSON.stringify(requestBody)
890
- });
891
- if (!res.ok) {
892
- throw new Error(
893
- `ChatService.sendMessage: ${res.status} ${res.statusText}`
894
- );
895
- }
896
- let accumulated = "";
897
- const renderedProducts = [];
898
- const parser = createParser({
899
- onEvent(event) {
900
- const data = event.data;
901
- if (!data || data === "[DONE]") return;
902
- try {
903
- const parsed = JSON.parse(data);
904
- const parsedType = parsed["type"];
905
- const type = typeof parsedType === "string" ? parsedType : "";
906
- renderedProducts.push(
907
- ...getRenderProductListItems(parsed)
908
- );
909
- if (type === "content" && typeof parsed["text"] === "string") {
910
- const text = parsed["text"];
911
- accumulated += text;
912
- onChunk?.(type, text);
913
- } else if (type === "status" && typeof parsed["message"] === "string") {
914
- const message = parsed["message"];
915
- onChunk?.(type, message);
916
- }
917
- } catch {
918
- }
919
- }
920
- });
921
- const body = res.body;
922
- if (body && typeof body.getReader === "function") {
923
- const reader = body.getReader();
924
- const decoder = new TextDecoder();
925
- while (true) {
926
- const { value, done } = await reader.read();
927
- if (done) break;
928
- parser.feed(decoder.decode(value, { stream: true }));
929
- }
930
- parser.feed(decoder.decode());
931
- } else {
932
- const rawBody = await res.text();
933
- parser.feed(rawBody);
934
- }
935
- const { summary, products } = extractProductsFromMarkdown(accumulated);
936
- const finalProducts = renderedProducts.length > 0 ? renderedProducts : products;
937
- return {
938
- summary,
939
- products: finalProducts,
940
- rawContent: accumulated
941
- };
942
- }
943
- };
944
- }
945
-
946
402
  // src/utils/catalogHelpers.ts
947
403
  var CART_DISABLED_PRODUCT_STATUSES = /* @__PURE__ */ new Set([
948
404
  "discontinued",
@@ -1251,6 +707,7 @@ function useSearchSuggestions({
1251
707
  const [suggestionFetchFailed, setSuggestionFetchFailed] = useState(false);
1252
708
  const [hasMoreResults, setHasMoreResults] = useState(false);
1253
709
  const [totalResultsCount, setTotalResultsCount] = useState(0);
710
+ const [settledQuery, setSettledQuery] = useState("");
1254
711
  const fetchDebounced = useRef(null);
1255
712
  const latestRequestId = useRef(0);
1256
713
  const resetSuggestionsState = useCallback(() => {
@@ -1260,6 +717,7 @@ function useSearchSuggestions({
1260
717
  setSuggestionFetchFailed(false);
1261
718
  setHasMoreResults(false);
1262
719
  setTotalResultsCount(0);
720
+ setSettledQuery("");
1263
721
  setLoading(false);
1264
722
  }, []);
1265
723
  const updateQuery = useCallback(
@@ -1310,6 +768,7 @@ function useSearchSuggestions({
1310
768
  );
1311
769
  setTotalResultsCount(effectiveTotal);
1312
770
  setSuggestionFetchFailed(false);
771
+ setSettledQuery(trimmedQuery);
1313
772
  setEmptyFetched(
1314
773
  hasDidYouMean ? false : visibleSuggestions.length === 0 && suggestedTerms.length === 0
1315
774
  );
@@ -1323,6 +782,7 @@ function useSearchSuggestions({
1323
782
  setSuggestionFetchFailed(true);
1324
783
  setHasMoreResults(false);
1325
784
  setTotalResultsCount(0);
785
+ setSettledQuery(trimmedQuery);
1326
786
  } finally {
1327
787
  if (requestId === latestRequestId.current) {
1328
788
  setLoading(false);
@@ -1357,6 +817,7 @@ function useSearchSuggestions({
1357
817
  didYouMean,
1358
818
  loading,
1359
819
  query,
820
+ settledQuery,
1360
821
  setQuery,
1361
822
  suggestionFetchFailed,
1362
823
  suggestions,
@@ -1365,381 +826,25 @@ function useSearchSuggestions({
1365
826
  };
1366
827
  }
1367
828
 
1368
- // node_modules/zustand/esm/vanilla.mjs
1369
- var createStoreImpl = (createState) => {
1370
- let state;
1371
- const listeners = /* @__PURE__ */ new Set();
1372
- const setState = (partial, replace) => {
1373
- const nextState = typeof partial === "function" ? partial(state) : partial;
1374
- if (!Object.is(nextState, state)) {
1375
- const previousState = state;
1376
- state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
1377
- listeners.forEach((listener) => listener(state, previousState));
1378
- }
1379
- };
1380
- const getState = () => state;
1381
- const getInitialState = () => initialState;
1382
- const subscribe = (listener) => {
1383
- listeners.add(listener);
1384
- return () => listeners.delete(listener);
1385
- };
1386
- const api = { setState, getState, getInitialState, subscribe };
1387
- const initialState = state = createState(setState, getState, api);
1388
- return api;
1389
- };
1390
- var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
1391
- var identity = (arg) => arg;
1392
- function useStore(api, selector = identity) {
1393
- const slice = React.useSyncExternalStore(
1394
- api.subscribe,
1395
- () => selector(api.getState()),
1396
- () => selector(api.getInitialState())
1397
- );
1398
- React.useDebugValue(slice);
1399
- return slice;
1400
- }
1401
- var createImpl = (createState) => {
1402
- const api = createStore(createState);
1403
- const useBoundStore = (selector) => useStore(api, selector);
1404
- Object.assign(useBoundStore, api);
1405
- return useBoundStore;
829
+ // src/utils/gtmConstants.ts
830
+ var SEARCH_GTM_EVENTS = {
831
+ CHAT_ENTRY_POINT: "Begin_chat",
832
+ SEARCH_TYPE: "Search_Type",
833
+ PRODUCT_SEARCH: "ProductSearch",
834
+ ERROR_POPUP: "Error_popup"
1406
835
  };
1407
- var create = (createState) => createImpl;
1408
-
1409
- // node_modules/zustand/esm/middleware.mjs
1410
- function createJSONStorage(getStorage, options) {
1411
- let storage;
1412
- try {
1413
- storage = getStorage();
1414
- } catch (e) {
1415
- return;
1416
- }
1417
- const persistStorage = {
1418
- getItem: (name) => {
1419
- var _a;
1420
- const parse = (str2) => {
1421
- if (str2 === null) {
1422
- return null;
1423
- }
1424
- return JSON.parse(str2, void 0 );
1425
- };
1426
- const str = (_a = storage.getItem(name)) != null ? _a : null;
1427
- if (str instanceof Promise) {
1428
- return str.then(parse);
1429
- }
1430
- return parse(str);
1431
- },
1432
- setItem: (name, newValue) => storage.setItem(
1433
- name,
1434
- JSON.stringify(newValue, void 0 )
1435
- ),
1436
- removeItem: (name) => storage.removeItem(name)
1437
- };
1438
- return persistStorage;
1439
- }
1440
- var toThenable = (fn) => (input) => {
1441
- try {
1442
- const result = fn(input);
1443
- if (result instanceof Promise) {
1444
- return result;
1445
- }
1446
- return {
1447
- then(onFulfilled) {
1448
- return toThenable(onFulfilled)(result);
1449
- },
1450
- catch(_onRejected) {
1451
- return this;
1452
- }
1453
- };
1454
- } catch (e) {
1455
- return {
1456
- then(_onFulfilled) {
1457
- return this;
1458
- },
1459
- catch(onRejected) {
1460
- return toThenable(onRejected)(e);
1461
- }
1462
- };
1463
- }
836
+ var SEARCH_GTM_SEARCH_TYPES = {
837
+ SEMANTIC: "semantic search",
838
+ AI_AGENT: "AI agent"
1464
839
  };
1465
- var persistImpl = (config, baseOptions) => (set, get, api) => {
1466
- let options = {
1467
- storage: createJSONStorage(() => localStorage),
1468
- partialize: (state) => state,
1469
- version: 0,
1470
- merge: (persistedState, currentState) => ({
1471
- ...currentState,
1472
- ...persistedState
1473
- }),
1474
- ...baseOptions
1475
- };
1476
- let hasHydrated = false;
1477
- const hydrationListeners = /* @__PURE__ */ new Set();
1478
- const finishHydrationListeners = /* @__PURE__ */ new Set();
1479
- let storage = options.storage;
1480
- if (!storage) {
1481
- return config(
1482
- (...args) => {
1483
- console.warn(
1484
- `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
1485
- );
1486
- set(...args);
1487
- },
1488
- get,
1489
- api
1490
- );
1491
- }
1492
- const setItem = () => {
1493
- const state = options.partialize({ ...get() });
1494
- return storage.setItem(options.name, {
1495
- state,
1496
- version: options.version
1497
- });
1498
- };
1499
- const savedSetState = api.setState;
1500
- api.setState = (state, replace) => {
1501
- savedSetState(state, replace);
1502
- void setItem();
1503
- };
1504
- const configResult = config(
1505
- (...args) => {
1506
- set(...args);
1507
- void setItem();
1508
- },
1509
- get,
1510
- api
1511
- );
1512
- api.getInitialState = () => configResult;
1513
- let stateFromStorage;
1514
- const hydrate = () => {
1515
- var _a, _b;
1516
- if (!storage) return;
1517
- hasHydrated = false;
1518
- hydrationListeners.forEach((cb) => {
1519
- var _a2;
1520
- return cb((_a2 = get()) != null ? _a2 : configResult);
1521
- });
1522
- const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;
1523
- return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
1524
- if (deserializedStorageValue) {
1525
- if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
1526
- if (options.migrate) {
1527
- return [
1528
- true,
1529
- options.migrate(
1530
- deserializedStorageValue.state,
1531
- deserializedStorageValue.version
1532
- )
1533
- ];
1534
- }
1535
- console.error(
1536
- `State loaded from storage couldn't be migrated since no migrate function was provided`
1537
- );
1538
- } else {
1539
- return [false, deserializedStorageValue.state];
1540
- }
1541
- }
1542
- return [false, void 0];
1543
- }).then((migrationResult) => {
1544
- var _a2;
1545
- const [migrated, migratedState] = migrationResult;
1546
- stateFromStorage = options.merge(
1547
- migratedState,
1548
- (_a2 = get()) != null ? _a2 : configResult
1549
- );
1550
- set(stateFromStorage, true);
1551
- if (migrated) {
1552
- return setItem();
1553
- }
1554
- }).then(() => {
1555
- postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
1556
- stateFromStorage = get();
1557
- hasHydrated = true;
1558
- finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
1559
- }).catch((e) => {
1560
- postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
1561
- });
1562
- };
1563
- api.persist = {
1564
- setOptions: (newOptions) => {
1565
- options = {
1566
- ...options,
1567
- ...newOptions
1568
- };
1569
- if (newOptions.storage) {
1570
- storage = newOptions.storage;
1571
- }
1572
- },
1573
- clearStorage: () => {
1574
- storage == null ? void 0 : storage.removeItem(options.name);
1575
- },
1576
- getOptions: () => options,
1577
- rehydrate: () => hydrate(),
1578
- hasHydrated: () => hasHydrated,
1579
- onHydrate: (cb) => {
1580
- hydrationListeners.add(cb);
1581
- return () => {
1582
- hydrationListeners.delete(cb);
1583
- };
1584
- },
1585
- onFinishHydration: (cb) => {
1586
- finishHydrationListeners.add(cb);
1587
- return () => {
1588
- finishHydrationListeners.delete(cb);
1589
- };
1590
- }
1591
- };
1592
- if (!options.skipHydration) {
1593
- hydrate();
1594
- }
1595
- return stateFromStorage || configResult;
840
+ var SEARCH_GTM_USER_STATUS = {
841
+ GUEST: "guest",
842
+ LOGGED_IN: "logged_in"
1596
843
  };
1597
- var persist = persistImpl;
1598
-
1599
- // src/store/searchHistoryStore.ts
1600
- var MAX_HISTORY = 10;
1601
- var useSearchHistoryStore = create()(
1602
- persist(
1603
- (set) => ({
1604
- entries: [],
1605
- addEntry: (entry) => {
1606
- const trimmed = entry.query.trim();
1607
- if (!trimmed) return;
1608
- set((state) => {
1609
- const deduped = state.entries.filter(
1610
- (e) => e.query.toLowerCase() !== trimmed.toLowerCase()
1611
- );
1612
- const newEntry = {
1613
- ...entry,
1614
- query: trimmed,
1615
- timestamp: Date.now()
1616
- };
1617
- return {
1618
- entries: [newEntry, ...deduped].slice(0, MAX_HISTORY)
1619
- };
1620
- });
1621
- },
1622
- addQuery: (query) => {
1623
- const trimmed = query.trim();
1624
- if (!trimmed) return;
1625
- set((state) => {
1626
- const deduped = state.entries.filter(
1627
- (e) => e.query.toLowerCase() !== trimmed.toLowerCase()
1628
- );
1629
- return {
1630
- entries: [
1631
- {
1632
- query: trimmed,
1633
- isAI: false,
1634
- timestamp: Date.now()
1635
- },
1636
- ...deduped
1637
- ].slice(0, MAX_HISTORY)
1638
- };
1639
- });
1640
- },
1641
- removeEntry: (query) => set((state) => ({
1642
- entries: state.entries.filter((e) => e.query !== query)
1643
- })),
1644
- clearAll: () => set({ entries: [] })
1645
- }),
1646
- {
1647
- name: "ai_search_recent_queries",
1648
- version: 1,
1649
- storage: createJSONStorage(
1650
- () => typeof window !== "undefined" ? window.sessionStorage : {}
1651
- ),
1652
- // Migrate from v0 (queries: string[]) to v1 (entries: SearchHistoryEntry[])
1653
- migrate(persistedState, version) {
1654
- if (version === 0) {
1655
- const old = persistedState;
1656
- if (Array.isArray(old?.queries)) {
1657
- return {
1658
- entries: old.queries.map((q) => ({
1659
- query: q,
1660
- isAI: false,
1661
- timestamp: Date.now()
1662
- }))
1663
- };
1664
- }
1665
- }
1666
- return persistedState;
1667
- }
1668
- }
1669
- )
1670
- );
1671
-
1672
- // src/hooks/useSearchHistory.ts
1673
- function useSearchHistory() {
1674
- const entries = useSearchHistoryStore((s) => s.entries);
1675
- const addEntry = useSearchHistoryStore((s) => s.addEntry);
1676
- const addQuery = useSearchHistoryStore((s) => s.addQuery);
1677
- const removeEntry = useSearchHistoryStore((s) => s.removeEntry);
1678
- const clearAll = useSearchHistoryStore((s) => s.clearAll);
1679
- return {
1680
- entries,
1681
- queries: entries.map((e) => e.query),
1682
- addEntry,
1683
- addQuery,
1684
- removeEntry,
1685
- clearAll
1686
- };
1687
- }
1688
- function getSpeechRecognition() {
1689
- if (typeof window === "undefined") return null;
1690
- const w = window;
1691
- return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
1692
- }
1693
- function useVoiceSearch({
1694
- lang,
1695
- onInterimResult,
1696
- onResult,
1697
- onError
1698
- }) {
1699
- const [listening, setListening] = useState(false);
1700
- const recognitionRef = useRef(null);
1701
- const supported = getSpeechRecognition() !== null;
1702
- const stop = useCallback(() => {
1703
- recognitionRef.current?.stop();
1704
- recognitionRef.current = null;
1705
- setListening(false);
1706
- }, []);
1707
- const start = useCallback(() => {
1708
- const SR = getSpeechRecognition();
1709
- if (!SR) return;
1710
- stop();
1711
- const rec = new SR();
1712
- rec.lang = lang ?? navigator.language ?? "en-US";
1713
- rec.interimResults = true;
1714
- rec.maxAlternatives = 1;
1715
- rec.onresult = (event) => {
1716
- let finalTranscript = "";
1717
- let interimTranscript = "";
1718
- const startIndex = event.resultIndex ?? 0;
1719
- for (let index = startIndex; index < event.results.length; index += 1) {
1720
- const result = event.results[index];
1721
- const transcript = result?.[0]?.transcript ?? "";
1722
- if (!transcript) continue;
1723
- if (result?.isFinal) {
1724
- finalTranscript += transcript;
1725
- } else {
1726
- interimTranscript += transcript;
1727
- }
1728
- }
1729
- if (interimTranscript) onInterimResult?.(interimTranscript);
1730
- if (finalTranscript) onResult(finalTranscript);
1731
- };
1732
- rec.onerror = (event) => {
1733
- onError?.(event);
1734
- setListening(false);
1735
- };
1736
- rec.onend = () => setListening(false);
1737
- recognitionRef.current = rec;
1738
- rec.start();
1739
- setListening(true);
1740
- }, [lang, onInterimResult, onResult, onError, stop]);
1741
- return { listening, supported, start, stop };
1742
- }
844
+ var IS_AUTHENTICATED_KEY = "IsAuthenticated";
845
+ var ACCOUNT_TYPE_KEY = "accountType";
846
+ var NUSKIN_ACCOUNT_DATA_KEY = "nuskin.account.data";
847
+ var GTM_FALLBACK_NA = "NA";
1743
848
 
1744
849
  // src/utils/commonUtils.ts
1745
850
  var IS_BROWSER = typeof window !== "undefined";
@@ -1775,42 +880,8 @@ function getLocalStorage(key) {
1775
880
  return void 0;
1776
881
  }
1777
882
  }
1778
- function getSessionStorage2(key) {
1779
- if (!IS_BROWSER) return void 0;
1780
- try {
1781
- const raw = window.sessionStorage.getItem(key);
1782
- return raw === null ? void 0 : safeParse(raw);
1783
- } catch {
1784
- return void 0;
1785
- }
1786
- }
1787
-
1788
- // src/utils/gtmConstants.ts
1789
- var SEARCH_GTM_EVENTS = {
1790
- CHAT_ENTRY_POINT: "Begin_chat",
1791
- SEARCH_TYPE: "Search_Type",
1792
- PRODUCT_SEARCH: "ProductSearch",
1793
- ERROR_POPUP: "Error_popup"
1794
- };
1795
- var SEARCH_GTM_SEARCH_TYPES = {
1796
- SEMANTIC: "semantic search",
1797
- AI_AGENT: "AI agent"
1798
- };
1799
- var SEARCH_GTM_USER_STATUS = {
1800
- GUEST: "guest",
1801
- LOGGED_IN: "logged_in"
1802
- };
1803
- var AI_CHAT_CONVERSATION_ID_KEY = "ai_chat_conversation_id";
1804
- var IS_AUTHENTICATED_KEY = "IsAuthenticated";
1805
- var ACCOUNT_TYPE_KEY = "accountType";
1806
- var NUSKIN_ACCOUNT_DATA_KEY = "nuskin.account.data";
1807
- var GTM_FALLBACK_NA = "NA";
1808
883
 
1809
884
  // src/utils/gtmTracking.ts
1810
- function readSessionChatId() {
1811
- const raw = getSessionStorage2(AI_CHAT_CONVERSATION_ID_KEY);
1812
- return typeof raw === "string" || typeof raw === "number" ? String(raw) : void 0;
1813
- }
1814
885
  function readUserStatusFromStorage() {
1815
886
  const value = getLocalStorage(IS_AUTHENTICATED_KEY);
1816
887
  if (value === void 0) return void 0;
@@ -1837,13 +908,12 @@ function resolveUserId(explicit) {
1837
908
  }
1838
909
  function baseEventPayload(ctx) {
1839
910
  const urlLocale = getLocaleFromUrl();
1840
- const chatId = ctx.chatId ?? readSessionChatId();
1841
911
  const userStatus = ctx.userStatus ?? readUserStatusFromStorage();
1842
912
  const accountType = ctx.accountType ?? readAccountTypeFromStorage();
1843
913
  const resolvedUserStatus = userStatus ?? SEARCH_GTM_USER_STATUS.GUEST;
1844
914
  const documentTitle = IS_BROWSER && typeof document?.title === "string" ? document.title : void 0;
1845
915
  return {
1846
- Chat_ID: toEventString(chatId, GTM_FALLBACK_NA),
916
+ Chat_ID: toEventString(ctx.chatId, GTM_FALLBACK_NA),
1847
917
  page_type: toEventString(
1848
918
  ctx.pageType ?? documentTitle,
1849
919
  GTM_FALLBACK_NA
@@ -1923,6 +993,411 @@ function trackErrorPopup(input) {
1923
993
  });
1924
994
  }
1925
995
 
1926
- export { CATALOG_SUGGESTIONS_PATH, DEBOUNCE_MS, DEFAULT_AI_CHAT_BASE_URL, DEFAULT_AI_CHAT_CONVERSATIONS_URL, DEFAULT_AI_CHAT_MESSAGES_URL, DEFAULT_SEARCH_PATH, DEFAULT_SUGGESTION_PAGE, DEFAULT_SUGGESTION_SIZE, MAX_VISIBLE_SUGGESTIONS, RECENT_SEARCHES_DEFAULT_LIMIT, RECENT_SEARCHES_PREFIX, SEARCH_GTM_EVENTS, SEARCH_GTM_SEARCH_TYPES, SEARCH_GTM_USER_STATUS, SEARCH_PLACEHOLDER, STOREFRONT_SHOPPING_CONTEXT, TRIGGER_PLACEHOLDER, createChatService, createSearchService, getImageFromProperty, getIngredientTerms, getLocaleFromUrl, getSeeMoreResultsPayload, getVisibleSuggestions, isCartActionDisabled, isSellableProductStatus, isSuggestionDisabled, mapCatalogProductToSuggestion, normalizeDidYouMean, pushGtmEvent, resolveApiGatewayPath, resolveSuggestionImageSrc, trackChatEntryPoint, trackErrorPopup, trackProductSearch, trackSearchType, useSearchHistory, useSearchHistoryStore, useSearchSuggestions, useVoiceSearch };
996
+ // src/utils/nuiSearchGate.ts
997
+ var NUI_SEARCH_FLAG = "enableNuiSearch";
998
+ function parseFlagValue(raw) {
999
+ const value = raw?.trim().toLowerCase();
1000
+ if (value === "true" || value === "1") return true;
1001
+ if (value === "false" || value === "0") return false;
1002
+ return void 0;
1003
+ }
1004
+ function readCookieFlag(cookie) {
1005
+ for (const part of cookie.split(";")) {
1006
+ const separator = part.indexOf("=");
1007
+ if (separator < 0) continue;
1008
+ if (part.slice(0, separator).trim() !== NUI_SEARCH_FLAG) continue;
1009
+ const rawValue = part.slice(separator + 1);
1010
+ try {
1011
+ return parseFlagValue(decodeURIComponent(rawValue));
1012
+ } catch {
1013
+ return void 0;
1014
+ }
1015
+ }
1016
+ return void 0;
1017
+ }
1018
+ function resolveNuiSearchFlag(env = {}) {
1019
+ const inBrowser = typeof window !== "undefined" && typeof document !== "undefined";
1020
+ const search = env.search ?? (inBrowser ? window.location.search : "");
1021
+ const cookie = env.cookie ?? (inBrowser ? document.cookie : "");
1022
+ const setCookie = env.setCookie ?? (inBrowser ? (value) => {
1023
+ document.cookie = value;
1024
+ } : void 0);
1025
+ const fromQuery = parseFlagValue(
1026
+ new URLSearchParams(search).get(NUI_SEARCH_FLAG)
1027
+ );
1028
+ if (fromQuery !== void 0) {
1029
+ const secure = inBrowser && window.location.protocol === "https:" ? "; Secure" : "";
1030
+ setCookie?.(
1031
+ `${NUI_SEARCH_FLAG}=${fromQuery}; path=/; SameSite=Lax${secure}`
1032
+ );
1033
+ return fromQuery;
1034
+ }
1035
+ return readCookieFlag(cookie);
1036
+ }
1037
+ function isNuiSearchEnabled({
1038
+ isAuthenticated,
1039
+ flag
1040
+ }) {
1041
+ return isAuthenticated === true && flag === true;
1042
+ }
1043
+
1044
+ // src/utils/searchRouting.ts
1045
+ function decideSearchRoute({
1046
+ enabled,
1047
+ snapshot
1048
+ }) {
1049
+ const term = snapshot.query.trim();
1050
+ if (!enabled || !term) return "search";
1051
+ if (snapshot.loading || snapshot.settledQuery !== term) return "wait";
1052
+ if (snapshot.suggestionFetchFailed) return "search";
1053
+ return snapshot.suggestions.length > 0 ? "search" : "handoff";
1054
+ }
1055
+ var HANDLE_POLL_MS = 50;
1056
+ var HANDLE_TIMEOUT_MS = 15e3;
1057
+ var SalesAIChatWidget = lazy(async () => {
1058
+ const [widget] = await Promise.all([
1059
+ import('@nuskin/react-nui-chat-sdk'),
1060
+ import('@nuskin/react-nui-chat-sdk/styles.css')
1061
+ ]);
1062
+ return { default: widget.SalesAIChatWidget };
1063
+ });
1064
+ function getSalesAIHandle() {
1065
+ return window.SalesAI;
1066
+ }
1067
+ var AgentErrorBoundary = class extends Component {
1068
+ constructor() {
1069
+ super(...arguments);
1070
+ this.state = { failed: false };
1071
+ }
1072
+ static getDerivedStateFromError() {
1073
+ return { failed: true };
1074
+ }
1075
+ componentDidCatch(_error, _info) {
1076
+ this.props.onError();
1077
+ }
1078
+ render() {
1079
+ return this.state.failed ? null : this.props.children;
1080
+ }
1081
+ };
1082
+ function useHandoff({
1083
+ query,
1084
+ handoffContext,
1085
+ agentContext,
1086
+ onUnavailable
1087
+ }) {
1088
+ useEffect(() => {
1089
+ let cancelled = false;
1090
+ let timer;
1091
+ const startedAt = Date.now();
1092
+ const tryOpen = () => {
1093
+ if (cancelled) return;
1094
+ const handle = getSalesAIHandle();
1095
+ if (handle) {
1096
+ handle.open({
1097
+ query,
1098
+ context: { ...agentContext, ...handoffContext }
1099
+ });
1100
+ return;
1101
+ }
1102
+ if (Date.now() - startedAt >= HANDLE_TIMEOUT_MS) {
1103
+ onUnavailable();
1104
+ return;
1105
+ }
1106
+ timer = setTimeout(tryOpen, HANDLE_POLL_MS);
1107
+ };
1108
+ tryOpen();
1109
+ return () => {
1110
+ cancelled = true;
1111
+ if (timer !== void 0) clearTimeout(timer);
1112
+ };
1113
+ }, [query]);
1114
+ }
1115
+ function NuiAgentPanel({
1116
+ agent,
1117
+ query,
1118
+ handoffContext,
1119
+ onUnavailable
1120
+ }) {
1121
+ useHandoff({
1122
+ query,
1123
+ handoffContext,
1124
+ agentContext: agent.context,
1125
+ onUnavailable
1126
+ });
1127
+ return /* @__PURE__ */ jsx(AgentErrorBoundary, { onError: onUnavailable, children: /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
1128
+ SalesAIChatWidget,
1129
+ {
1130
+ appKey: agent.appKey,
1131
+ apiBaseUrl: agent.apiBaseUrl,
1132
+ theme: agent.theme ?? "nui-light",
1133
+ defaultOpen: true,
1134
+ hideFab: true,
1135
+ placement: "host",
1136
+ ...agent.language === void 0 ? {} : { language: agent.language },
1137
+ ...agent.renderProduct === void 0 ? {} : { renderProduct: agent.renderProduct }
1138
+ }
1139
+ ) }) });
1140
+ }
1141
+ var SUBMIT_WAIT_TIMEOUT_MS = 2e3;
1142
+ function uniqueRecentSearches(queries) {
1143
+ const seen = /* @__PURE__ */ new Set();
1144
+ return queries.filter((query) => {
1145
+ const key = query.trim().toLowerCase();
1146
+ if (!key || seen.has(key)) return false;
1147
+ seen.add(key);
1148
+ return true;
1149
+ });
1150
+ }
1151
+ function ProductSearch({
1152
+ isOpen,
1153
+ onClose,
1154
+ service,
1155
+ navigate,
1156
+ isAuthenticated,
1157
+ agent,
1158
+ logo,
1159
+ cancelLabel,
1160
+ fallbackImageUrl,
1161
+ copy,
1162
+ gtmContext
1163
+ }) {
1164
+ const [flag, setFlag] = useState(void 0);
1165
+ const [handoff, setHandoff] = useState(null);
1166
+ const agentQuery = handoff?.query ?? null;
1167
+ const [pendingTerm, setPendingTerm] = useState(null);
1168
+ const [recentSearches, setRecentSearches] = useState([]);
1169
+ const search = useSearchSuggestions({
1170
+ service,
1171
+ enabled: isOpen && agentQuery === null
1172
+ });
1173
+ const {
1174
+ clearQuery,
1175
+ didYouMean,
1176
+ emptyFetched,
1177
+ hasMoreResults,
1178
+ loading,
1179
+ query,
1180
+ settledQuery,
1181
+ suggestionFetchFailed,
1182
+ suggestions,
1183
+ updateQuery
1184
+ } = search;
1185
+ const enabled = isNuiSearchEnabled({ isAuthenticated, flag });
1186
+ const items = getVisibleSuggestions({
1187
+ didYouMean,
1188
+ suggestions
1189
+ });
1190
+ const showDidYouMean = didYouMean.length > 0;
1191
+ useEffect(() => {
1192
+ if (isOpen) setFlag(resolveNuiSearchFlag());
1193
+ }, [isOpen]);
1194
+ useEffect(() => {
1195
+ if (isOpen) {
1196
+ setRecentSearches(
1197
+ uniqueRecentSearches(service.getRecentSearches())
1198
+ );
1199
+ }
1200
+ }, [isOpen, service, agentQuery]);
1201
+ const close = useCallback(() => {
1202
+ setHandoff(null);
1203
+ setPendingTerm(null);
1204
+ clearQuery();
1205
+ onClose();
1206
+ }, [clearQuery, onClose]);
1207
+ useEffect(() => {
1208
+ if (!isOpen) {
1209
+ setHandoff(null);
1210
+ setPendingTerm(null);
1211
+ clearQuery();
1212
+ }
1213
+ }, [isOpen, clearQuery]);
1214
+ const navigateTo = useCallback(
1215
+ (path) => {
1216
+ if (!path || path === "action-handled" || path === "action-pending") {
1217
+ return;
1218
+ }
1219
+ navigate(path);
1220
+ close();
1221
+ },
1222
+ [navigate, close]
1223
+ );
1224
+ const trackSemantic = useCallback(
1225
+ (productResultsData) => {
1226
+ trackProductSearch({
1227
+ ...gtmContext,
1228
+ searchType: SEARCH_GTM_SEARCH_TYPES.SEMANTIC,
1229
+ productResultsData
1230
+ });
1231
+ },
1232
+ [gtmContext]
1233
+ );
1234
+ const runSearch = useCallback(
1235
+ (term) => {
1236
+ trackSemantic(items.length > 0 ? items : { query: term });
1237
+ navigateTo(service.submitProductSearch(term));
1238
+ },
1239
+ [items, navigateTo, service, trackSemantic]
1240
+ );
1241
+ const decide = useCallback(
1242
+ (term) => decideSearchRoute({
1243
+ enabled,
1244
+ snapshot: {
1245
+ query: term,
1246
+ loading,
1247
+ settledQuery,
1248
+ suggestions,
1249
+ suggestionFetchFailed
1250
+ }
1251
+ }),
1252
+ [enabled, loading, settledQuery, suggestions, suggestionFetchFailed]
1253
+ );
1254
+ const act = useCallback(
1255
+ (term, route) => {
1256
+ setPendingTerm(null);
1257
+ if (route === "handoff") {
1258
+ trackChatEntryPoint(gtmContext ?? {});
1259
+ setHandoff({
1260
+ query: term,
1261
+ didYouMean: didYouMean.map((item) => item.value)
1262
+ });
1263
+ return;
1264
+ }
1265
+ runSearch(term);
1266
+ },
1267
+ [didYouMean, gtmContext, runSearch]
1268
+ );
1269
+ const handleSubmit = useCallback(
1270
+ (value) => {
1271
+ const term = value.trim();
1272
+ if (!term) return;
1273
+ const route = decide(term);
1274
+ if (route === "wait") {
1275
+ setPendingTerm(term);
1276
+ return;
1277
+ }
1278
+ act(term, route);
1279
+ },
1280
+ [act, decide]
1281
+ );
1282
+ const latest = useRef({ act, decide });
1283
+ latest.current = { act, decide };
1284
+ useEffect(() => {
1285
+ if (pendingTerm === null) return void 0;
1286
+ const route = latest.current.decide(pendingTerm);
1287
+ if (route !== "wait") {
1288
+ latest.current.act(pendingTerm, route);
1289
+ return void 0;
1290
+ }
1291
+ const timer = setTimeout(
1292
+ () => latest.current.act(pendingTerm, "search"),
1293
+ SUBMIT_WAIT_TIMEOUT_MS
1294
+ );
1295
+ return () => clearTimeout(timer);
1296
+ }, [
1297
+ pendingTerm,
1298
+ loading,
1299
+ settledQuery,
1300
+ suggestions,
1301
+ suggestionFetchFailed
1302
+ ]);
1303
+ const handleSelect = useCallback(
1304
+ (option) => {
1305
+ if (isSuggestionDisabled(
1306
+ option
1307
+ )) {
1308
+ return;
1309
+ }
1310
+ const term = String(option["value"] ?? option["label"] ?? "");
1311
+ if (term.trim()) trackSemantic([option]);
1312
+ const suggestionOption = option;
1313
+ const href = service.getSuggestionHref(suggestionOption);
1314
+ navigateTo(
1315
+ href || service.submitProductSearch(term, suggestionOption)
1316
+ );
1317
+ },
1318
+ [navigateTo, service, trackSemantic]
1319
+ );
1320
+ const handleRunAction = useCallback(
1321
+ (option) => {
1322
+ if (isSuggestionDisabled(
1323
+ option
1324
+ )) {
1325
+ return;
1326
+ }
1327
+ const result = service.activateSuggestionAction(
1328
+ option
1329
+ );
1330
+ void Promise.resolve(result).then(navigateTo).catch(() => void 0);
1331
+ },
1332
+ [navigateTo, service]
1333
+ );
1334
+ const handleSeeMore = useCallback(() => {
1335
+ const term = query.trim();
1336
+ if (term) navigateTo(service.viewMoreResults({ query: term }));
1337
+ }, [navigateTo, query, service]);
1338
+ const handleRecentSelect = useCallback(
1339
+ (recentQuery) => {
1340
+ trackSemantic({ query: recentQuery });
1341
+ navigateTo(service.submitProductSearch(recentQuery));
1342
+ },
1343
+ [navigateTo, service, trackSemantic]
1344
+ );
1345
+ const handleClearRecent = useCallback(() => {
1346
+ service.clearRecentSearches();
1347
+ setRecentSearches([]);
1348
+ }, [service]);
1349
+ const handleAgentUnavailable = useCallback(() => {
1350
+ if (agentQuery !== null)
1351
+ navigateTo(service.submitProductSearch(agentQuery));
1352
+ }, [agentQuery, navigateTo, service]);
1353
+ return /* @__PURE__ */ jsx(
1354
+ SearchModal,
1355
+ {
1356
+ isOpen,
1357
+ onClose: close,
1358
+ logo,
1359
+ ...cancelLabel === void 0 ? {} : { cancelLabel },
1360
+ ...fallbackImageUrl === void 0 ? {} : { fallbackImageUrl },
1361
+ ...copy === void 0 ? {} : { copy },
1362
+ input: {
1363
+ value: query,
1364
+ onChange: updateQuery,
1365
+ onSubmit: handleSubmit
1366
+ },
1367
+ suggestions: {
1368
+ items,
1369
+ loading,
1370
+ showNoResults: !loading && emptyFetched && items.length === 0,
1371
+ showDidYouMean,
1372
+ hasMore: hasMoreResults,
1373
+ query,
1374
+ onSelect: handleSelect,
1375
+ onRunAction: handleRunAction,
1376
+ onSeeMore: handleSeeMore
1377
+ },
1378
+ recentSearches: {
1379
+ items: recentSearches,
1380
+ onSelect: handleRecentSelect,
1381
+ onClear: handleClearRecent
1382
+ },
1383
+ agentPanel: handoff === null ? void 0 : /* @__PURE__ */ jsx(
1384
+ NuiAgentPanel,
1385
+ {
1386
+ agent,
1387
+ query: handoff.query,
1388
+ handoffContext: {
1389
+ source: "storefront_search",
1390
+ trigger: "zero_results",
1391
+ query: handoff.query,
1392
+ did_you_mean: handoff.didYouMean
1393
+ },
1394
+ onUnavailable: handleAgentUnavailable
1395
+ }
1396
+ )
1397
+ }
1398
+ );
1399
+ }
1400
+
1401
+ export { CATALOG_SUGGESTIONS_PATH, DEBOUNCE_MS, DEFAULT_SEARCH_PATH, DEFAULT_SUGGESTION_PAGE, DEFAULT_SUGGESTION_SIZE, MAX_VISIBLE_SUGGESTIONS, NUI_SEARCH_FLAG, ProductSearch, RECENT_SEARCHES_DEFAULT_LIMIT, RECENT_SEARCHES_PREFIX, SEARCH_GTM_EVENTS, SEARCH_GTM_SEARCH_TYPES, SEARCH_GTM_USER_STATUS, SEARCH_PLACEHOLDER, STOREFRONT_SHOPPING_CONTEXT, SUBMIT_WAIT_TIMEOUT_MS, TRIGGER_PLACEHOLDER, createSearchService, decideSearchRoute, getImageFromProperty, getIngredientTerms, getLocaleFromUrl, getSeeMoreResultsPayload, getVisibleSuggestions, isCartActionDisabled, isNuiSearchEnabled, isSellableProductStatus, isSuggestionDisabled, mapCatalogProductToSuggestion, normalizeDidYouMean, pushGtmEvent, resolveApiGatewayPath, resolveNuiSearchFlag, resolveSuggestionImageSrc, trackChatEntryPoint, trackErrorPopup, trackProductSearch, trackSearchType, useSearchSuggestions };
1927
1402
  //# sourceMappingURL=index.mjs.map
1928
1403
  //# sourceMappingURL=index.mjs.map