@replohq/sdk 1.9.3 → 1.9.5

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/README.md CHANGED
@@ -41,6 +41,13 @@ export default function RootLayout({ children }: React.PropsWithChildren) {
41
41
  `ReploProvider` is an async Server Component. Components that use SDK hooks or
42
42
  loaders must render beneath it.
43
43
 
44
+ ## Buy now checkout
45
+
46
+ Use `useBuyNow` from `@replohq/sdk/cart/hooks/use-buy-now` to send a shopper
47
+ directly to checkout. Shopify checkout applies selling plans and discount codes.
48
+ Stripe checkout ignores both, logs a server warning when either is supplied,
49
+ and still creates the checkout session.
50
+
44
51
  ## Data loaders
45
52
 
46
53
  Data loaders retrieve data from integrations configured for the Replo project.
@@ -1,16 +1,18 @@
1
1
  "use client";
2
2
  import { jsx } from "react/jsx-runtime";
3
- import { findDelegatedPlatform } from "../consent/consent-platform";
4
- import { isConsentAllowed, useConsent } from "../consent/consent-store";
5
3
  import { InjectedScript } from "../consent/replo-scripts";
4
+ import { useIsBlockedByNativeConsent } from "../consent/use-is-blocked-by-native-consent";
6
5
  const PIXEL_SCRIPT_ID = "replo:first-party-pixel";
6
+ const PIXEL_REQUIRED_CONSENT = ["analytics"];
7
7
  function ReploPixelScript({
8
8
  pixelUrl,
9
9
  apiUrl,
10
10
  projectId
11
11
  }) {
12
- const consent = useConsent();
13
- if (!findDelegatedPlatform() && !isConsentAllowed({ state: consent, requiredConsent: ["analytics"] })) {
12
+ const isBlockedByNativeConsent = useIsBlockedByNativeConsent(
13
+ PIXEL_REQUIRED_CONSENT
14
+ );
15
+ if (isBlockedByNativeConsent) {
14
16
  return null;
15
17
  }
16
18
  const descriptors = [
@@ -28,7 +30,7 @@ function ReploPixelScript({
28
30
  {
29
31
  baseId: PIXEL_SCRIPT_ID,
30
32
  descriptors,
31
- requiredConsent: ["analytics"]
33
+ requiredConsent: PIXEL_REQUIRED_CONSENT
32
34
  }
33
35
  );
34
36
  }
@@ -53,6 +53,9 @@ function createAnalyticsQueue({
53
53
  return;
54
54
  }
55
55
  if (isReady()) {
56
+ if (queue.length > 0) {
57
+ flush();
58
+ }
56
59
  send(payload);
57
60
  } else {
58
61
  queue.push(payload);
@@ -124,6 +127,9 @@ function createMethodQueue(checkInstanceReady, options) {
124
127
  }
125
128
  const instance = checkInstanceReady();
126
129
  if (instance) {
130
+ if (queue.length > 0) {
131
+ flush();
132
+ }
127
133
  const methodFunction = instance[method];
128
134
  if (typeof methodFunction === "function") {
129
135
  void methodFunction.apply(instance, args);
@@ -48,6 +48,11 @@ async function buyNowWithRecoveryAction(input) {
48
48
  };
49
49
  });
50
50
  if (checkoutProvider === "stripe") {
51
+ if (discountCodes.length > 0 || lineItems.some((lineItem) => Boolean(lineItem.sellingPlanId))) {
52
+ console.warn(
53
+ "[Replo] Stripe buy now does not support selling plans or discount codes; those options were ignored."
54
+ );
55
+ }
51
56
  const env = await getEnv();
52
57
  const temporaryCartId = input.checkoutAttemptId ?? uuidv4();
53
58
  const body = {
@@ -78,4 +78,83 @@ export declare const cartSchema: z.ZodObject<{
78
78
  country: z.ZodNullable<z.ZodString>;
79
79
  }, z.core.$strip>>;
80
80
  }, z.core.$strip>;
81
+ export declare const clientCartSchema: z.ZodObject<{
82
+ id: z.ZodString;
83
+ cost: z.ZodObject<{
84
+ subtotalAmount: z.ZodNumber;
85
+ totalAmount: z.ZodNumber;
86
+ currencyCode: z.ZodString;
87
+ }, z.core.$strip>;
88
+ checkoutUrl: z.ZodOptional<z.ZodString>;
89
+ discountCodes: z.ZodOptional<z.ZodArray<z.ZodObject<{
90
+ code: z.ZodString;
91
+ applicable: z.ZodBoolean;
92
+ }, z.core.$strip>>>;
93
+ discountAllocations: z.ZodOptional<z.ZodArray<z.ZodObject<{
94
+ discountedAmount: z.ZodNumber;
95
+ title: z.ZodNullable<z.ZodString>;
96
+ }, z.core.$strip>>>;
97
+ buyerIdentity: z.ZodOptional<z.ZodObject<{
98
+ country: z.ZodNullable<z.ZodString>;
99
+ }, z.core.$strip>>;
100
+ lines: z.ZodArray<z.ZodObject<{
101
+ id: z.ZodString;
102
+ quantity: z.ZodNumber;
103
+ attributes: z.ZodArray<z.ZodObject<{
104
+ key: z.ZodString;
105
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
106
+ }, z.core.$strip>>;
107
+ sellingPlanAllocation: z.ZodOptional<z.ZodNullable<z.ZodObject<{
108
+ sellingPlan: z.ZodObject<{
109
+ id: z.ZodString;
110
+ name: z.ZodString;
111
+ description: z.ZodNullable<z.ZodString>;
112
+ }, z.core.$strip>;
113
+ priceAdjustments: z.ZodArray<z.ZodObject<{
114
+ compareAtPrice: z.ZodObject<{
115
+ amount: z.ZodNumber;
116
+ currencyCode: z.ZodString;
117
+ }, z.core.$strip>;
118
+ perDeliveryPrice: z.ZodObject<{
119
+ amount: z.ZodNumber;
120
+ currencyCode: z.ZodString;
121
+ }, z.core.$strip>;
122
+ price: z.ZodObject<{
123
+ amount: z.ZodNumber;
124
+ currencyCode: z.ZodString;
125
+ }, z.core.$strip>;
126
+ unitPrice: z.ZodNullable<z.ZodObject<{
127
+ amount: z.ZodNumber;
128
+ currencyCode: z.ZodString;
129
+ }, z.core.$strip>>;
130
+ }, z.core.$strip>>;
131
+ checkoutChargeAmount: z.ZodObject<{
132
+ amount: z.ZodNumber;
133
+ currencyCode: z.ZodString;
134
+ }, z.core.$strip>;
135
+ remainingBalanceChargeAmount: z.ZodObject<{
136
+ amount: z.ZodNumber;
137
+ currencyCode: z.ZodString;
138
+ }, z.core.$strip>;
139
+ }, z.core.$strip>>>;
140
+ merchandise: z.ZodNullable<z.ZodObject<{
141
+ id: z.ZodString;
142
+ title: z.ZodString;
143
+ price: z.ZodNumber;
144
+ compareAtPrice: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
145
+ image: z.ZodNullable<z.ZodObject<{
146
+ url: z.ZodString;
147
+ altText: z.ZodNullable<z.ZodString>;
148
+ }, z.core.$strip>>;
149
+ selectedOptions: z.ZodArray<z.ZodObject<{
150
+ name: z.ZodString;
151
+ value: z.ZodString;
152
+ }, z.core.$strip>>;
153
+ product: z.ZodObject<{
154
+ id: z.ZodString;
155
+ title: z.ZodString;
156
+ }, z.core.$loose>;
157
+ }, z.core.$strip>>;
158
+ }, z.core.$strip>>;
159
+ }, z.core.$strip>;
81
160
  export type Cart = z.infer<typeof cartSchema>;
@@ -69,6 +69,16 @@ const cartSchema = z.object({
69
69
  discountAllocations: z.array(cartDiscountAllocationSchema).optional(),
70
70
  buyerIdentity: z.object({ country: z.string().nullable() }).optional()
71
71
  });
72
+ const clientCartSchema = cartSchema.extend({
73
+ lines: z.array(
74
+ cartLineSchema.extend({
75
+ merchandise: cartLineMerchandiseSchema.extend({
76
+ product: cartLineMerchandiseSchema.shape.product.loose()
77
+ }).nullable()
78
+ })
79
+ )
80
+ });
72
81
  export {
73
- cartSchema
82
+ cartSchema,
83
+ clientCartSchema
74
84
  };
@@ -21,7 +21,8 @@ export interface VariantBuyNowInfo {
21
21
  /**
22
22
  * React hook that returns a `buyNow` function for express checkout flows.
23
23
  * Handles creating the cart/checkout session server-side and redirecting
24
- * the browser to checkout.
24
+ * the browser to checkout. Stripe checkout ignores selling plans and discount
25
+ * codes, logging a server-side warning when either is supplied.
25
26
  *
26
27
  * @example
27
28
  *
@@ -66,7 +66,8 @@ function calculateCartTotals({
66
66
  }) {
67
67
  const lineItemSubtotal = calculateLineItemsSubtotal(lineItems);
68
68
  const compareAtSubtotal = lineItems.reduce((sum, item) => {
69
- return sum + getCartLinePricing(item).compareAtPrice * item.quantity;
69
+ const { compareAtPrice, finalPrice } = getCartLinePricing(item);
70
+ return sum + Math.max(compareAtPrice, finalPrice) * item.quantity;
70
71
  }, 0);
71
72
  const total = cart?.cost.totalAmount ?? lineItemSubtotal;
72
73
  const discountAmount = (cart?.discountAllocations ?? []).reduce(
@@ -1,10 +1,28 @@
1
1
  "use server";
2
2
  import { cookies } from "next/headers";
3
+ import { parseJsonOrNull } from "../../_vendor/replo-utils/lib/json.mjs";
4
+ import { CanopyError } from "../../lib/canopy-error";
5
+ import { clientCartSchema } from "../cart-schema";
3
6
  import { getCartCookieOptions } from "../gateways/cart-constants";
4
7
  import { recalculateCartCost } from "./cart-utils";
8
+ const MAX_CART_COOKIE_SIZE_BYTES = 3900;
9
+ class CartCookieSizeError extends CanopyError {
10
+ }
5
11
  async function saveCartToCookie(cart, cookieName) {
12
+ const serializedCart = JSON.stringify(cart);
13
+ const serializedSizeBytes = encodeURIComponent(serializedCart).length;
14
+ if (serializedSizeBytes > MAX_CART_COOKIE_SIZE_BYTES) {
15
+ throw new CartCookieSizeError({
16
+ message: `[Replo] ${cookieName} exceeds the browser cookie size limit; cart changes were not persisted.`,
17
+ additionalData: {
18
+ cookieName,
19
+ serializedSizeBytes,
20
+ maxSizeBytes: MAX_CART_COOKIE_SIZE_BYTES
21
+ }
22
+ });
23
+ }
6
24
  const cookieStore = await cookies();
7
- cookieStore.set(cookieName, JSON.stringify(cart), getCartCookieOptions());
25
+ cookieStore.set(cookieName, serializedCart, getCartCookieOptions());
8
26
  }
9
27
  async function loadCartFromCookie(cookieName) {
10
28
  const cookieStore = await cookies();
@@ -12,13 +30,13 @@ async function loadCartFromCookie(cookieName) {
12
30
  if (!cartCookie?.value) {
13
31
  return null;
14
32
  }
15
- try {
16
- return JSON.parse(cartCookie.value);
17
- } catch (error) {
18
- console.warn("Failed to parse cart cookie:", error);
19
- await clearCartCookie(cookieName);
20
- return null;
33
+ const result = clientCartSchema.safeParse(parseJsonOrNull(cartCookie.value));
34
+ if (result.success) {
35
+ return result.data;
21
36
  }
37
+ console.warn("Failed to parse cart cookie:", result.error);
38
+ await clearCartCookie(cookieName);
39
+ return null;
22
40
  }
23
41
  async function clearCartCookie(cookieName) {
24
42
  const cookieStore = await cookies();
@@ -1,5 +1,16 @@
1
1
  import type { ConsentAction } from "../_vendor/schemas/generated/consent";
2
2
  import type { ConsentCategories } from "./cookie";
3
+ /**
4
+ * Pure mapping from a consent decision (previous state vs the resulting state)
5
+ * to the legal-record `action` written to the proof-of-consent audit log.
6
+ *
7
+ * Only non-necessary categories matter (`necessary` is always granted). The
8
+ * mapping is:
9
+ * - first decision (`decidedAt === null`), some category granted -> "accept"
10
+ * - first decision, nothing granted -> "reject"
11
+ * - later decision moving from some consent to none -> "withdraw"
12
+ * - any other later change -> "update"
13
+ */
3
14
  export declare function deriveConsentAction({ previous, next, }: {
4
15
  previous: {
5
16
  decidedAt: number | null;
@@ -1,23 +1,15 @@
1
- const NON_NECESSARY_CATEGORIES = [
2
- "analytics",
3
- "marketing",
4
- "preferences",
5
- "sale_of_data"
6
- ];
1
+ import { OPTIONAL_CONSENT_CATEGORIES } from "./consent-platform";
2
+ function hasAnyGranted(categories) {
3
+ return OPTIONAL_CONSENT_CATEGORIES.some((category) => categories[category]);
4
+ }
7
5
  function deriveConsentAction({
8
6
  previous,
9
7
  next
10
8
  }) {
11
- const anyGranted = NON_NECESSARY_CATEGORIES.some(
12
- (category) => next[category]
13
- );
14
9
  if (previous.decidedAt === null) {
15
- return anyGranted ? "accept" : "reject";
16
- }
17
- if (!anyGranted) {
18
- return "withdraw";
10
+ return hasAnyGranted(next) ? "accept" : "reject";
19
11
  }
20
- return "update";
12
+ return hasAnyGranted(previous.categories) && !hasAnyGranted(next) ? "withdraw" : "update";
21
13
  }
22
14
  export {
23
15
  deriveConsentAction
@@ -6,11 +6,10 @@ import type { ConsentCategories } from "./cookie";
6
6
  * all share the same state regardless of where they sit in the React tree — no
7
7
  * provider-ancestor relationship is required.
8
8
  *
9
- * Consent-dependent work (script injection, banner visibility) happens on the
10
- * client (effects / post-mount), so there is no SSR/hydration mismatch. The
11
- * client reads the (non-httpOnly) consent cookie directly, so no server seed is
12
- * needed. The whole-site `mode` comes from the `data-replo-consent-mode`
13
- * attribute on `<html>`.
9
+ * SSR and the first hydration render use a `mode: "off"` snapshot, which allows
10
+ * every category under native consent. Irreversible consent work must wait for
11
+ * client hydration, when the cookie-backed snapshot is available. The
12
+ * whole-site `mode` comes from `data-replo-consent-mode` on `<html>`.
14
13
  */
15
14
  export interface ConsentState {
16
15
  /** Which platform owns consent. Absent means Replo's native banner; "external" is a generic `consentPlatform` entry. */
@@ -11,7 +11,6 @@ import {
11
11
  isConsentPlatformEntry,
12
12
  OPTIONAL_CONSENT_CATEGORIES
13
13
  } from "./consent-platform";
14
- import { isConsentAllowed, useConsent } from "./consent-store";
15
14
  import { injectScriptDescriptors } from "./inject-script-descriptors";
16
15
  import {
17
16
  registerScript,
@@ -19,6 +18,7 @@ import {
19
18
  unregisterScript
20
19
  } from "./script-registration-store";
21
20
  import { buildScriptTags, defaultConsentFor } from "./script-snippets";
21
+ import { useIsBlockedByNativeConsent } from "./use-is-blocked-by-native-consent";
22
22
  import { installConsentWindowApi } from "./window-api";
23
23
  function scriptId(entry) {
24
24
  if (entry.type === "custom") {
@@ -90,10 +90,9 @@ class ScriptRegistration extends Component {
90
90
  }
91
91
  }
92
92
  function ManagedScript({ entry }) {
93
- const consent = useConsent();
94
93
  const requiredConsent = requiredConsentFor(entry);
95
94
  const id = scriptId(entry);
96
- const isBlockedByNativeConsent = !findDelegatedPlatform() && !isConsentAllowed({ state: consent, requiredConsent });
95
+ const isBlockedByNativeConsent = useIsBlockedByNativeConsent(requiredConsent);
97
96
  return /* @__PURE__ */ jsxs(Fragment, { children: [
98
97
  /* @__PURE__ */ jsx(
99
98
  ScriptRegistration,
@@ -0,0 +1,11 @@
1
+ import type { ReactNode } from "react";
2
+ import type { ConsentCategories } from "./cookie";
3
+ export declare function clearConsentCookie(): void;
4
+ export declare function writeConsentCookie({ categories, consentId, }: {
5
+ categories: ConsentCategories;
6
+ consentId: string;
7
+ }): void;
8
+ export declare function hydrateFromServer(element: ReactNode): {
9
+ root: import("react-dom/client").Root;
10
+ serverHtml: string;
11
+ };
@@ -0,0 +1,29 @@
1
+ import { flushSync } from "react-dom";
2
+ import { hydrateRoot } from "react-dom/client";
3
+ import { renderToString } from "react-dom/server";
4
+ import { CONSENT_COOKIE_NAME, serializeConsentCookieValue } from "./cookie";
5
+ function clearConsentCookie() {
6
+ document.cookie = `${CONSENT_COOKIE_NAME}=; path=/; max-age=0`;
7
+ }
8
+ function writeConsentCookie({
9
+ categories,
10
+ consentId
11
+ }) {
12
+ document.cookie = `${CONSENT_COOKIE_NAME}=${serializeConsentCookieValue({
13
+ categories,
14
+ decidedAt: 1e3,
15
+ consentId
16
+ })}; path=/`;
17
+ }
18
+ function hydrateFromServer(element) {
19
+ const serverHtml = renderToString(element);
20
+ const container = document.createElement("div");
21
+ container.innerHTML = serverHtml;
22
+ const root = flushSync(() => hydrateRoot(container, element));
23
+ return { root, serverHtml };
24
+ }
25
+ export {
26
+ clearConsentCookie,
27
+ hydrateFromServer,
28
+ writeConsentCookie
29
+ };
@@ -0,0 +1,2 @@
1
+ import type { ConsentCategory } from "../_vendor/schemas/generated/consent";
2
+ export declare function useIsBlockedByNativeConsent(requiredConsent: ConsentCategory[]): boolean;
@@ -0,0 +1,11 @@
1
+ import { useIsHydrated } from "../hooks/use-is-hydrated";
2
+ import { findDelegatedPlatform } from "./consent-platform";
3
+ import { isConsentAllowed, useConsent } from "./consent-store";
4
+ function useIsBlockedByNativeConsent(requiredConsent) {
5
+ const isHydrated = useIsHydrated();
6
+ const consent = useConsent();
7
+ return !findDelegatedPlatform() && (!isHydrated || !isConsentAllowed({ state: consent, requiredConsent }));
8
+ }
9
+ export {
10
+ useIsBlockedByNativeConsent
11
+ };
@@ -0,0 +1,2 @@
1
+ /** False during SSR and hydration, then true for client renders. */
2
+ export declare function useIsHydrated(): boolean;
@@ -0,0 +1,11 @@
1
+ import { useSyncExternalStore } from "react";
2
+ const subscribe = () => () => {
3
+ };
4
+ const getClientSnapshot = () => true;
5
+ const getServerSnapshot = () => false;
6
+ function useIsHydrated() {
7
+ return useSyncExternalStore(subscribe, getClientSnapshot, getServerSnapshot);
8
+ }
9
+ export {
10
+ useIsHydrated
11
+ };
@@ -1,7 +1,7 @@
1
1
  export const BUILD_METADATA = {
2
2
  "packageName": "@replohq/sdk",
3
- "version": "1.9.3",
3
+ "version": "1.9.5",
4
4
  "branch": "HEAD",
5
- "commit": "c32fdfc2a6a7ee4c9353574f7c61b940fe0bbb19",
6
- "builtAt": "2026-09-18T15:00:53.352Z"
5
+ "commit": "0a035b21ce1b041469758df14644035659d54252",
6
+ "builtAt": "2026-09-18T18:40:51.491Z"
7
7
  };
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@replohq/sdk",
3
- "version": "1.9.3",
3
+ "version": "1.9.5",
4
4
  "reploBuild": {
5
5
  "packageName": "@replohq/sdk",
6
- "version": "1.9.3",
6
+ "version": "1.9.5",
7
7
  "branch": "HEAD",
8
- "commit": "c32fdfc2a6a7ee4c9353574f7c61b940fe0bbb19",
9
- "builtAt": "2026-09-18T15:00:53.352Z"
8
+ "commit": "0a035b21ce1b041469758df14644035659d54252",
9
+ "builtAt": "2026-09-18T18:40:51.491Z"
10
10
  },
11
11
  "description": "Replo SDK — cart, analytics, and data loaders for agent-built Next.js sites.",
12
12
  "license": "SEE LICENSE IN LICENSE",