@rebuy/rebuy-hydrogen 3.0.0-beta.19 → 3.0.0-beta.20

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.js CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  RebuyCompleteTheLook: () => RebuyCompleteTheLook,
34
34
  RebuyConfigProvider: () => RebuyConfigProvider,
35
35
  RebuyDynamicBundleProducts: () => RebuyDynamicBundleProducts,
36
+ RebuyGiftWithPurchase: () => RebuyGiftWithPurchase,
36
37
  RebuyHydrogenContextProvider: () => RebuyHydrogenContextProvider,
37
38
  RebuyHydrogenReactContextProvider: () => RebuyHydrogenReactContextProvider,
38
39
  RebuyProductAddOns: () => RebuyProductAddOns,
@@ -2722,6 +2723,11 @@ var createContextParameters = ({
2722
2723
  legacyCartCostValue = legacyCartCost;
2723
2724
  legacyCartIdValue = legacyCartId;
2724
2725
  }
2726
+ let shopifyCustomerId;
2727
+ if (solidifiedHydrogenCart?.buyerIdentity?.customer?.id) {
2728
+ const customerId = Utilities.getIdFromGraphUrl(solidifiedHydrogenCart.buyerIdentity.customer.id, "Customer");
2729
+ shopifyCustomerId = customerId?.toString();
2730
+ }
2725
2731
  const contextParametersOutput = {
2726
2732
  cache_key: cacheKey,
2727
2733
  cart: void 0,
@@ -2742,6 +2748,7 @@ var createContextParameters = ({
2742
2748
  hydrogenReactCartError,
2743
2749
  hydrogenReactCartStatus,
2744
2750
  isHydrogenReact,
2751
+ shopify_customer_id: shopifyCustomerId,
2745
2752
  time: queryObject.time ?? "",
2746
2753
  url: windowUrl
2747
2754
  };
@@ -2767,7 +2774,7 @@ var createContextParameters = ({
2767
2774
  product_id: line.merchandise?.product?.id ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, "Product")?.toString() || "" : "",
2768
2775
  properties: "",
2769
2776
  quantity: line.quantity,
2770
- variant_id: line.merchandise?.id ? Utilities.getIdFromGraphUrl(line.merchandise.product.id, "Product")?.toString() || "" : ""
2777
+ variant_id: line.merchandise?.id ? Utilities.getIdFromGraphUrl(line.merchandise.id, "ProductVariant")?.toString() || "" : ""
2771
2778
  };
2772
2779
  if (line.attributes?.length) {
2773
2780
  const validLineAttributes = line.attributes.filter(
@@ -2804,8 +2811,11 @@ var RebuyHydrogenContext = ({
2804
2811
  } = useRebuyConfig();
2805
2812
  const warningLogged2 = (0, import_react5.useRef)(false);
2806
2813
  const location = (0, import_react_router.useLocation)();
2807
- const queryObject = Utilities2.queryStringToObject(location.search);
2808
- const windowUrl = `${shop}${location.pathname}${location.search}`;
2814
+ const queryObject = (0, import_react5.useMemo)(() => Utilities2.queryStringToObject(location.search), [location.search]);
2815
+ const windowUrl = (0, import_react5.useMemo)(
2816
+ () => `${shop}${location.pathname}${location.search}`,
2817
+ [shop, location.pathname, location.search]
2818
+ );
2809
2819
  const contextParameters = (0, import_react5.useMemo)(
2810
2820
  () => createContextParameters({
2811
2821
  cacheKey: rebuyConfig?.shop?.cache_key,
@@ -3963,6 +3973,10 @@ var useCartItemFeatures = ({ config, line }) => {
3963
3973
  const shouldHideQuantitySelector = (0, import_react8.useMemo)(() => {
3964
3974
  if (isTieredProgressBarGiftItem(line)) return true;
3965
3975
  if (isCartItemHiddenByStandardLogic(line)) return true;
3976
+ const hasHideQuantitySelectorAttribute = line.attributes?.some(
3977
+ (attr) => attr.key === "_r_gwp_hide_qty" /* HIDE_QUANTITY_SELECTOR_GWP_ITEM */ && attr.value === "true"
3978
+ );
3979
+ if (hasHideQuantitySelectorAttribute) return true;
3966
3980
  return false;
3967
3981
  }, [line]);
3968
3982
  const isBmsmGloballyEnabled = (0, import_react8.useMemo)(() => isBMSMEnabled(config), [config]);
@@ -9611,9 +9625,433 @@ var RebuyDynamicBundleProducts = (props) => {
9611
9625
  ] });
9612
9626
  };
9613
9627
 
9628
+ // src/widgets/RebuyGiftWithPurchase/RebuyGiftWithPurchase.tsx
9629
+ var import_rebuy4 = require("@rebuy/rebuy");
9630
+ var import_react38 = require("react");
9631
+ var import_react_router9 = require("react-router");
9632
+
9633
+ // src/widgets/RebuyGiftWithPurchase/store/giftWithPurchaseStore.ts
9634
+ var import_zustand2 = require("zustand");
9635
+ var import_middleware = require("zustand/middleware");
9636
+ var initialState = {
9637
+ lastSyncedGiftsByWidget: {},
9638
+ lastSyncTimestampByWidget: {},
9639
+ pendingAdditionsByWidget: {},
9640
+ syncStatusByWidget: {}
9641
+ };
9642
+ var useGiftWithPurchaseStore = (0, import_zustand2.create)()(
9643
+ (0, import_middleware.subscribeWithSelector)((set, get) => ({
9644
+ ...initialState,
9645
+ clearPendingAddition: (widgetId, variantId) => {
9646
+ rebuyDebugLog.log(
9647
+ "rebuy-widget" /* WIDGET */,
9648
+ `[GWP Store] Clearing pending addition for widget ${widgetId}: ${variantId}`
9649
+ );
9650
+ set((state) => {
9651
+ const currentPending = state.pendingAdditionsByWidget[widgetId] || [];
9652
+ const newPending = currentPending.filter((id) => id !== variantId);
9653
+ return {
9654
+ pendingAdditionsByWidget: {
9655
+ ...state.pendingAdditionsByWidget,
9656
+ [widgetId]: newPending
9657
+ }
9658
+ };
9659
+ });
9660
+ },
9661
+ getLastSyncedGifts: (widgetId) => {
9662
+ return get().lastSyncedGiftsByWidget[widgetId] || [];
9663
+ },
9664
+ getPendingAdditions: (widgetId) => {
9665
+ return get().pendingAdditionsByWidget[widgetId] || [];
9666
+ },
9667
+ getSyncStatus: (widgetId) => {
9668
+ return get().syncStatusByWidget[widgetId] || "idle";
9669
+ },
9670
+ reset: (widgetId) => {
9671
+ rebuyDebugLog.log("rebuy-widget" /* WIDGET */, `[GWP Store] Resetting state for widget ${widgetId}`);
9672
+ set((state) => {
9673
+ const newSyncStatus = { ...state.syncStatusByWidget };
9674
+ const newLastSyncedGifts = { ...state.lastSyncedGiftsByWidget };
9675
+ const newLastSyncTimestamp = { ...state.lastSyncTimestampByWidget };
9676
+ const newPendingAdditions = { ...state.pendingAdditionsByWidget };
9677
+ delete newSyncStatus[widgetId];
9678
+ delete newLastSyncedGifts[widgetId];
9679
+ delete newLastSyncTimestamp[widgetId];
9680
+ delete newPendingAdditions[widgetId];
9681
+ return {
9682
+ lastSyncedGiftsByWidget: newLastSyncedGifts,
9683
+ lastSyncTimestampByWidget: newLastSyncTimestamp,
9684
+ pendingAdditionsByWidget: newPendingAdditions,
9685
+ syncStatusByWidget: newSyncStatus
9686
+ };
9687
+ });
9688
+ },
9689
+ resetAll: () => {
9690
+ rebuyDebugLog.log("rebuy-widget" /* WIDGET */, "[GWP Store] Resetting all state");
9691
+ set(initialState);
9692
+ },
9693
+ setLastSyncedGifts: (widgetId, giftIds) => {
9694
+ rebuyDebugLog.log(
9695
+ "rebuy-widget" /* WIDGET */,
9696
+ `[GWP Store] Setting last synced gifts for widget ${widgetId}:`,
9697
+ giftIds
9698
+ );
9699
+ set((state) => ({
9700
+ lastSyncedGiftsByWidget: {
9701
+ ...state.lastSyncedGiftsByWidget,
9702
+ [widgetId]: giftIds
9703
+ }
9704
+ }));
9705
+ },
9706
+ setPendingAdditions: (widgetId, variantIds) => {
9707
+ rebuyDebugLog.log(
9708
+ "rebuy-widget" /* WIDGET */,
9709
+ `[GWP Store] Setting pending additions for widget ${widgetId}:`,
9710
+ variantIds
9711
+ );
9712
+ set((state) => ({
9713
+ pendingAdditionsByWidget: {
9714
+ ...state.pendingAdditionsByWidget,
9715
+ [widgetId]: variantIds
9716
+ }
9717
+ }));
9718
+ },
9719
+ setSyncStatus: (widgetId, status) => {
9720
+ rebuyDebugLog.log("rebuy-widget" /* WIDGET */, `[GWP Store] Setting sync status for widget ${widgetId} to ${status}`);
9721
+ set((state) => ({
9722
+ // Update timestamp when starting a sync
9723
+ lastSyncTimestampByWidget: status === "syncing" ? { ...state.lastSyncTimestampByWidget, [widgetId]: Date.now() } : state.lastSyncTimestampByWidget,
9724
+ syncStatusByWidget: {
9725
+ ...state.syncStatusByWidget,
9726
+ [widgetId]: status
9727
+ }
9728
+ }));
9729
+ },
9730
+ shouldSync: (widgetId) => {
9731
+ const state = get();
9732
+ const status = state.syncStatusByWidget[widgetId] || "idle";
9733
+ if (status !== "idle") {
9734
+ rebuyDebugLog.log(
9735
+ "rebuy-widget" /* WIDGET */,
9736
+ `[GWP Store] shouldSync = false for widget ${widgetId}: status is ${status}`
9737
+ );
9738
+ return false;
9739
+ }
9740
+ const lastSync = state.lastSyncTimestampByWidget[widgetId];
9741
+ if (lastSync && Date.now() - lastSync < 2e3) {
9742
+ rebuyDebugLog.log(
9743
+ "rebuy-widget" /* WIDGET */,
9744
+ `[GWP Store] shouldSync = false for widget ${widgetId}: synced ${Date.now() - lastSync}ms ago`
9745
+ );
9746
+ return false;
9747
+ }
9748
+ return true;
9749
+ }
9750
+ }))
9751
+ );
9752
+
9753
+ // src/widgets/RebuyGiftWithPurchase/utils.ts
9754
+ var prepareGiftItems = (variantGids, widgetId, settings = null) => {
9755
+ return variantGids.map((variantGid) => {
9756
+ const attributes = [
9757
+ { key: "_widget_id", value: String(widgetId) },
9758
+ { key: "_attribution", value: "Rebuy Gift with Purchase" /* GIFT_WITH_PURCHASE */ }
9759
+ ];
9760
+ if (settings?.hide_quantity_selector) {
9761
+ attributes.push({ key: "_r_gwp_hide_qty" /* HIDE_QUANTITY_SELECTOR_GWP_ITEM */, value: "true" });
9762
+ }
9763
+ return {
9764
+ attributes,
9765
+ merchandiseId: variantGid,
9766
+ quantity: 1
9767
+ };
9768
+ });
9769
+ };
9770
+ var getGiftDeclineKey = (widgetId, productId, cartToken) => {
9771
+ const token = cartToken || "default";
9772
+ return `rebuy_gwp_${widgetId}_${token}_${productId}`;
9773
+ };
9774
+ var isGiftDeclined = (widgetId, productId, cartToken) => {
9775
+ const key = getGiftDeclineKey(widgetId, productId, cartToken);
9776
+ return sessionStorage.getItem(key) === "declined";
9777
+ };
9778
+ var hasCartActions = (actions) => {
9779
+ return Boolean(actions?.linesAdd && actions?.linesRemove);
9780
+ };
9781
+
9782
+ // src/widgets/RebuyGiftWithPurchase/RebuyGiftWithPurchase.tsx
9783
+ var RebuyGiftWithPurchase = (props) => {
9784
+ const { widgetId } = props;
9785
+ const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
9786
+ const rebuyContext = (0, import_react38.useContext)(RebuyContext);
9787
+ const contextParams = rebuyContext?.contextParameters;
9788
+ const hydrogenCart = contextParams?.hydrogenCart;
9789
+ const cartToken = hydrogenCart?.id;
9790
+ const isHydrogenReact = contextParams?.isHydrogenReact;
9791
+ const hydrogenReactCartActions = contextParams?.hydrogenReactCartActions;
9792
+ const cartFetcher = (0, import_react_router9.useFetcher)();
9793
+ const [settings, setSettings] = (0, import_react38.useState)(null);
9794
+ const [products, setProducts] = (0, import_react38.useState)([]);
9795
+ const [loading, setLoading] = (0, import_react38.useState)(true);
9796
+ const _syncStatus = useGiftWithPurchaseStore((state) => state.getSyncStatus(String(widgetId)));
9797
+ const shouldSync = useGiftWithPurchaseStore((state) => state.shouldSync);
9798
+ const setSyncStatus = useGiftWithPurchaseStore((state) => state.setSyncStatus);
9799
+ const setLastSyncedGifts = useGiftWithPurchaseStore((state) => state.setLastSyncedGifts);
9800
+ const setPendingAdditions = useGiftWithPurchaseStore((state) => state.setPendingAdditions);
9801
+ const _clearPendingAddition = useGiftWithPurchaseStore((state) => state.clearPendingAddition);
9802
+ const clientRef = (0, import_react38.useRef)(null);
9803
+ const isMountedRef = (0, import_react38.useRef)(true);
9804
+ const lastCartHashRef = (0, import_react38.useRef)("");
9805
+ const cacheKey = rebuyConfig?.shop?.cache_key || contextParams?.cache_key || "";
9806
+ (0, import_react38.useEffect)(() => {
9807
+ if (!apiKey || configLoadingStatus !== "success" || clientRef.current) return;
9808
+ const client = new import_rebuy4.RebuyClient(apiKey);
9809
+ if (contextParams) {
9810
+ const filteredParams = filterContextForWidgetEndpoints(contextParams, void 0);
9811
+ client.setContextParameters(filteredParams);
9812
+ }
9813
+ clientRef.current = client;
9814
+ }, [apiKey, configLoadingStatus, contextParams]);
9815
+ (0, import_react38.useEffect)(() => {
9816
+ if (!widgetId || !clientRef.current || configLoadingStatus !== "success") return;
9817
+ const fetchSettings = async () => {
9818
+ try {
9819
+ const params = { id: widgetId };
9820
+ if (cacheKey) {
9821
+ params.cache_key = cacheKey;
9822
+ }
9823
+ const response = await clientRef.current.getShieldedAsset("/api/v1/widgets/settings", params);
9824
+ const parseResult = widgetSettingsSchema.safeParse(response?.data);
9825
+ if (!parseResult.success) {
9826
+ throw new Error(`Invalid settings data: ${parseResult.error.message}`);
9827
+ }
9828
+ const fetchedSettings = parseResult.data;
9829
+ if (fetchedSettings.type !== "gift_with_purchase") {
9830
+ throw new Error(
9831
+ `Widget ${widgetId} is not a gift_with_purchase widget (type: ${fetchedSettings.type})`
9832
+ );
9833
+ }
9834
+ setSettings(fetchedSettings);
9835
+ } catch (e) {
9836
+ console.error(`[RebuyGiftWithPurchase] Error fetching settings for widget ${widgetId}:`, e);
9837
+ setSettings(null);
9838
+ } finally {
9839
+ setLoading(false);
9840
+ }
9841
+ };
9842
+ fetchSettings();
9843
+ }, [widgetId, cacheKey, configLoadingStatus]);
9844
+ (0, import_react38.useEffect)(() => {
9845
+ if (!settings || !clientRef.current || !contextParams?.cart) return;
9846
+ const cartHash = JSON.stringify(
9847
+ contextParams.cart.items?.map((item) => ({
9848
+ product_id: item.product_id,
9849
+ quantity: item.quantity,
9850
+ variant_id: item.variant_id
9851
+ })) || []
9852
+ );
9853
+ if (cartHash === lastCartHashRef.current) return;
9854
+ lastCartHashRef.current = cartHash;
9855
+ const fetchProducts = async () => {
9856
+ try {
9857
+ const cartItems = contextParams.cart?.items || [];
9858
+ const productIds = cartItems.map((item) => item.product_id).filter(Boolean);
9859
+ const variantIds = cartItems.map((item) => item.variant_id).filter(Boolean);
9860
+ const params = {
9861
+ cache_key: cacheKey,
9862
+ key: apiKey,
9863
+ limit: settings.limit || 8
9864
+ };
9865
+ if (productIds.length > 0) {
9866
+ params.shopify_product_ids = productIds.join(",");
9867
+ }
9868
+ if (variantIds.length > 0) {
9869
+ params.shopify_variant_ids = variantIds.join(",");
9870
+ }
9871
+ params.cart_token = contextParams.cart?.token;
9872
+ params.cart_subtotal = contextParams.cart?.subtotal;
9873
+ params.cart_item_count = contextParams.cart?.item_count;
9874
+ params.cart_line_count = contextParams.cart?.line_count;
9875
+ params.cart = {
9876
+ attributes: contextParams.cart?.attributes ? encodeURIComponent(JSON.stringify(contextParams.cart.attributes)) : "",
9877
+ item_count: contextParams.cart?.item_count || 0,
9878
+ items: cartItems.map((item) => ({
9879
+ product_id: item.product_id,
9880
+ properties: item.properties ? encodeURIComponent(JSON.stringify(item.properties)) : "",
9881
+ quantity: item.quantity,
9882
+ variant_id: item.variant_id
9883
+ })),
9884
+ line_count: contextParams.cart?.line_count || 0,
9885
+ notes: contextParams.cart?.note || "",
9886
+ subtotal: contextParams.cart?.subtotal || 0,
9887
+ token: contextParams.cart?.token || ""
9888
+ };
9889
+ let endpoint = settings.endpoint;
9890
+ if (endpoint && endpoint.startsWith("/") && !endpoint.startsWith("/api/v1/")) {
9891
+ if (endpoint.startsWith("/custom") || endpoint.startsWith("/rules")) {
9892
+ endpoint = `/api/v1${endpoint}`;
9893
+ }
9894
+ }
9895
+ const { data } = await clientRef.current.getStorefrontData(endpoint, params);
9896
+ const fetchedProducts = Array.isArray(data) ? data : [];
9897
+ setProducts(fetchedProducts);
9898
+ } catch (e) {
9899
+ console.error(`[RebuyGiftWithPurchase] Error fetching products:`, e);
9900
+ if (isMountedRef.current) {
9901
+ setProducts([]);
9902
+ }
9903
+ }
9904
+ };
9905
+ fetchProducts();
9906
+ }, [settings, apiKey, cacheKey, contextParams?.cart]);
9907
+ const manageGifts = (0, import_react38.useCallback)(() => {
9908
+ const widgetIdStr = String(widgetId);
9909
+ if (!shouldSync(widgetIdStr)) return;
9910
+ if (!hydrogenCart) return;
9911
+ setSyncStatus(widgetIdStr, "syncing");
9912
+ try {
9913
+ const cartLines = hydrogenCart.lines?.nodes || hydrogenCart.lines?.edges?.map((edge) => edge.node) || [];
9914
+ const hasInputProducts = (contextParams?.cart?.items?.length || 0) > 0;
9915
+ const allowGiftsWithoutPurchase = settings?.allow_gifts_without_purchase !== false;
9916
+ const giftLinesFromWidget = cartLines.filter(
9917
+ (line) => line.attributes?.some((attr) => attr.key === "_widget_id" && attr.value === String(widgetId))
9918
+ );
9919
+ const rebuyCartItems = contextParams?.cart?.items || [];
9920
+ const existingGiftVariantIds = /* @__PURE__ */ new Set();
9921
+ for (const item of rebuyCartItems) {
9922
+ if (item.attributes?.some((attr) => attr.key === "_widget_id" && attr.value === String(widgetId))) {
9923
+ existingGiftVariantIds.add(String(item.variant_id));
9924
+ }
9925
+ }
9926
+ const hasOnlyGifts = cartLines.length > 0 && cartLines.length === giftLinesFromWidget.length;
9927
+ const shouldRemoveAllGifts = !hasInputProducts || products.length === 0 || hasOnlyGifts && !allowGiftsWithoutPurchase;
9928
+ if (shouldRemoveAllGifts) {
9929
+ if (giftLinesFromWidget.length > 0) {
9930
+ const lineIdsToRemove = giftLinesFromWidget.map((line) => line.id);
9931
+ if (isHydrogenReact && hasCartActions(hydrogenReactCartActions)) {
9932
+ hydrogenReactCartActions.linesRemove(lineIdsToRemove);
9933
+ } else {
9934
+ cartFetcher.submit(
9935
+ {
9936
+ action: "cartLinesRemove",
9937
+ data: { lineIds: lineIdsToRemove }
9938
+ },
9939
+ {
9940
+ action: "/cart",
9941
+ encType: "application/json",
9942
+ method: "POST"
9943
+ }
9944
+ );
9945
+ }
9946
+ }
9947
+ return;
9948
+ }
9949
+ const giftsToEnsure = /* @__PURE__ */ new Map();
9950
+ for (const giftProduct of products) {
9951
+ let variantId;
9952
+ const productWithEdges = giftProduct;
9953
+ if (productWithEdges.variants?.nodes?.[0]?.id) {
9954
+ variantId = String(productWithEdges.variants.nodes[0].id);
9955
+ } else if (productWithEdges.variants?.edges?.[0]?.node?.id) {
9956
+ variantId = String(productWithEdges.variants.edges[0].node.id);
9957
+ }
9958
+ if (variantId) {
9959
+ giftsToEnsure.set(variantId, String(giftProduct.id));
9960
+ }
9961
+ }
9962
+ const variantsToAdd = [];
9963
+ for (const [variantId, productId] of giftsToEnsure) {
9964
+ const inHydrogenCart = giftLinesFromWidget.some((line) => line.merchandise?.id === variantId);
9965
+ const inRebuyCart = existingGiftVariantIds.has(variantId);
9966
+ const alreadyInCart = inHydrogenCart || inRebuyCart;
9967
+ if (!hasInputProducts && !allowGiftsWithoutPurchase) {
9968
+ continue;
9969
+ }
9970
+ if (!alreadyInCart && !isGiftDeclined(String(widgetId), productId, cartToken)) {
9971
+ variantsToAdd.push(variantId);
9972
+ }
9973
+ }
9974
+ if (variantsToAdd.length > 0) {
9975
+ setPendingAdditions(widgetIdStr, variantsToAdd);
9976
+ const itemsToAdd = prepareGiftItems(variantsToAdd, String(widgetId), settings);
9977
+ if (isHydrogenReact && hasCartActions(hydrogenReactCartActions)) {
9978
+ hydrogenReactCartActions.linesAdd(itemsToAdd);
9979
+ } else {
9980
+ cartFetcher.submit(
9981
+ {
9982
+ action: "cartLinesAdd",
9983
+ data: { lines: itemsToAdd }
9984
+ },
9985
+ {
9986
+ action: "/cart",
9987
+ encType: "application/json",
9988
+ method: "POST"
9989
+ }
9990
+ );
9991
+ }
9992
+ }
9993
+ const validVariantIds = new Set(Array.from(giftsToEnsure.keys()));
9994
+ const linesToRemove = giftLinesFromWidget.filter((line) => {
9995
+ const lineVariantId = line.merchandise?.id;
9996
+ return lineVariantId && !validVariantIds.has(lineVariantId);
9997
+ });
9998
+ if (linesToRemove.length > 0) {
9999
+ const lineIdsToRemove = linesToRemove.map((line) => line.id);
10000
+ if (isHydrogenReact && hasCartActions(hydrogenReactCartActions)) {
10001
+ hydrogenReactCartActions.linesRemove(lineIdsToRemove);
10002
+ } else {
10003
+ cartFetcher.submit(
10004
+ {
10005
+ action: "cartLinesRemove",
10006
+ data: { lineIds: lineIdsToRemove }
10007
+ },
10008
+ {
10009
+ action: "/cart",
10010
+ encType: "application/json",
10011
+ method: "POST"
10012
+ }
10013
+ );
10014
+ }
10015
+ }
10016
+ const currentGiftIds = Array.from(giftsToEnsure.values());
10017
+ setLastSyncedGifts(widgetIdStr, currentGiftIds);
10018
+ } catch (error) {
10019
+ console.error("[RebuyGiftWithPurchase] Error managing gifts:", error);
10020
+ } finally {
10021
+ setTimeout(() => setSyncStatus(widgetIdStr, "idle"), 1e3);
10022
+ }
10023
+ }, [
10024
+ hydrogenCart,
10025
+ products,
10026
+ widgetId,
10027
+ cartToken,
10028
+ isHydrogenReact,
10029
+ hydrogenReactCartActions,
10030
+ cartFetcher,
10031
+ contextParams?.cart?.items,
10032
+ shouldSync,
10033
+ setSyncStatus,
10034
+ setPendingAdditions,
10035
+ setLastSyncedGifts,
10036
+ settings
10037
+ ]);
10038
+ (0, import_react38.useEffect)(() => {
10039
+ if (!loading && settings && hydrogenCart) {
10040
+ const timer = setTimeout(manageGifts, 500);
10041
+ return () => clearTimeout(timer);
10042
+ }
10043
+ }, [products, hydrogenCart, loading, settings, manageGifts]);
10044
+ (0, import_react38.useEffect)(() => {
10045
+ return () => {
10046
+ isMountedRef.current = false;
10047
+ };
10048
+ }, []);
10049
+ return null;
10050
+ };
10051
+
9614
10052
  // src/widgets/RebuyProductAddOns/RebuyProductAddOns.tsx
9615
10053
  var import_hydrogen_react3 = require("@shopify/hydrogen-react");
9616
- var import_react38 = require("react");
10054
+ var import_react39 = require("react");
9617
10055
 
9618
10056
  // src/widgets/RebuyProductAddOns/RebuyProductAddOnCard.tsx
9619
10057
  var import_hydrogen10 = require("@shopify/hydrogen");
@@ -9690,11 +10128,11 @@ var RebuyProductAddOns = (props) => {
9690
10128
  const { isHydrogenReact, product, products } = useRebuyWidget();
9691
10129
  const productTitleClean = customTitle.replace("{product_title}", product?.title ?? "");
9692
10130
  const withProductTextClean = withProductText.replace("{product_title}", product?.title ?? "");
9693
- const [addedItems, setAddedItems] = (0, import_react38.useState)(products);
9694
- const [subtotalWithProduct, setSubtotalWithProduct] = (0, import_react38.useState)();
9695
- const [subtotalWithOutProduct, setSubtotalWithOutProduct] = (0, import_react38.useState)();
10131
+ const [addedItems, setAddedItems] = (0, import_react39.useState)(products);
10132
+ const [subtotalWithProduct, setSubtotalWithProduct] = (0, import_react39.useState)();
10133
+ const [subtotalWithOutProduct, setSubtotalWithOutProduct] = (0, import_react39.useState)();
9696
10134
  const convertedProduct = convertToRebuyProduct(isHydrogenReact || false, product);
9697
- (0, import_react38.useEffect)(() => {
10135
+ (0, import_react39.useEffect)(() => {
9698
10136
  let initialTotal = 0;
9699
10137
  let currencyCode = "USD";
9700
10138
  products.map((product2) => {
@@ -9724,7 +10162,7 @@ var RebuyProductAddOns = (props) => {
9724
10162
  setAddedItems(products);
9725
10163
  }
9726
10164
  }, [products, product, isHydrogenReact, includeMainProduct]);
9727
- const handleChange = (0, import_react38.useCallback)(
10165
+ const handleChange = (0, import_react39.useCallback)(
9728
10166
  (event, product2) => {
9729
10167
  const newProducts = [...products];
9730
10168
  const productIndex = newProducts.findIndex((p) => p.id === product2.id);
@@ -9743,7 +10181,7 @@ var RebuyProductAddOns = (props) => {
9743
10181
  },
9744
10182
  [products]
9745
10183
  );
9746
- (0, import_react38.useEffect)(() => {
10184
+ (0, import_react39.useEffect)(() => {
9747
10185
  let total = 0;
9748
10186
  let currencyCode = "USD";
9749
10187
  addedItems.forEach((item) => {
@@ -9851,13 +10289,13 @@ var RebuyProductRecommendations = (props) => {
9851
10289
  };
9852
10290
 
9853
10291
  // src/widgets/RebuyProductViewed/RebuyProductViewed.tsx
9854
- var import_rebuy4 = require("@rebuy/rebuy");
10292
+ var import_rebuy5 = require("@rebuy/rebuy");
9855
10293
  var Utilities6 = __toESM(require("@rebuy/rebuy/utilities"), 1);
9856
- var import_react39 = require("react");
10294
+ var import_react40 = require("react");
9857
10295
 
9858
10296
  // src/zustandStores/productViewed.ts
9859
- var import_zustand2 = require("zustand");
9860
- var useProductViewedStore = (0, import_zustand2.create)((set) => ({
10297
+ var import_zustand3 = require("zustand");
10298
+ var useProductViewedStore = (0, import_zustand3.create)((set) => ({
9861
10299
  customerId: null,
9862
10300
  setCustomerId: (customerId) => set({ customerId }),
9863
10301
  setUuid: (uuid) => set({ uuid }),
@@ -9868,12 +10306,12 @@ var useProductViewedStore = (0, import_zustand2.create)((set) => ({
9868
10306
  var RebuyProductViewed = ({ ...props }) => {
9869
10307
  const { apiKey: apiKeyFromContext } = useRebuyConfig();
9870
10308
  const { customerId, product, productHandle, productId } = props;
9871
- const [event, setEvent] = (0, import_react39.useState)(null);
9872
- const [Rebuy, setRebuy] = (0, import_react39.useState)(null);
10309
+ const [event, setEvent] = (0, import_react40.useState)(null);
10310
+ const [Rebuy, setRebuy] = (0, import_react40.useState)(null);
9873
10311
  const shopifyProductId = product?.id ?? productId ?? null;
9874
- const [initialized, setInitialized] = (0, import_react39.useState)(false);
10312
+ const [initialized, setInitialized] = (0, import_react40.useState)(false);
9875
10313
  const { setCustomerId, setUuid } = useProductViewedStore();
9876
- const request = (0, import_react39.useMemo)(() => {
10314
+ const request = (0, import_react40.useMemo)(() => {
9877
10315
  const request2 = {
9878
10316
  parameters: {}
9879
10317
  };
@@ -9887,7 +10325,7 @@ var RebuyProductViewed = ({ ...props }) => {
9887
10325
  }
9888
10326
  return request2;
9889
10327
  }, [productHandle, shopifyProductId]);
9890
- (0, import_react39.useEffect)(() => {
10328
+ (0, import_react40.useEffect)(() => {
9891
10329
  const recordView = async () => {
9892
10330
  if (!Rebuy) {
9893
10331
  return;
@@ -9906,7 +10344,7 @@ var RebuyProductViewed = ({ ...props }) => {
9906
10344
  }
9907
10345
  };
9908
10346
  if (!initialized && apiKeyFromContext) {
9909
- const client = new import_rebuy4.RebuyClient(apiKeyFromContext);
10347
+ const client = new import_rebuy5.RebuyClient(apiKeyFromContext);
9910
10348
  setRebuy(client);
9911
10349
  setInitialized(true);
9912
10350
  return;
@@ -9921,9 +10359,9 @@ var RebuyProductViewed = ({ ...props }) => {
9921
10359
  };
9922
10360
 
9923
10361
  // src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.tsx
9924
- var import_rebuy5 = require("@rebuy/rebuy");
10362
+ var import_rebuy6 = require("@rebuy/rebuy");
9925
10363
  var import_hydrogen11 = require("@shopify/hydrogen");
9926
- var import_react40 = require("react");
10364
+ var import_react41 = require("react");
9927
10365
 
9928
10366
  // src/widgets/RebuyRecentlyViewedProducts/RebuyRecentlyViewedProducts.module.css
9929
10367
  var result27 = { "rebuy-recently-viewed-products-container": "RebuyRecentlyViewedProducts_rebuy-recently-viewed-products-container", "product-grid": "RebuyRecentlyViewedProducts_product-grid" };
@@ -9944,16 +10382,16 @@ var RebuyRecentlyViewedProducts = (props) => {
9944
10382
  } = props;
9945
10383
  const { customerId, uuid } = useProductViewedStore();
9946
10384
  const { apiKey, loadingStatus: configLoadingStatus, rebuyConfig } = useRebuyConfig();
9947
- const rebuyContext = (0, import_react40.useContext)(RebuyContext);
9948
- const [rebuyApiClient, setRebuyApiClient] = (0, import_react40.useState)(null);
9949
- const [initialized, setInitialized] = (0, import_react40.useState)(false);
9950
- const [products, setProducts] = (0, import_react40.useState)([]);
9951
- const [metadata, setMetadata] = (0, import_react40.useState)();
10385
+ const rebuyContext = (0, import_react41.useContext)(RebuyContext);
10386
+ const [rebuyApiClient, setRebuyApiClient] = (0, import_react41.useState)(null);
10387
+ const [initialized, setInitialized] = (0, import_react41.useState)(false);
10388
+ const [products, setProducts] = (0, import_react41.useState)([]);
10389
+ const [metadata, setMetadata] = (0, import_react41.useState)();
9952
10390
  const rebuyConfigKey = rebuyConfig?.shop?.cache_key;
9953
10391
  const endpoint = customerId && customerId !== "" ? `/api/v1/products/viewed?key=${rebuyConfigKey}&customer_id=${customerId}` : `/api/v1/products/viewed?key=${rebuyConfigKey}&uuid=${uuid}`;
9954
- (0, import_react40.useEffect)(() => {
10392
+ (0, import_react41.useEffect)(() => {
9955
10393
  if (!rebuyApiClient && apiKey && configLoadingStatus === "success") {
9956
- const client = new import_rebuy5.RebuyClient(apiKey);
10394
+ const client = new import_rebuy6.RebuyClient(apiKey);
9957
10395
  if (rebuyContext?.contextParameters) {
9958
10396
  const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);
9959
10397
  client.setContextParameters(filteredParams);
@@ -9965,13 +10403,13 @@ var RebuyRecentlyViewedProducts = (props) => {
9965
10403
  setInitialized(true);
9966
10404
  }
9967
10405
  }, [apiKey, rebuyApiClient, configLoadingStatus, options, rebuyContext, uuid, endpoint]);
9968
- (0, import_react40.useEffect)(() => {
10406
+ (0, import_react41.useEffect)(() => {
9969
10407
  if (rebuyApiClient && rebuyContext?.contextParameters) {
9970
10408
  const filteredParams = filterContextForWidgetEndpoints(rebuyContext.contextParameters, endpoint);
9971
10409
  rebuyApiClient.setContextParameters(filteredParams);
9972
10410
  }
9973
10411
  }, [rebuyApiClient, rebuyContext, uuid, endpoint]);
9974
- const request = (0, import_react40.useMemo)(() => {
10412
+ const request = (0, import_react41.useMemo)(() => {
9975
10413
  const req = {
9976
10414
  endpoint,
9977
10415
  params: {}
@@ -9982,7 +10420,7 @@ var RebuyRecentlyViewedProducts = (props) => {
9982
10420
  }
9983
10421
  return req;
9984
10422
  }, [limit, uuid, endpoint]);
9985
- (0, import_react40.useEffect)(() => {
10423
+ (0, import_react41.useEffect)(() => {
9986
10424
  let isMounted = true;
9987
10425
  if (!rebuyApiClient || !initialized || configLoadingStatus !== "success") return;
9988
10426
  const fetchData = async () => {