@replohq/canopy-sdk 0.1.0
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/_vendor/replo-utils/lib/errors.d.ts +83 -0
- package/_vendor/replo-utils/lib/json.d.ts +6 -0
- package/_vendor/replo-utils/lib/misc.d.ts +128 -0
- package/_vendor/replo-utils/lib/misc.mjs +1 -0
- package/_vendor/replo-utils/lib/object.d.ts +31 -0
- package/_vendor/replo-utils/lib/parse.d.ts +15 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/levanta.d.ts +49 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/levanta.mjs +36 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/product.d.ts +334 -0
- package/_vendor/schemas/agentTools/customIntegrations/loaders/product.mjs +50 -0
- package/_vendor/schemas/cart.d.ts +198 -0
- package/_vendor/schemas/cart.mjs +83 -0
- package/_vendor/schemas/errors.d.ts +428 -0
- package/_vendor/schemas/errors.mjs +955 -0
- package/_vendor/schemas/generated/errors.d.ts +61 -0
- package/_vendor/schemas/generated/selectMode.d.ts +95 -0
- package/_vendor/schemas/generated/selectMode.mjs +1 -0
- package/_vendor/schemas/loaderKeys.d.ts +39 -0
- package/_vendor/schemas/loaderKeys.mjs +23 -0
- package/_vendor/schemas/objectType.d.ts +895 -0
- package/_vendor/schemas/objectType.mjs +2 -0
- package/_vendor/schemas/registry.d.ts +243 -0
- package/_vendor/schemas/sandboxFiles.d.ts +35 -0
- package/_vendor/schemas/selectMode.d.ts +507 -0
- package/_vendor/schemas/selectMode.mjs +194 -0
- package/_vendor/schemas/sellingPlan.d.ts +60 -0
- package/_vendor/schemas/sellingPlan.mjs +1 -0
- package/analytics/analytics-provider.d.ts +13 -0
- package/analytics/analytics-provider.js +104 -0
- package/analytics/analytics-provider.js.map +7 -0
- package/analytics/analytics-sink.d.ts +20 -0
- package/analytics/analytics-sink.js +1 -0
- package/analytics/analytics-sink.js.map +7 -0
- package/analytics/hooks/use-product-viewed-analytics.d.ts +23 -0
- package/analytics/hooks/use-product-viewed-analytics.js +34 -0
- package/analytics/hooks/use-product-viewed-analytics.js.map +7 -0
- package/analytics/sinks/ga4-sink.d.ts +15 -0
- package/analytics/sinks/ga4-sink.js +52 -0
- package/analytics/sinks/ga4-sink.js.map +7 -0
- package/analytics/sinks/meta-sink.d.ts +14 -0
- package/analytics/sinks/meta-sink.js +44 -0
- package/analytics/sinks/meta-sink.js.map +7 -0
- package/analytics/sinks/pinterest-sink.d.ts +14 -0
- package/analytics/sinks/pinterest-sink.js +76 -0
- package/analytics/sinks/pinterest-sink.js.map +7 -0
- package/analytics/sinks/reddit-sink.d.ts +14 -0
- package/analytics/sinks/reddit-sink.js +80 -0
- package/analytics/sinks/reddit-sink.js.map +7 -0
- package/analytics/sinks/replo-sink.d.ts +14 -0
- package/analytics/sinks/replo-sink.js +57 -0
- package/analytics/sinks/replo-sink.js.map +7 -0
- package/analytics/sinks/snapchat-sink.d.ts +14 -0
- package/analytics/sinks/snapchat-sink.js +67 -0
- package/analytics/sinks/snapchat-sink.js.map +7 -0
- package/analytics/sinks/tiktok-sink.d.ts +14 -0
- package/analytics/sinks/tiktok-sink.js +79 -0
- package/analytics/sinks/tiktok-sink.js.map +7 -0
- package/analytics/sinks/window-sink.d.ts +18 -0
- package/analytics/sinks/window-sink.js +46 -0
- package/analytics/sinks/window-sink.js.map +7 -0
- package/analytics/utils/analytics-utils.d.ts +7 -0
- package/analytics/utils/analytics-utils.js +130 -0
- package/analytics/utils/analytics-utils.js.map +7 -0
- package/analytics/utils/navigation-tracker.d.ts +16 -0
- package/analytics/utils/navigation-tracker.js +44 -0
- package/analytics/utils/navigation-tracker.js.map +7 -0
- package/cart/buy-now-action.d.ts +21 -0
- package/cart/buy-now-action.js +104 -0
- package/cart/buy-now-action.js.map +7 -0
- package/cart/cart-actions.d.ts +63 -0
- package/cart/cart-actions.js +90 -0
- package/cart/cart-actions.js.map +7 -0
- package/cart/cart-loader.d.ts +9 -0
- package/cart/cart-loader.js +11 -0
- package/cart/cart-loader.js.map +7 -0
- package/cart/cart-provider.d.ts +85 -0
- package/cart/cart-provider.js +358 -0
- package/cart/cart-provider.js.map +7 -0
- package/cart/cart-types.d.ts +154 -0
- package/cart/cart-types.js +16 -0
- package/cart/cart-types.js.map +7 -0
- package/cart/gateways/cart-gateway.d.ts +10 -0
- package/cart/gateways/cart-gateway.js +19 -0
- package/cart/gateways/cart-gateway.js.map +7 -0
- package/cart/gateways/cookie-cart-gateway.d.ts +28 -0
- package/cart/gateways/cookie-cart-gateway.js +109 -0
- package/cart/gateways/cookie-cart-gateway.js.map +7 -0
- package/cart/gateways/default-cart-gateway.d.ts +19 -0
- package/cart/gateways/default-cart-gateway.js +30 -0
- package/cart/gateways/default-cart-gateway.js.map +7 -0
- package/cart/gateways/resolver-cart-gateway.d.ts +2 -0
- package/cart/gateways/resolver-cart-gateway.js +106 -0
- package/cart/gateways/resolver-cart-gateway.js.map +7 -0
- package/cart/gateways/stripe-cart-gateway.d.ts +19 -0
- package/cart/gateways/stripe-cart-gateway.js +28 -0
- package/cart/gateways/stripe-cart-gateway.js.map +7 -0
- package/cart/gateways/stripe-constants.d.ts +1 -0
- package/cart/gateways/stripe-constants.js +5 -0
- package/cart/gateways/stripe-constants.js.map +7 -0
- package/cart/hooks/use-add-to-cart.d.ts +63 -0
- package/cart/hooks/use-add-to-cart.js +120 -0
- package/cart/hooks/use-add-to-cart.js.map +7 -0
- package/cart/hooks/use-buy-now.d.ts +49 -0
- package/cart/hooks/use-buy-now.js +62 -0
- package/cart/hooks/use-buy-now.js.map +7 -0
- package/cart/utils/cart-utils.d.ts +31 -0
- package/cart/utils/cart-utils.js +48 -0
- package/cart/utils/cart-utils.js.map +7 -0
- package/cart/utils/cookie-cart-persistence.d.ts +55 -0
- package/cart/utils/cookie-cart-persistence.js +153 -0
- package/cart/utils/cookie-cart-persistence.js.map +7 -0
- package/cart/utils/variant-to-cart-line.d.ts +124 -0
- package/cart/utils/variant-to-cart-line.js +202 -0
- package/cart/utils/variant-to-cart-line.js.map +7 -0
- package/chunk-46YU2W6T.mjs +538 -0
- package/chunk-4TZVNC3W.mjs +33 -0
- package/chunk-INHK6MYI.mjs +1598 -0
- package/editor/ClientErrorBoundary.d.ts +7 -0
- package/editor/ClientErrorBoundary.js +48 -0
- package/editor/ClientErrorBoundary.js.map +7 -0
- package/editor/LinkInterceptor.d.ts +1 -0
- package/editor/LinkInterceptor.js +124 -0
- package/editor/LinkInterceptor.js.map +7 -0
- package/editor/posthog-relay.d.ts +10 -0
- package/editor/posthog-relay.js +60 -0
- package/editor/posthog-relay.js.map +7 -0
- package/editor/select-mode/EditorSelection.d.ts +24 -0
- package/editor/select-mode/EditorSelection.js +34 -0
- package/editor/select-mode/EditorSelection.js.map +7 -0
- package/editor/select-mode/descriptor/elementDescriptor.d.ts +15 -0
- package/editor/select-mode/descriptor/elementDescriptor.js +213 -0
- package/editor/select-mode/descriptor/elementDescriptor.js.map +7 -0
- package/editor/select-mode/fiber.d.ts +52 -0
- package/editor/select-mode/fiber.js +269 -0
- package/editor/select-mode/fiber.js.map +7 -0
- package/editor/select-mode/hooks/useCrosshairCursor.d.ts +12 -0
- package/editor/select-mode/hooks/useCrosshairCursor.js +20 -0
- package/editor/select-mode/hooks/useCrosshairCursor.js.map +7 -0
- package/editor/select-mode/hooks/useParentMessaging.d.ts +24 -0
- package/editor/select-mode/hooks/useParentMessaging.js +33 -0
- package/editor/select-mode/hooks/useParentMessaging.js.map +7 -0
- package/editor/select-mode/hooks/useSelectModeController.d.ts +8 -0
- package/editor/select-mode/hooks/useSelectModeController.js +49 -0
- package/editor/select-mode/hooks/useSelectModeController.js.map +7 -0
- package/editor/select-mode/hooks/useSelectionHover.d.ts +22 -0
- package/editor/select-mode/hooks/useSelectionHover.js +98 -0
- package/editor/select-mode/hooks/useSelectionHover.js.map +7 -0
- package/editor/select-mode/hooks/useSelectionInteractions.d.ts +32 -0
- package/editor/select-mode/hooks/useSelectionInteractions.js +293 -0
- package/editor/select-mode/hooks/useSelectionInteractions.js.map +7 -0
- package/editor/select-mode/hooks/useSelectionScrollSync.d.ts +28 -0
- package/editor/select-mode/hooks/useSelectionScrollSync.js +77 -0
- package/editor/select-mode/hooks/useSelectionScrollSync.js.map +7 -0
- package/editor/select-mode/interactions/selectionGeometry.d.ts +80 -0
- package/editor/select-mode/interactions/selectionGeometry.js +160 -0
- package/editor/select-mode/interactions/selectionGeometry.js.map +7 -0
- package/editor/select-mode/selectModeSession.d.ts +21 -0
- package/editor/select-mode/selectModeSession.js +7 -0
- package/editor/select-mode/selectModeSession.js.map +7 -0
- package/editor/select-mode/selectionFrame.d.ts +48 -0
- package/editor/select-mode/selectionFrame.js +74 -0
- package/editor/select-mode/selectionFrame.js.map +7 -0
- package/editor/select-mode/symbolicate.d.ts +3 -0
- package/editor/select-mode/symbolicate.js +139 -0
- package/editor/select-mode/symbolicate.js.map +7 -0
- package/env.d.ts +13 -0
- package/env.js +20 -0
- package/env.js.map +7 -0
- package/gateways/canopy-api.d.ts +84 -0
- package/gateways/canopy-api.js +203 -0
- package/gateways/canopy-api.js.map +7 -0
- package/hooks/use-client-value.d.ts +10 -0
- package/hooks/use-client-value.js +12 -0
- package/hooks/use-client-value.js.map +7 -0
- package/hooks/use-formatted-price.d.ts +15 -0
- package/hooks/use-formatted-price.js +19 -0
- package/hooks/use-formatted-price.js.map +7 -0
- package/lib/get-query-client.d.ts +2 -0
- package/lib/get-query-client.js +34 -0
- package/lib/get-query-client.js.map +7 -0
- package/lib/integration-utils.d.ts +2 -0
- package/lib/integration-utils.js +9 -0
- package/lib/integration-utils.js.map +7 -0
- package/lib/shopify-utils.d.ts +16 -0
- package/lib/shopify-utils.js +11 -0
- package/lib/shopify-utils.js.map +7 -0
- package/lib/url-utils.d.ts +4 -0
- package/lib/url-utils.js +8 -0
- package/lib/url-utils.js.map +7 -0
- package/loaders/collection-loader.d.ts +11 -0
- package/loaders/collection-loader.js +53 -0
- package/loaders/collection-loader.js.map +7 -0
- package/loaders/collection-products-loader.d.ts +12 -0
- package/loaders/collection-products-loader.js +56 -0
- package/loaders/collection-products-loader.js.map +7 -0
- package/loaders/invoke-loader-action.d.ts +11 -0
- package/loaders/invoke-loader-action.js +14 -0
- package/loaders/invoke-loader-action.js.map +7 -0
- package/loaders/invoke-loader-server.d.ts +18 -0
- package/loaders/invoke-loader-server.js +35 -0
- package/loaders/invoke-loader-server.js.map +7 -0
- package/loaders/invoke-loader.d.ts +14 -0
- package/loaders/invoke-loader.js +36 -0
- package/loaders/invoke-loader.js.map +7 -0
- package/loaders/levanta-product-loader.d.ts +11 -0
- package/loaders/levanta-product-loader.js +53 -0
- package/loaders/levanta-product-loader.js.map +7 -0
- package/loaders/loader-error-boundary.d.ts +25 -0
- package/loaders/loader-error-boundary.js +24 -0
- package/loaders/loader-error-boundary.js.map +7 -0
- package/loaders/okendo-review-aggregate-loader.d.ts +17 -0
- package/loaders/okendo-review-aggregate-loader.js +56 -0
- package/loaders/okendo-review-aggregate-loader.js.map +7 -0
- package/loaders/okendo-reviews-loader.d.ts +23 -0
- package/loaders/okendo-reviews-loader.js +54 -0
- package/loaders/okendo-reviews-loader.js.map +7 -0
- package/loaders/prefetch-loaders.d.ts +33 -0
- package/loaders/prefetch-loaders.js +46 -0
- package/loaders/prefetch-loaders.js.map +7 -0
- package/loaders/product-loader.d.ts +11 -0
- package/loaders/product-loader.js +53 -0
- package/loaders/product-loader.js.map +7 -0
- package/loaders/rebuy-recommendations-loader.d.ts +159 -0
- package/loaders/rebuy-recommendations-loader.js +57 -0
- package/loaders/rebuy-recommendations-loader.js.map +7 -0
- package/loaders/smile-earning-rules-loader.d.ts +19 -0
- package/loaders/smile-earning-rules-loader.js +44 -0
- package/loaders/smile-earning-rules-loader.js.map +7 -0
- package/loaders/smile-rewards-loader.d.ts +19 -0
- package/loaders/smile-rewards-loader.js +44 -0
- package/loaders/smile-rewards-loader.js.map +7 -0
- package/loaders/smile-vip-tiers-loader.d.ts +18 -0
- package/loaders/smile-vip-tiers-loader.js +43 -0
- package/loaders/smile-vip-tiers-loader.js.map +7 -0
- package/package.json +29 -0
- package/providers/query-provider.d.ts +1 -0
- package/providers/query-provider.js +12 -0
- package/providers/query-provider.js.map +7 -0
- package/providers/replo-provider.d.ts +1 -0
- package/providers/replo-provider.js +20 -0
- package/providers/replo-provider.js.map +7 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import React from "react";
|
|
3
|
+
import { ReploError } from "../../_vendor/schemas/errors.mjs";
|
|
4
|
+
import { useClientValue } from "../../hooks/use-client-value";
|
|
5
|
+
import { buyNowAction } from "../buy-now-action";
|
|
6
|
+
const REPLO_LOCAL_STORAGE_SESSION_KEY = "_replo_sid";
|
|
7
|
+
const REPLO_SESSION_ID_KEY = "rsid";
|
|
8
|
+
const REPLO_CLIENT_ID_KEY = "rclid";
|
|
9
|
+
class ProductHasNoVariantsError extends ReploError {
|
|
10
|
+
}
|
|
11
|
+
function useBuyNow() {
|
|
12
|
+
const reploSessionString = useClientValue(
|
|
13
|
+
() => localStorage.getItem(REPLO_LOCAL_STORAGE_SESSION_KEY),
|
|
14
|
+
null
|
|
15
|
+
);
|
|
16
|
+
const buyNow = React.useCallback(
|
|
17
|
+
async (variants, options) => {
|
|
18
|
+
if (!variants || variants.length === 0) {
|
|
19
|
+
throw new ProductHasNoVariantsError({
|
|
20
|
+
message: "No variants provided"
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
const { redirectUrl } = await buyNowAction({
|
|
24
|
+
lineItems: variants.map((variant) => ({
|
|
25
|
+
variantId: variant.variantId,
|
|
26
|
+
quantity: variant.quantity ?? 1,
|
|
27
|
+
sellingPlanId: variant.sellingPlanId ?? null,
|
|
28
|
+
properties: []
|
|
29
|
+
})),
|
|
30
|
+
discountCodes: options?.discountCodes ?? [],
|
|
31
|
+
pageUrl: window.location.href
|
|
32
|
+
});
|
|
33
|
+
const url = new URL(redirectUrl);
|
|
34
|
+
const isStripeCheckout = url.hostname.endsWith("stripe.com");
|
|
35
|
+
if (!isStripeCheckout) {
|
|
36
|
+
const currentParams = new URLSearchParams(window.location.search);
|
|
37
|
+
for (const [key, value] of currentParams.entries()) {
|
|
38
|
+
if (!url.searchParams.has(key)) {
|
|
39
|
+
url.searchParams.set(key, value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (reploSessionString) {
|
|
43
|
+
try {
|
|
44
|
+
const sessionData = JSON.parse(reploSessionString);
|
|
45
|
+
if (sessionData.sessionId && sessionData.reploId) {
|
|
46
|
+
url.searchParams.set(REPLO_SESSION_ID_KEY, sessionData.sessionId);
|
|
47
|
+
url.searchParams.set(REPLO_CLIENT_ID_KEY, sessionData.reploId);
|
|
48
|
+
}
|
|
49
|
+
} catch {
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
window.location.href = url.toString();
|
|
54
|
+
},
|
|
55
|
+
[reploSessionString]
|
|
56
|
+
);
|
|
57
|
+
return { buyNow };
|
|
58
|
+
}
|
|
59
|
+
export {
|
|
60
|
+
useBuyNow
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=use-buy-now.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../cart/hooks/use-buy-now.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Use useBuyNow() hook to create \"Buy Now\" buttons that skip the cart and go directly to checkout.\n * Calls a server action to create the cart/checkout session, then redirects the browser.\n * @module\n */\n\"use client\";\n\nimport React from \"react\";\n\nimport { ReploError } from \"schemas/errors\";\n\nimport { useClientValue } from \"../../hooks/use-client-value\";\nimport { buyNowAction } from \"../buy-now-action\";\n\n// Analytics constants - defined locally to avoid dependency on analytics-client package\nconst REPLO_LOCAL_STORAGE_SESSION_KEY = \"_replo_sid\";\nconst REPLO_SESSION_ID_KEY = \"rsid\";\nconst REPLO_CLIENT_ID_KEY = \"rclid\";\n\n// Analytics session data type - defined locally to avoid dependency\ninterface AnalyticsSessionData {\n sessionId: string;\n reploId: string;\n expiresAt: number;\n createdAt: number;\n conversionsCounter: number;\n isEntryPage: boolean;\n}\n\nclass ProductHasNoVariantsError extends ReploError {}\n\nexport interface VariantBuyNowInfo {\n variantId: string;\n quantity?: number;\n sellingPlanId?: string | null;\n}\n\n/**\n * React hook that returns a `buyNow` function for express checkout flows.\n * Handles creating the cart/checkout session server-side and redirecting\n * the browser to checkout.\n *\n * @example\n *\n * ```tsx\n * import { useBuyNow } from \"canopy-sdk/cart/hooks/use-buy-now\";\n *\n * function MyComponent({ selectedVariant, selectedSellingPlan, quantity }) {\n * const { buyNow } = useBuyNow();\n *\n * return (\n * <Button\n * disabled={!selectedVariant?.availableForSale}\n * onClick={async () => {\n * if (selectedVariant) {\n * await buyNow(\n * [\n * {\n * variantId: selectedVariant.id,\n * quantity,\n * sellingPlanId: selectedSellingPlan?.id,\n * },\n * ],\n * { discountCodes: [\"SUMMER2024\"] }\n * );\n * }\n * }}\n * >\n * Shop Now\n * </Button>\n * );\n * }\n * ```\n *\n * @returns Object containing the buyNow function\n */\nexport function useBuyNow() {\n const reploSessionString = useClientValue(\n () => localStorage.getItem(REPLO_LOCAL_STORAGE_SESSION_KEY),\n null,\n );\n\n const buyNow = React.useCallback(\n async (\n variants: VariantBuyNowInfo[],\n options?: { discountCodes?: string[] },\n ) => {\n if (!variants || variants.length === 0) {\n throw new ProductHasNoVariantsError({\n message: \"No variants provided\",\n });\n }\n\n const { redirectUrl } = await buyNowAction({\n lineItems: variants.map((variant) => ({\n variantId: variant.variantId,\n quantity: variant.quantity ?? 1,\n sellingPlanId: variant.sellingPlanId ?? null,\n properties: [],\n })),\n discountCodes: options?.discountCodes ?? [],\n pageUrl: window.location.href,\n });\n\n const url = new URL(redirectUrl);\n\n // Only append tracking params for non-Stripe checkout URLs (e.g. Shopify).\n // Stripe checkout URLs should not be modified with extra query params.\n const isStripeCheckout = url.hostname.endsWith(\"stripe.com\");\n if (!isStripeCheckout) {\n const currentParams = new URLSearchParams(window.location.search);\n for (const [key, value] of currentParams.entries()) {\n if (!url.searchParams.has(key)) {\n url.searchParams.set(key, value);\n }\n }\n\n if (reploSessionString) {\n try {\n const sessionData: AnalyticsSessionData =\n JSON.parse(reploSessionString);\n if (sessionData.sessionId && sessionData.reploId) {\n url.searchParams.set(REPLO_SESSION_ID_KEY, sessionData.sessionId);\n url.searchParams.set(REPLO_CLIENT_ID_KEY, sessionData.reploId);\n }\n } catch {\n // Ignore invalid session data\n }\n }\n }\n\n window.location.href = url.toString();\n },\n [reploSessionString],\n );\n\n return { buyNow };\n}\n"],
|
|
5
|
+
"mappings": ";AAOA,OAAO,WAAW;AAElB,SAAS,kBAAkB;AAE3B,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAG7B,MAAM,kCAAkC;AACxC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AAY5B,MAAM,kCAAkC,WAAW;AAAC;AA+C7C,SAAS,YAAY;AAC1B,QAAM,qBAAqB;AAAA,IACzB,MAAM,aAAa,QAAQ,+BAA+B;AAAA,IAC1D;AAAA,EACF;AAEA,QAAM,SAAS,MAAM;AAAA,IACnB,OACE,UACA,YACG;AACH,UAAI,CAAC,YAAY,SAAS,WAAW,GAAG;AACtC,cAAM,IAAI,0BAA0B;AAAA,UAClC,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAEA,YAAM,EAAE,YAAY,IAAI,MAAM,aAAa;AAAA,QACzC,WAAW,SAAS,IAAI,CAAC,aAAa;AAAA,UACpC,WAAW,QAAQ;AAAA,UACnB,UAAU,QAAQ,YAAY;AAAA,UAC9B,eAAe,QAAQ,iBAAiB;AAAA,UACxC,YAAY,CAAC;AAAA,QACf,EAAE;AAAA,QACF,eAAe,SAAS,iBAAiB,CAAC;AAAA,QAC1C,SAAS,OAAO,SAAS;AAAA,MAC3B,CAAC;AAED,YAAM,MAAM,IAAI,IAAI,WAAW;AAI/B,YAAM,mBAAmB,IAAI,SAAS,SAAS,YAAY;AAC3D,UAAI,CAAC,kBAAkB;AACrB,cAAM,gBAAgB,IAAI,gBAAgB,OAAO,SAAS,MAAM;AAChE,mBAAW,CAAC,KAAK,KAAK,KAAK,cAAc,QAAQ,GAAG;AAClD,cAAI,CAAC,IAAI,aAAa,IAAI,GAAG,GAAG;AAC9B,gBAAI,aAAa,IAAI,KAAK,KAAK;AAAA,UACjC;AAAA,QACF;AAEA,YAAI,oBAAoB;AACtB,cAAI;AACF,kBAAM,cACJ,KAAK,MAAM,kBAAkB;AAC/B,gBAAI,YAAY,aAAa,YAAY,SAAS;AAChD,kBAAI,aAAa,IAAI,sBAAsB,YAAY,SAAS;AAChE,kBAAI,aAAa,IAAI,qBAAqB,YAAY,OAAO;AAAA,YAC/D;AAAA,UACF,QAAQ;AAAA,UAER;AAAA,QACF;AAAA,MACF;AAEA,aAAO,SAAS,OAAO,IAAI,SAAS;AAAA,IACtC;AAAA,IACA,CAAC,kBAAkB;AAAA,EACrB;AAEA,SAAO,EAAE,OAAO;AAClB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Cart, CartLine } from "../cart-types";
|
|
2
|
+
export interface CartTotals {
|
|
3
|
+
subtotal: number;
|
|
4
|
+
discountAmount: number;
|
|
5
|
+
totalSavings: number;
|
|
6
|
+
total: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Calculate cart totals including subtotal, discounts, and final total.
|
|
10
|
+
* When cart cost data is provided (from Shopify), uses the actual totalAmount
|
|
11
|
+
* which includes cart-level discounts from discount codes.
|
|
12
|
+
*
|
|
13
|
+
* @param options - Object containing lineItems and cart
|
|
14
|
+
* @param options.lineItems - Array of cart line items
|
|
15
|
+
* @param options.cart - Optional cart data from Shopify (includes discount codes)
|
|
16
|
+
*/
|
|
17
|
+
export declare function calculateCartTotals({ lineItems, cart, }: {
|
|
18
|
+
lineItems: CartLine[];
|
|
19
|
+
cart: Cart | null;
|
|
20
|
+
}): CartTotals;
|
|
21
|
+
/**
|
|
22
|
+
* Format price as currency string
|
|
23
|
+
*/
|
|
24
|
+
export declare function formatPrice(price: number, currency?: string): string;
|
|
25
|
+
/**
|
|
26
|
+
* Validates and formats a Shopify selling plan ID to ensure it has the correct GID format.
|
|
27
|
+
*
|
|
28
|
+
* @param sellingPlanId - The selling plan ID to validate and format
|
|
29
|
+
* @returns The formatted selling plan ID with GID prefix, or null if no ID provided
|
|
30
|
+
*/
|
|
31
|
+
export declare function formatSellingPlanId(sellingPlanId: string | null | undefined): string | null;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { getCartLinePricing } from "./variant-to-cart-line";
|
|
2
|
+
function calculateCartTotals({
|
|
3
|
+
lineItems,
|
|
4
|
+
cart
|
|
5
|
+
}) {
|
|
6
|
+
const { compareAtSubtotal, lineItemSubtotal } = lineItems.reduce(
|
|
7
|
+
(sum, item) => {
|
|
8
|
+
const pricing = getCartLinePricing(item);
|
|
9
|
+
return {
|
|
10
|
+
compareAtSubtotal: sum.compareAtSubtotal + pricing.compareAtPrice * item.quantity,
|
|
11
|
+
lineItemSubtotal: sum.lineItemSubtotal + pricing.finalPrice * item.quantity
|
|
12
|
+
};
|
|
13
|
+
},
|
|
14
|
+
{ compareAtSubtotal: 0, lineItemSubtotal: 0 }
|
|
15
|
+
);
|
|
16
|
+
const total = cart?.cost.totalAmount ?? lineItemSubtotal;
|
|
17
|
+
const actualSubtotal = cart?.cost.subtotalAmount ?? lineItemSubtotal;
|
|
18
|
+
const discountAmount = actualSubtotal - total;
|
|
19
|
+
const totalSavings = compareAtSubtotal - total;
|
|
20
|
+
return {
|
|
21
|
+
subtotal: lineItemSubtotal,
|
|
22
|
+
discountAmount,
|
|
23
|
+
totalSavings,
|
|
24
|
+
total
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function formatPrice(price, currency = "USD") {
|
|
28
|
+
const formatter = new Intl.NumberFormat("en-US", {
|
|
29
|
+
style: "currency",
|
|
30
|
+
currency
|
|
31
|
+
});
|
|
32
|
+
return formatter.format(price);
|
|
33
|
+
}
|
|
34
|
+
function formatSellingPlanId(sellingPlanId) {
|
|
35
|
+
if (!sellingPlanId) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (sellingPlanId.startsWith("gid://shopify/SellingPlan/")) {
|
|
39
|
+
return sellingPlanId;
|
|
40
|
+
}
|
|
41
|
+
return `gid://shopify/SellingPlan/${sellingPlanId}`;
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
calculateCartTotals,
|
|
45
|
+
formatPrice,
|
|
46
|
+
formatSellingPlanId
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=cart-utils.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../cart/utils/cart-utils.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Cart, CartLine } from \"../cart-types\";\n\nimport { getCartLinePricing } from \"./variant-to-cart-line\";\n\nexport interface CartTotals {\n subtotal: number;\n discountAmount: number;\n totalSavings: number;\n total: number;\n}\n\n/**\n * Calculate cart totals including subtotal, discounts, and final total.\n * When cart cost data is provided (from Shopify), uses the actual totalAmount\n * which includes cart-level discounts from discount codes.\n *\n * @param options - Object containing lineItems and cart\n * @param options.lineItems - Array of cart line items\n * @param options.cart - Optional cart data from Shopify (includes discount codes)\n */\nexport function calculateCartTotals({\n lineItems,\n cart,\n}: {\n lineItems: CartLine[];\n cart: Cart | null;\n}): CartTotals {\n const { compareAtSubtotal, lineItemSubtotal } = lineItems.reduce(\n (sum, item) => {\n const pricing = getCartLinePricing(item);\n return {\n compareAtSubtotal:\n sum.compareAtSubtotal + pricing.compareAtPrice * item.quantity,\n lineItemSubtotal:\n sum.lineItemSubtotal + pricing.finalPrice * item.quantity,\n };\n },\n { compareAtSubtotal: 0, lineItemSubtotal: 0 },\n );\n\n // Use Provider's actual total when available\n const total = cart?.cost.totalAmount ?? lineItemSubtotal;\n\n // Calculate the actual discount amount\n // If we have cart cost data, use subtotalAmount which doesn't include discounts\n const actualSubtotal = cart?.cost.subtotalAmount ?? lineItemSubtotal;\n const discountAmount = actualSubtotal - total;\n\n const totalSavings = compareAtSubtotal - total;\n\n return {\n subtotal: lineItemSubtotal,\n discountAmount,\n totalSavings,\n total,\n };\n}\n\n/**\n * Format price as currency string\n */\nexport function formatPrice(price: number, currency: string = \"USD\"): string {\n const formatter = new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: currency,\n });\n return formatter.format(price);\n}\n\n/**\n * Validates and formats a Shopify selling plan ID to ensure it has the correct GID format.\n *\n * @param sellingPlanId - The selling plan ID to validate and format\n * @returns The formatted selling plan ID with GID prefix, or null if no ID provided\n */\nexport function formatSellingPlanId(\n sellingPlanId: string | null | undefined,\n): string | null {\n if (!sellingPlanId) {\n return null;\n }\n\n // Check if it already has the gid format\n if (sellingPlanId.startsWith(\"gid://shopify/SellingPlan/\")) {\n return sellingPlanId;\n }\n\n // If it doesn't have the gid format, prepend it\n return `gid://shopify/SellingPlan/${sellingPlanId}`;\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,0BAA0B;AAkB5B,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA;AACF,GAGe;AACb,QAAM,EAAE,mBAAmB,iBAAiB,IAAI,UAAU;AAAA,IACxD,CAAC,KAAK,SAAS;AACb,YAAM,UAAU,mBAAmB,IAAI;AACvC,aAAO;AAAA,QACL,mBACE,IAAI,oBAAoB,QAAQ,iBAAiB,KAAK;AAAA,QACxD,kBACE,IAAI,mBAAmB,QAAQ,aAAa,KAAK;AAAA,MACrD;AAAA,IACF;AAAA,IACA,EAAE,mBAAmB,GAAG,kBAAkB,EAAE;AAAA,EAC9C;AAGA,QAAM,QAAQ,MAAM,KAAK,eAAe;AAIxC,QAAM,iBAAiB,MAAM,KAAK,kBAAkB;AACpD,QAAM,iBAAiB,iBAAiB;AAExC,QAAM,eAAe,oBAAoB;AAEzC,SAAO;AAAA,IACL,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAKO,SAAS,YAAY,OAAe,WAAmB,OAAe;AAC3E,QAAM,YAAY,IAAI,KAAK,aAAa,SAAS;AAAA,IAC/C,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AACD,SAAO,UAAU,OAAO,KAAK;AAC/B;AAQO,SAAS,oBACd,eACe;AACf,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAGA,MAAI,cAAc,WAAW,4BAA4B,GAAG;AAC1D,WAAO;AAAA,EACT;AAGA,SAAO,6BAA6B,aAAa;AACnD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { AddToCartPayload, Cart, CartLine, CartLinePayload, RemoveFromCartPayload, UpdateCartLineItemPayload } from "../cart-types";
|
|
2
|
+
/**
|
|
3
|
+
* Line merge function type - returns index of existing line to merge with, or -1 to add as new line
|
|
4
|
+
*/
|
|
5
|
+
export type LineMergeFn = (existingLines: CartLine[], newLine: CartLinePayload) => number;
|
|
6
|
+
/**
|
|
7
|
+
* Options for creating a cart with persistence
|
|
8
|
+
*/
|
|
9
|
+
interface CreateCartOptions {
|
|
10
|
+
cookieName: string;
|
|
11
|
+
lines?: CartLinePayload[];
|
|
12
|
+
lineIdGenerator: () => string;
|
|
13
|
+
cartIdGenerator: () => string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Options for adding to cart with persistence
|
|
17
|
+
*/
|
|
18
|
+
interface AddToCartOptions {
|
|
19
|
+
cookieName: string;
|
|
20
|
+
mergeFn: LineMergeFn;
|
|
21
|
+
lineIdGenerator: () => string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Save cart to cookie
|
|
25
|
+
*/
|
|
26
|
+
export declare function saveCartToCookie(cart: Cart, cookieName: string): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Load cart from cookie
|
|
29
|
+
*/
|
|
30
|
+
export declare function loadCartFromCookie(cookieName: string): Promise<Cart | null>;
|
|
31
|
+
/**
|
|
32
|
+
* Clear cart cookie
|
|
33
|
+
*/
|
|
34
|
+
export declare function clearCartCookie(cookieName: string): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Update cart in cookie atomically (load-transform-save pattern)
|
|
37
|
+
*/
|
|
38
|
+
export declare function updateCartInCookie(cartId: string, cookieName: string, updater: (cart: Cart) => Cart): Promise<Cart | null>;
|
|
39
|
+
/**
|
|
40
|
+
* Create a new cart with persistence
|
|
41
|
+
*/
|
|
42
|
+
export declare function createCartWithPersistence(options: CreateCartOptions): Promise<Cart | null>;
|
|
43
|
+
/**
|
|
44
|
+
* Add lines to cart with configurable line merging strategy
|
|
45
|
+
*/
|
|
46
|
+
export declare function addToCartWithPersistence(payload: AddToCartPayload, options: AddToCartOptions): Promise<Cart | null>;
|
|
47
|
+
/**
|
|
48
|
+
* Update cart line item
|
|
49
|
+
*/
|
|
50
|
+
export declare function updateCartLineItemWithPersistence(payload: UpdateCartLineItemPayload, cookieName: string): Promise<Cart | null>;
|
|
51
|
+
/**
|
|
52
|
+
* Remove cart line items
|
|
53
|
+
*/
|
|
54
|
+
export declare function removeCartLineItemsWithPersistence(payload: RemoveFromCartPayload, cookieName: string): Promise<Cart | null>;
|
|
55
|
+
export {};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"use server";
|
|
2
|
+
import { cookies } from "next/headers";
|
|
3
|
+
const CART_COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
|
|
4
|
+
async function saveCartToCookie(cart, cookieName) {
|
|
5
|
+
const cookieStore = await cookies();
|
|
6
|
+
cookieStore.set(cookieName, JSON.stringify(cart), {
|
|
7
|
+
maxAge: CART_COOKIE_MAX_AGE,
|
|
8
|
+
httpOnly: true,
|
|
9
|
+
secure: process.env.NODE_ENV === "production",
|
|
10
|
+
sameSite: "lax",
|
|
11
|
+
path: "/"
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
async function loadCartFromCookie(cookieName) {
|
|
15
|
+
const cookieStore = await cookies();
|
|
16
|
+
const cartCookie = cookieStore.get(cookieName);
|
|
17
|
+
if (!cartCookie?.value) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(cartCookie.value);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
console.warn("Failed to parse cart cookie:", error);
|
|
24
|
+
await clearCartCookie(cookieName);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function clearCartCookie(cookieName) {
|
|
29
|
+
const cookieStore = await cookies();
|
|
30
|
+
cookieStore.delete(cookieName);
|
|
31
|
+
}
|
|
32
|
+
async function updateCartInCookie(cartId, cookieName, updater) {
|
|
33
|
+
const existingCart = await loadCartFromCookie(cookieName);
|
|
34
|
+
if (!existingCart || existingCart.id !== cartId) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const updatedCart = updater(existingCart);
|
|
38
|
+
await saveCartToCookie(updatedCart, cookieName);
|
|
39
|
+
return updatedCart;
|
|
40
|
+
}
|
|
41
|
+
async function createCartWithPersistence(options) {
|
|
42
|
+
const cartId = options.cartIdGenerator();
|
|
43
|
+
const cart = {
|
|
44
|
+
id: cartId,
|
|
45
|
+
lines: [],
|
|
46
|
+
cost: {
|
|
47
|
+
subtotalAmount: 0,
|
|
48
|
+
totalAmount: 0,
|
|
49
|
+
currencyCode: "USD"
|
|
50
|
+
},
|
|
51
|
+
checkoutUrl: "/checkout"
|
|
52
|
+
};
|
|
53
|
+
for (const line of options.lines ?? []) {
|
|
54
|
+
cart.lines.push(
|
|
55
|
+
convertCartLinePayloadToCartLine(line, options.lineIdGenerator)
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
await saveCartToCookie(cart, options.cookieName);
|
|
59
|
+
return cart;
|
|
60
|
+
}
|
|
61
|
+
async function addToCartWithPersistence(payload, options) {
|
|
62
|
+
return await updateCartInCookie(
|
|
63
|
+
payload.cartId,
|
|
64
|
+
options.cookieName,
|
|
65
|
+
(cart) => {
|
|
66
|
+
for (const linePayload of payload.lines) {
|
|
67
|
+
const existingLineIndex = options.mergeFn(cart.lines, linePayload);
|
|
68
|
+
if (existingLineIndex >= 0) {
|
|
69
|
+
cart.lines[existingLineIndex].quantity += linePayload.quantity;
|
|
70
|
+
} else {
|
|
71
|
+
const newLine = convertCartLinePayloadToCartLine(
|
|
72
|
+
linePayload,
|
|
73
|
+
options.lineIdGenerator
|
|
74
|
+
);
|
|
75
|
+
cart.lines.push(newLine);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return cart;
|
|
79
|
+
}
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
async function updateCartLineItemWithPersistence(payload, cookieName) {
|
|
83
|
+
return await updateCartInCookie(payload.cartId, cookieName, (cart) => {
|
|
84
|
+
const lineIndex = cart.lines.findIndex(
|
|
85
|
+
(line) => line.id === payload.line.id
|
|
86
|
+
);
|
|
87
|
+
if (lineIndex >= 0) {
|
|
88
|
+
if (payload.line.quantity <= 0) {
|
|
89
|
+
cart.lines.splice(lineIndex, 1);
|
|
90
|
+
} else {
|
|
91
|
+
cart.lines[lineIndex].quantity = payload.line.quantity;
|
|
92
|
+
if (payload.line.properties) {
|
|
93
|
+
cart.lines[lineIndex].attributes = payload.line.properties;
|
|
94
|
+
}
|
|
95
|
+
if (payload.line.merchandise) {
|
|
96
|
+
cart.lines[lineIndex].merchandise = payload.line.merchandise;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return cart;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async function removeCartLineItemsWithPersistence(payload, cookieName) {
|
|
104
|
+
return await updateCartInCookie(payload.cartId, cookieName, (cart) => {
|
|
105
|
+
const removeSet = new Set(payload.lineIds);
|
|
106
|
+
cart.lines = cart.lines.filter((line) => !removeSet.has(line.id));
|
|
107
|
+
return cart;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function convertCartLinePayloadToCartLine(linePayload, lineIdGenerator) {
|
|
111
|
+
const fallbackMerchandise = {
|
|
112
|
+
id: linePayload.id,
|
|
113
|
+
product: {
|
|
114
|
+
id: linePayload.merchandise?.product.id ?? linePayload.id,
|
|
115
|
+
title: linePayload.merchandise?.product.title ?? "Product"
|
|
116
|
+
},
|
|
117
|
+
title: linePayload.merchandise?.title ?? "Product Variant",
|
|
118
|
+
price: linePayload.merchandise?.price ?? 0,
|
|
119
|
+
compareAtPrice: linePayload.merchandise?.compareAtPrice ?? null,
|
|
120
|
+
image: linePayload.merchandise?.image ? {
|
|
121
|
+
url: linePayload.merchandise.image.url,
|
|
122
|
+
altText: linePayload.merchandise.image.altText
|
|
123
|
+
} : null,
|
|
124
|
+
selectedOptions: linePayload.merchandise?.selectedOptions ?? []
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
id: lineIdGenerator(),
|
|
128
|
+
quantity: linePayload.quantity,
|
|
129
|
+
merchandise: linePayload.merchandise ?? fallbackMerchandise,
|
|
130
|
+
attributes: linePayload.properties ?? [],
|
|
131
|
+
sellingPlanAllocation: linePayload.sellingPlanId ? {
|
|
132
|
+
sellingPlan: {
|
|
133
|
+
id: linePayload.sellingPlanId,
|
|
134
|
+
name: "Subscription Plan",
|
|
135
|
+
description: null
|
|
136
|
+
},
|
|
137
|
+
priceAdjustments: [],
|
|
138
|
+
checkoutChargeAmount: { amount: 0, currencyCode: "USD" },
|
|
139
|
+
remainingBalanceChargeAmount: { amount: 0, currencyCode: "USD" }
|
|
140
|
+
} : null
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
export {
|
|
144
|
+
addToCartWithPersistence,
|
|
145
|
+
clearCartCookie,
|
|
146
|
+
createCartWithPersistence,
|
|
147
|
+
loadCartFromCookie,
|
|
148
|
+
removeCartLineItemsWithPersistence,
|
|
149
|
+
saveCartToCookie,
|
|
150
|
+
updateCartInCookie,
|
|
151
|
+
updateCartLineItemWithPersistence
|
|
152
|
+
};
|
|
153
|
+
//# sourceMappingURL=cookie-cart-persistence.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../cart/utils/cookie-cart-persistence.ts"],
|
|
4
|
+
"sourcesContent": ["\"use server\";\n\nimport type {\n AddToCartPayload,\n Cart,\n CartLine,\n CartLinePayload,\n RemoveFromCartPayload,\n UpdateCartLineItemPayload,\n} from \"../cart-types\";\n\nimport { cookies } from \"next/headers\";\n\nconst CART_COOKIE_MAX_AGE = 60 * 60 * 24 * 30; // 30 days\n\n/**\n * Line merge function type - returns index of existing line to merge with, or -1 to add as new line\n */\nexport type LineMergeFn = (\n existingLines: CartLine[],\n newLine: CartLinePayload,\n) => number;\n\n/**\n * Options for creating a cart with persistence\n */\ninterface CreateCartOptions {\n cookieName: string;\n lines?: CartLinePayload[];\n lineIdGenerator: () => string;\n cartIdGenerator: () => string;\n}\n\n/**\n * Options for adding to cart with persistence\n */\ninterface AddToCartOptions {\n cookieName: string;\n mergeFn: LineMergeFn;\n lineIdGenerator: () => string;\n}\n\n/**\n * Save cart to cookie\n */\nexport async function saveCartToCookie(cart: Cart, cookieName: string) {\n const cookieStore = await cookies();\n cookieStore.set(cookieName, JSON.stringify(cart), {\n maxAge: CART_COOKIE_MAX_AGE,\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n path: \"/\",\n });\n}\n\n/**\n * Load cart from cookie\n */\nexport async function loadCartFromCookie(\n cookieName: string,\n): Promise<Cart | null> {\n const cookieStore = await cookies();\n const cartCookie = cookieStore.get(cookieName);\n\n if (!cartCookie?.value) {\n return null;\n }\n\n try {\n // Legacy cast - may or may not be necessary\n // eslint-disable-next-line replo/no-as-cast\n return JSON.parse(cartCookie.value) as Cart;\n } catch (error) {\n console.warn(\"Failed to parse cart cookie:\", error);\n await clearCartCookie(cookieName);\n return null;\n }\n}\n\n/**\n * Clear cart cookie\n */\nexport async function clearCartCookie(cookieName: string) {\n const cookieStore = await cookies();\n cookieStore.delete(cookieName);\n}\n\n/**\n * Update cart in cookie atomically (load-transform-save pattern)\n */\nexport async function updateCartInCookie(\n cartId: string,\n cookieName: string,\n updater: (cart: Cart) => Cart,\n): Promise<Cart | null> {\n const existingCart = await loadCartFromCookie(cookieName);\n\n if (!existingCart || existingCart.id !== cartId) {\n return null;\n }\n\n const updatedCart = updater(existingCart);\n\n await saveCartToCookie(updatedCart, cookieName);\n\n return updatedCart;\n}\n\n/**\n * Create a new cart with persistence\n */\nexport async function createCartWithPersistence(\n options: CreateCartOptions,\n): Promise<Cart | null> {\n const cartId = options.cartIdGenerator();\n\n const cart: Cart = {\n id: cartId,\n lines: [],\n cost: {\n subtotalAmount: 0,\n totalAmount: 0,\n currencyCode: \"USD\",\n },\n checkoutUrl: \"/checkout\",\n };\n\n for (const line of options.lines ?? []) {\n cart.lines.push(\n convertCartLinePayloadToCartLine(line, options.lineIdGenerator),\n );\n }\n\n await saveCartToCookie(cart, options.cookieName);\n return cart;\n}\n\n/**\n * Add lines to cart with configurable line merging strategy\n */\nexport async function addToCartWithPersistence(\n payload: AddToCartPayload,\n options: AddToCartOptions,\n): Promise<Cart | null> {\n return await updateCartInCookie(\n payload.cartId,\n options.cookieName,\n (cart) => {\n for (const linePayload of payload.lines) {\n const existingLineIndex = options.mergeFn(cart.lines, linePayload);\n\n if (existingLineIndex >= 0) {\n cart.lines[existingLineIndex]!.quantity += linePayload.quantity;\n } else {\n const newLine: CartLine = convertCartLinePayloadToCartLine(\n linePayload,\n options.lineIdGenerator,\n );\n cart.lines.push(newLine);\n }\n }\n\n return cart;\n },\n );\n}\n\n/**\n * Update cart line item\n */\nexport async function updateCartLineItemWithPersistence(\n payload: UpdateCartLineItemPayload,\n cookieName: string,\n): Promise<Cart | null> {\n return await updateCartInCookie(payload.cartId, cookieName, (cart) => {\n const lineIndex = cart.lines.findIndex(\n (line) => line.id === payload.line.id,\n );\n\n if (lineIndex >= 0) {\n if (payload.line.quantity <= 0) {\n cart.lines.splice(lineIndex, 1);\n } else {\n cart.lines[lineIndex]!.quantity = payload.line.quantity;\n if (payload.line.properties) {\n cart.lines[lineIndex]!.attributes = payload.line.properties;\n }\n if (payload.line.merchandise) {\n cart.lines[lineIndex]!.merchandise = payload.line.merchandise;\n }\n }\n }\n\n return cart;\n });\n}\n\n/**\n * Remove cart line items\n */\nexport async function removeCartLineItemsWithPersistence(\n payload: RemoveFromCartPayload,\n cookieName: string,\n): Promise<Cart | null> {\n return await updateCartInCookie(payload.cartId, cookieName, (cart) => {\n const removeSet = new Set(payload.lineIds);\n cart.lines = cart.lines.filter((line) => !removeSet.has(line.id));\n return cart;\n });\n}\n\n/**\n * Convert CartLinePayload to CartLine with custom ID generator\n */\nfunction convertCartLinePayloadToCartLine(\n linePayload: CartLinePayload,\n lineIdGenerator: () => string,\n): CartLine {\n // Cookie-persisted carts (Stripe/default) are their own source of truth \u2014\n // there's no server roundtrip to backfill merchandise later. Fall back to a\n // placeholder when the caller didn't pass merchandise so the persisted line\n // is renderable; otherwise an unresolvable line would render as a skeleton\n // forever. Shopify carts hit a different code path and use the skeleton\n // treatment in cart-provider.tsx.\n const fallbackMerchandise = {\n id: linePayload.id,\n product: {\n id: linePayload.merchandise?.product.id ?? linePayload.id,\n title: linePayload.merchandise?.product.title ?? \"Product\",\n },\n title: linePayload.merchandise?.title ?? \"Product Variant\",\n price: linePayload.merchandise?.price ?? 0,\n compareAtPrice: linePayload.merchandise?.compareAtPrice ?? null,\n image: linePayload.merchandise?.image\n ? {\n url: linePayload.merchandise.image.url,\n altText: linePayload.merchandise.image.altText,\n }\n : null,\n selectedOptions: linePayload.merchandise?.selectedOptions ?? [],\n };\n\n return {\n id: lineIdGenerator(),\n quantity: linePayload.quantity,\n merchandise: linePayload.merchandise ?? fallbackMerchandise,\n attributes: linePayload.properties ?? [],\n sellingPlanAllocation: linePayload.sellingPlanId\n ? {\n sellingPlan: {\n id: linePayload.sellingPlanId,\n name: \"Subscription Plan\",\n description: null,\n },\n priceAdjustments: [],\n checkoutChargeAmount: { amount: 0, currencyCode: \"USD\" },\n remainingBalanceChargeAmount: { amount: 0, currencyCode: \"USD\" },\n }\n : null,\n };\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { CartLine, CartLineAttribute, CartLineMerchandise, CartLinePayload, SellingPlanAllocation, SellingPlanGroup } from "../cart-types";
|
|
2
|
+
interface ProductVariant {
|
|
3
|
+
id: string;
|
|
4
|
+
externalId?: string;
|
|
5
|
+
title: string;
|
|
6
|
+
price: number;
|
|
7
|
+
originalPrice: number | null;
|
|
8
|
+
optionValues?: {
|
|
9
|
+
id: string;
|
|
10
|
+
value: string;
|
|
11
|
+
color: string | null;
|
|
12
|
+
image: string | null;
|
|
13
|
+
imageUrls: string[];
|
|
14
|
+
referenceType: "SHOPIFY" | "REPLO";
|
|
15
|
+
}[];
|
|
16
|
+
}
|
|
17
|
+
export interface VariantToCartLineProduct {
|
|
18
|
+
id: string;
|
|
19
|
+
title: string;
|
|
20
|
+
featuredMedia?: {
|
|
21
|
+
type: string;
|
|
22
|
+
url: string;
|
|
23
|
+
alt?: string;
|
|
24
|
+
} | null;
|
|
25
|
+
sellingPlanGroups?: SellingPlanGroup[];
|
|
26
|
+
}
|
|
27
|
+
interface VariantToCartLineOptions {
|
|
28
|
+
quantity?: number;
|
|
29
|
+
properties?: CartLineAttribute[];
|
|
30
|
+
sellingPlanId?: string | null;
|
|
31
|
+
pricing?: {
|
|
32
|
+
compareAtPrice: number;
|
|
33
|
+
discountPercentage: number;
|
|
34
|
+
};
|
|
35
|
+
bundle?: {
|
|
36
|
+
bundleId: string;
|
|
37
|
+
bundleDiscount: number;
|
|
38
|
+
};
|
|
39
|
+
includeMerchandise?: boolean;
|
|
40
|
+
product?: VariantToCartLineProduct;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Converts a product variant to a cart line payload.
|
|
44
|
+
* This is the primary function for creating cart lines from variants.
|
|
45
|
+
*
|
|
46
|
+
* When a ProductVariant has both `price` and `originalPrice`, the function will
|
|
47
|
+
* automatically calculate and include pricing attributes (compareAtPrice and discountPercentage)
|
|
48
|
+
* unless explicitly overridden in the options.
|
|
49
|
+
*/
|
|
50
|
+
export declare function variantToCartLine(variant: ProductVariant, options?: VariantToCartLineOptions): CartLinePayload;
|
|
51
|
+
/**
|
|
52
|
+
* Gets a specific attribute value from a cart line.
|
|
53
|
+
*
|
|
54
|
+
* @param cartLine - The cart line to get the attribute from
|
|
55
|
+
* @param key - The attribute key to retrieve
|
|
56
|
+
* @returns The attribute value, or undefined if not found
|
|
57
|
+
*/
|
|
58
|
+
export declare function getCartLineAttribute(cartLine: CartLine, key: string): string | number | boolean | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* Calculates pricing information for a cart line, including discounts and
|
|
61
|
+
* selling plan adjustments.
|
|
62
|
+
*
|
|
63
|
+
* @param cartLine - The cart line to calculate pricing for
|
|
64
|
+
* @returns Object containing compareAtPrice, discountPercentage, hasDiscount, sellingPlanAdjustedPrice, and finalPrice
|
|
65
|
+
*/
|
|
66
|
+
export declare function getCartLinePricing(cartLine: CartLine): {
|
|
67
|
+
compareAtPrice: number;
|
|
68
|
+
discountPercentage: number;
|
|
69
|
+
hasDiscount: boolean;
|
|
70
|
+
sellingPlanAdjustedPrice: number;
|
|
71
|
+
finalPrice: number;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Extracts bundle information from cart line attributes.
|
|
75
|
+
*
|
|
76
|
+
* @param cartLine - The cart line to get bundle info from
|
|
77
|
+
* @returns Object containing bundle ID, discount, and whether it's a bundle item
|
|
78
|
+
*/
|
|
79
|
+
export declare function getCartLineBundleInfo(cartLine: CartLine): {
|
|
80
|
+
bundleId: string;
|
|
81
|
+
bundleDiscount: number;
|
|
82
|
+
isBundleItem: boolean;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Extracts special item information from cart line attributes.
|
|
86
|
+
*
|
|
87
|
+
* @param cartLine - The cart line to get special info from
|
|
88
|
+
* @returns Object containing whether it's a special item and any special instructions
|
|
89
|
+
*/
|
|
90
|
+
export declare function getCartLineSpecialInfo(cartLine: CartLine): {
|
|
91
|
+
isSpecialItem: boolean;
|
|
92
|
+
specialInstructions: string[];
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Extracts subscription (selling plan) information from a cart line.
|
|
96
|
+
*
|
|
97
|
+
* @param cartLine - The cart line to get subscription info from
|
|
98
|
+
* @returns Object containing isSubscription, frequency, discount, and sellingPlan
|
|
99
|
+
*/
|
|
100
|
+
export declare function getCartLineSubscriptionInfo(cartLine: CartLine): {
|
|
101
|
+
isSubscription: boolean;
|
|
102
|
+
frequency: string;
|
|
103
|
+
discount: number;
|
|
104
|
+
sellingPlan: {
|
|
105
|
+
id: string;
|
|
106
|
+
name: string;
|
|
107
|
+
description: string | null;
|
|
108
|
+
};
|
|
109
|
+
} | {
|
|
110
|
+
isSubscription: boolean;
|
|
111
|
+
frequency: null;
|
|
112
|
+
discount: number;
|
|
113
|
+
sellingPlan: null;
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* Creates an optimistic selling plan allocation using product data.
|
|
117
|
+
* This matches the exact structure that Shopify returns so the UI doesn't need conditional logic.
|
|
118
|
+
*/
|
|
119
|
+
export declare function createOptimisticSellingPlanAllocation({ merchandise, sellingPlanId, currencyCode, }: {
|
|
120
|
+
merchandise: CartLineMerchandise;
|
|
121
|
+
sellingPlanId: string | null;
|
|
122
|
+
currencyCode?: string;
|
|
123
|
+
}): SellingPlanAllocation | null;
|
|
124
|
+
export {};
|