@economist/web-apple-pay 1.15.1-beta.1 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -147,10 +147,14 @@ Consumers should listen for this event and continue payment orchestration.
147
147
  - `createIfEnabled(offer, country, entryPoint?)`: returns a configured button or `null`.
148
148
  - `DUAL_OFFER_BANNER` (or omitted): always-on after offer exclusions — no homepage/Safari gate at `createIfEnabled` (device gating via `isApplePayAvailable` on mount).
149
149
  - `FREE_TRIAL_BANNER`: same always-on-after-exclusions gate as Dual; wallet impression `entry_point` is `free_trial_banner`.
150
- - `FREE_TRIAL_POPUP`: same always-on-after-exclusions gate. Wallet impression `entry_point` is `free_trial_popup`. On payment success for a logged-in reader, `/checkout/complete` is opened with `status=nspc`. An anonymous popup stays `nex`. Other entry points stay `lex` or `nex`. The origin URL is still written to `checkout-redirect` for sma-checkout.
150
+ - `FREE_TRIAL_POPUP`: same always-on-after-exclusions gate. Wallet impression `entry_point` is `free_trial_popup`.
151
151
  - `SUBSCRIBE`: same always-on-after-exclusions gate for `/subscribe` (sma-checkout); no Amplitude. Wallet impression `entry_point` is `subscribe`.
152
152
  - `PAYWALL`: always-on after offer exclusions + Safari/Apple placement eligibility. No Amplitude experiment / `$exposure`.
153
153
  - `REGWALL`: inert — always returns `null`.
154
+ - **Where the user returns after purchase.** Each entry point sets a `ReturnUrlPolicy` in `ENTRY_POINT_CONFIG` (`src/apple-pay-button.ts`), which decides what is written to `localStorage['checkout-redirect']` (read by the onboarding app):
155
+ - `CURRENT_PAGE`: the page the button is on (banners, popup, paywall, regwall), e.g. back to the article.
156
+ - `HOST_MANAGED`: nothing is written, so the host's own value is kept (`SUBSCRIBE`: sma-checkout stores the article the user arrived from; with none stored, onboarding returns them to the home page).
157
+ - A new entry point must declare its policy, or it will not compile.
154
158
  - `ApplePayModal`: modal component class.
155
159
  - `ensureApplePayLogoSymbol()`: logo symbol injection helper.
156
160
  - `Offer`: offer contract type used by component props.
@@ -220,4 +224,3 @@ Story coverage matrix:
220
224
  - `ApplePayButton` behavior and state variants are available as individual canvas stories in Storybook.
221
225
  - `ApplePayModal` docs page shows the stable default example.
222
226
  - `ApplePayModal` behavior and state variants are available as individual canvas stories in Storybook.
223
-
package/dist/index.js CHANGED
@@ -569,15 +569,21 @@ var configureApplePay = (config) => {
569
569
  var getApplePayConfig = () => runtimeConfig;
570
570
 
571
571
  // src/utils/recaptcha.ts
572
+ var findScriptForKey = (siteKey) => Array.from(
573
+ document.querySelectorAll(
574
+ 'script[src*="recaptcha/api.js"]'
575
+ )
576
+ ).find((script) => script.src.includes(`render=${siteKey}`));
577
+ var pendingLoads = /* @__PURE__ */ new Map();
572
578
  var loadRecaptchaScript = (siteKey) => {
573
- return new Promise((resolve, reject) => {
574
- if (typeof grecaptcha !== "undefined") return resolve();
575
- const existingScript = document.querySelector(
576
- 'script[src*="recaptcha/api.js"]'
577
- );
578
- if (existingScript) {
579
- existingScript.addEventListener("load", () => resolve());
580
- existingScript.addEventListener("error", () => {
579
+ const pending = pendingLoads.get(siteKey);
580
+ if (pending) return pending;
581
+ const ownScript = findScriptForKey(siteKey);
582
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
583
+ const load = new Promise((resolve, reject) => {
584
+ if (ownScript) {
585
+ ownScript.addEventListener("load", () => resolve());
586
+ ownScript.addEventListener("error", () => {
581
587
  reject(new Error("Failed to load existing reCAPTCHA script"));
582
588
  });
583
589
  return;
@@ -592,6 +598,9 @@ var loadRecaptchaScript = (siteKey) => {
592
598
  };
593
599
  document.head.appendChild(script);
594
600
  });
601
+ pendingLoads.set(siteKey, load);
602
+ load.catch(() => pendingLoads.delete(siteKey));
603
+ return load;
595
604
  };
596
605
  var getRecaptchaToken = async (action) => {
597
606
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -1303,8 +1312,13 @@ function isAllowedRedirectUrl(url) {
1303
1312
  return false;
1304
1313
  }
1305
1314
  }
1315
+ var CHECKOUT_REDIRECT_BY_POLICY = {
1316
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
1317
+ ["host_managed" /* HOST_MANAGED */]: () => null
1318
+ };
1319
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
1306
1320
  var writeCheckoutRedirect = (originUrl) => {
1307
- if (!isAllowedRedirectUrl(originUrl)) return;
1321
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
1308
1322
  try {
1309
1323
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
1310
1324
  } catch {
@@ -1611,17 +1625,6 @@ var shippingContactDetails = (shippingContact) => {
1611
1625
  return { emailAddress };
1612
1626
  };
1613
1627
 
1614
- // src/constants.ts
1615
- var ApplePayEntryPoint = /* @__PURE__ */ ((ApplePayEntryPoint2) => {
1616
- ApplePayEntryPoint2["PAYWALL"] = "article_paywall";
1617
- ApplePayEntryPoint2["REGWALL"] = "article_regwall";
1618
- ApplePayEntryPoint2["DUAL_OFFER_BANNER"] = "dual_offer_banner";
1619
- ApplePayEntryPoint2["FREE_TRIAL_BANNER"] = "free_trial_banner";
1620
- ApplePayEntryPoint2["FREE_TRIAL_POPUP"] = "free_trial_popup";
1621
- ApplePayEntryPoint2["SUBSCRIBE"] = "subscribe";
1622
- return ApplePayEntryPoint2;
1623
- })(ApplePayEntryPoint || {});
1624
-
1625
1628
  // src/clients/payment-checkout/payment-handler.ts
1626
1629
  var failApplePaySession = (session, errors = []) => {
1627
1630
  session.completePayment({
@@ -1702,8 +1705,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
1702
1705
  trackWalletPaymentSuccess(skuId, result.basketId);
1703
1706
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
1704
1707
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
1705
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
1706
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
1708
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
1707
1709
  writeCheckoutRedirect(returnUrl);
1708
1710
  window.location.href = redirectToCheckoutComplete({
1709
1711
  basketId: result.basketId,
@@ -2007,29 +2009,48 @@ var isNativeButtonEnabled = (hostname = window.location.hostname, override, enab
2007
2009
  // src/utils/applePayExpressEligibility.ts
2008
2010
  var isEligibleForApplePayExpressPaywall = () => isAppleDeviceOrSafari();
2009
2011
 
2012
+ // src/constants.ts
2013
+ var ApplePayEntryPoint = /* @__PURE__ */ ((ApplePayEntryPoint2) => {
2014
+ ApplePayEntryPoint2["PAYWALL"] = "article_paywall";
2015
+ ApplePayEntryPoint2["REGWALL"] = "article_regwall";
2016
+ ApplePayEntryPoint2["DUAL_OFFER_BANNER"] = "dual_offer_banner";
2017
+ ApplePayEntryPoint2["FREE_TRIAL_BANNER"] = "free_trial_banner";
2018
+ ApplePayEntryPoint2["FREE_TRIAL_POPUP"] = "free_trial_popup";
2019
+ ApplePayEntryPoint2["SUBSCRIBE"] = "subscribe";
2020
+ return ApplePayEntryPoint2;
2021
+ })(ApplePayEntryPoint || {});
2022
+
2010
2023
  // src/apple-pay-button.ts
2011
2024
  var ENTRY_POINT_CONFIG = {
2012
2025
  ["dual_offer_banner" /* DUAL_OFFER_BANNER */]: {
2013
- isEligible: () => true
2026
+ isEligible: () => true,
2027
+ returnUrl: "current_page" /* CURRENT_PAGE */
2014
2028
  },
2015
2029
  ["free_trial_banner" /* FREE_TRIAL_BANNER */]: {
2016
- isEligible: () => true
2030
+ isEligible: () => true,
2031
+ returnUrl: "current_page" /* CURRENT_PAGE */
2017
2032
  },
2018
2033
  ["article_paywall" /* PAYWALL */]: {
2019
- isEligible: isEligibleForApplePayExpressPaywall
2034
+ isEligible: isEligibleForApplePayExpressPaywall,
2035
+ returnUrl: "current_page" /* CURRENT_PAGE */
2020
2036
  },
2021
2037
  ["article_regwall" /* REGWALL */]: {
2022
2038
  isEligible: () => true,
2023
- enabled: false
2039
+ enabled: false,
2040
+ returnUrl: "current_page" /* CURRENT_PAGE */
2024
2041
  },
2025
2042
  ["free_trial_popup" /* FREE_TRIAL_POPUP */]: {
2026
- isEligible: () => true
2043
+ isEligible: () => true,
2044
+ returnUrl: "current_page" /* CURRENT_PAGE */
2027
2045
  },
2028
2046
  ["subscribe" /* SUBSCRIBE */]: {
2029
- isEligible: () => true
2047
+ isEligible: () => true,
2030
2048
  // Always-on after offer exclusions — host (sma-checkout) owns rollout toggle
2049
+ // The offers page is not a place to return to: the host keeps the article the user arrived from (or home).
2050
+ returnUrl: "host_managed" /* HOST_MANAGED */
2031
2051
  }
2032
2052
  };
2053
+ var DEFAULT_ENTRY_POINT = "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2033
2054
  var TOTAL_LABEL = "The Economist";
2034
2055
  var DEFAULT_CURRENCY = "USD";
2035
2056
  var DEFAULT_TOTAL = "0.00";
@@ -2072,7 +2093,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2072
2093
  if (APPLE_PAY_EXCLUDED_VARIANTS.includes(offer.product?.variant)) {
2073
2094
  return null;
2074
2095
  }
2075
- const resolvedEntryPoint = entryPoint || "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2096
+ const resolvedEntryPoint = entryPoint || DEFAULT_ENTRY_POINT;
2076
2097
  const config = ENTRY_POINT_CONFIG[resolvedEntryPoint];
2077
2098
  if (!config) {
2078
2099
  return null;
@@ -2110,7 +2131,10 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2110
2131
  #readyPromise = null;
2111
2132
  #sessionData = null;
2112
2133
  #paymentOptions = null;
2134
+ /** URL of the page the button is on (sent to payment options). */
2113
2135
  #returnUrl = "";
2136
+ /** `checkout-redirect` to persist after purchase, per the entry point's `ReturnUrlPolicy`; `null` = leave it. */
2137
+ #checkoutRedirectUrl = null;
2114
2138
  #supportedBillingCountries = [];
2115
2139
  #entryPoint = "";
2116
2140
  // ─── Public API ─────────────────────────────────────────────────────────────
@@ -2176,6 +2200,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2176
2200
  this.#sessionData = null;
2177
2201
  this.#paymentOptions = null;
2178
2202
  this.#returnUrl = "";
2203
+ this.#checkoutRedirectUrl = null;
2179
2204
  this.#supportedBillingCountries = [];
2180
2205
  this.querySelector(SEL_CONTAINER)?.remove();
2181
2206
  }
@@ -2244,6 +2269,11 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2244
2269
  /** Captures the current page URL once at mount for reuse across the session lifetime. */
2245
2270
  #captureReturnUrl() {
2246
2271
  this.#returnUrl = captureOriginUrl();
2272
+ const config = ENTRY_POINT_CONFIG[this.#entryPoint || DEFAULT_ENTRY_POINT] ?? ENTRY_POINT_CONFIG[DEFAULT_ENTRY_POINT];
2273
+ this.#checkoutRedirectUrl = resolveCheckoutRedirectUrl(
2274
+ config.returnUrl,
2275
+ this.#returnUrl
2276
+ );
2247
2277
  }
2248
2278
  /**
2249
2279
  * Computes supported billing countries once at mount.
@@ -2370,7 +2400,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2370
2400
  totalAmount,
2371
2401
  totalLabel: TOTAL_LABEL,
2372
2402
  skuId,
2373
- returnUrl: this.#returnUrl,
2403
+ returnUrl: this.#checkoutRedirectUrl,
2374
2404
  userLoggedIn: sessionData.loggedIn,
2375
2405
  onPaymentAuthorized: async (event, session) => {
2376
2406
  const recaptchaToken = await recaptchaTokenPromise;
@@ -2378,10 +2408,9 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2378
2408
  skuId,
2379
2409
  country,
2380
2410
  currency: offer.price?.currency_code ?? DEFAULT_CURRENCY,
2381
- returnUrl: this.#returnUrl,
2411
+ returnUrl: this.#checkoutRedirectUrl,
2382
2412
  supportedBillingCountries: this.#supportedBillingCountries,
2383
- recaptchaToken,
2384
- entryPoint: this.#entryPoint
2413
+ recaptchaToken
2385
2414
  });
2386
2415
  }
2387
2416
  };
@@ -2404,7 +2433,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2404
2433
  );
2405
2434
  } catch {
2406
2435
  redirectToFallbackCheckout({
2407
- returnUrl: this.#returnUrl,
2436
+ returnUrl: this.#checkoutRedirectUrl,
2408
2437
  skuId,
2409
2438
  countryCode: country
2410
2439
  });
@@ -564,15 +564,21 @@ var runtimeConfig = null;
564
564
  var getApplePayConfig = () => runtimeConfig;
565
565
 
566
566
  // src/utils/recaptcha.ts
567
+ var findScriptForKey = (siteKey) => Array.from(
568
+ document.querySelectorAll(
569
+ 'script[src*="recaptcha/api.js"]'
570
+ )
571
+ ).find((script) => script.src.includes(`render=${siteKey}`));
572
+ var pendingLoads = /* @__PURE__ */ new Map();
567
573
  var loadRecaptchaScript = (siteKey) => {
568
- return new Promise((resolve, reject) => {
569
- if (typeof grecaptcha !== "undefined") return resolve();
570
- const existingScript = document.querySelector(
571
- 'script[src*="recaptcha/api.js"]'
572
- );
573
- if (existingScript) {
574
- existingScript.addEventListener("load", () => resolve());
575
- existingScript.addEventListener("error", () => {
574
+ const pending = pendingLoads.get(siteKey);
575
+ if (pending) return pending;
576
+ const ownScript = findScriptForKey(siteKey);
577
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
578
+ const load = new Promise((resolve, reject) => {
579
+ if (ownScript) {
580
+ ownScript.addEventListener("load", () => resolve());
581
+ ownScript.addEventListener("error", () => {
576
582
  reject(new Error("Failed to load existing reCAPTCHA script"));
577
583
  });
578
584
  return;
@@ -587,6 +593,9 @@ var loadRecaptchaScript = (siteKey) => {
587
593
  };
588
594
  document.head.appendChild(script);
589
595
  });
596
+ pendingLoads.set(siteKey, load);
597
+ load.catch(() => pendingLoads.delete(siteKey));
598
+ return load;
590
599
  };
591
600
  var getRecaptchaToken = async (action) => {
592
601
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -1298,8 +1307,13 @@ function isAllowedRedirectUrl(url) {
1298
1307
  return false;
1299
1308
  }
1300
1309
  }
1310
+ var CHECKOUT_REDIRECT_BY_POLICY = {
1311
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
1312
+ ["host_managed" /* HOST_MANAGED */]: () => null
1313
+ };
1314
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
1301
1315
  var writeCheckoutRedirect = (originUrl) => {
1302
- if (!isAllowedRedirectUrl(originUrl)) return;
1316
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
1303
1317
  try {
1304
1318
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
1305
1319
  } catch {
@@ -1686,8 +1700,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
1686
1700
  trackWalletPaymentSuccess(skuId, result.basketId);
1687
1701
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
1688
1702
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
1689
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
1690
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
1703
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
1691
1704
  writeCheckoutRedirect(returnUrl);
1692
1705
  window.location.href = redirectToCheckoutComplete({
1693
1706
  basketId: result.basketId,
@@ -1994,26 +2007,34 @@ var isEligibleForApplePayExpressPaywall = () => isAppleDeviceOrSafari();
1994
2007
  // src/apple-pay-button.ts
1995
2008
  var ENTRY_POINT_CONFIG = {
1996
2009
  ["dual_offer_banner" /* DUAL_OFFER_BANNER */]: {
1997
- isEligible: () => true
2010
+ isEligible: () => true,
2011
+ returnUrl: "current_page" /* CURRENT_PAGE */
1998
2012
  },
1999
2013
  ["free_trial_banner" /* FREE_TRIAL_BANNER */]: {
2000
- isEligible: () => true
2014
+ isEligible: () => true,
2015
+ returnUrl: "current_page" /* CURRENT_PAGE */
2001
2016
  },
2002
2017
  ["article_paywall" /* PAYWALL */]: {
2003
- isEligible: isEligibleForApplePayExpressPaywall
2018
+ isEligible: isEligibleForApplePayExpressPaywall,
2019
+ returnUrl: "current_page" /* CURRENT_PAGE */
2004
2020
  },
2005
2021
  ["article_regwall" /* REGWALL */]: {
2006
2022
  isEligible: () => true,
2007
- enabled: false
2023
+ enabled: false,
2024
+ returnUrl: "current_page" /* CURRENT_PAGE */
2008
2025
  },
2009
2026
  ["free_trial_popup" /* FREE_TRIAL_POPUP */]: {
2010
- isEligible: () => true
2027
+ isEligible: () => true,
2028
+ returnUrl: "current_page" /* CURRENT_PAGE */
2011
2029
  },
2012
2030
  ["subscribe" /* SUBSCRIBE */]: {
2013
- isEligible: () => true
2031
+ isEligible: () => true,
2014
2032
  // Always-on after offer exclusions — host (sma-checkout) owns rollout toggle
2033
+ // The offers page is not a place to return to: the host keeps the article the user arrived from (or home).
2034
+ returnUrl: "host_managed" /* HOST_MANAGED */
2015
2035
  }
2016
2036
  };
2037
+ var DEFAULT_ENTRY_POINT = "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2017
2038
  var TOTAL_LABEL = "The Economist";
2018
2039
  var DEFAULT_CURRENCY = "USD";
2019
2040
  var DEFAULT_TOTAL = "0.00";
@@ -2056,7 +2077,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2056
2077
  if (APPLE_PAY_EXCLUDED_VARIANTS.includes(offer.product?.variant)) {
2057
2078
  return null;
2058
2079
  }
2059
- const resolvedEntryPoint = entryPoint || "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2080
+ const resolvedEntryPoint = entryPoint || DEFAULT_ENTRY_POINT;
2060
2081
  const config = ENTRY_POINT_CONFIG[resolvedEntryPoint];
2061
2082
  if (!config) {
2062
2083
  return null;
@@ -2094,7 +2115,10 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2094
2115
  #readyPromise = null;
2095
2116
  #sessionData = null;
2096
2117
  #paymentOptions = null;
2118
+ /** URL of the page the button is on (sent to payment options). */
2097
2119
  #returnUrl = "";
2120
+ /** `checkout-redirect` to persist after purchase, per the entry point's `ReturnUrlPolicy`; `null` = leave it. */
2121
+ #checkoutRedirectUrl = null;
2098
2122
  #supportedBillingCountries = [];
2099
2123
  #entryPoint = "";
2100
2124
  // ─── Public API ─────────────────────────────────────────────────────────────
@@ -2160,6 +2184,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2160
2184
  this.#sessionData = null;
2161
2185
  this.#paymentOptions = null;
2162
2186
  this.#returnUrl = "";
2187
+ this.#checkoutRedirectUrl = null;
2163
2188
  this.#supportedBillingCountries = [];
2164
2189
  this.querySelector(SEL_CONTAINER)?.remove();
2165
2190
  }
@@ -2228,6 +2253,11 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2228
2253
  /** Captures the current page URL once at mount for reuse across the session lifetime. */
2229
2254
  #captureReturnUrl() {
2230
2255
  this.#returnUrl = captureOriginUrl();
2256
+ const config = ENTRY_POINT_CONFIG[this.#entryPoint || DEFAULT_ENTRY_POINT] ?? ENTRY_POINT_CONFIG[DEFAULT_ENTRY_POINT];
2257
+ this.#checkoutRedirectUrl = resolveCheckoutRedirectUrl(
2258
+ config.returnUrl,
2259
+ this.#returnUrl
2260
+ );
2231
2261
  }
2232
2262
  /**
2233
2263
  * Computes supported billing countries once at mount.
@@ -2354,7 +2384,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2354
2384
  totalAmount,
2355
2385
  totalLabel: TOTAL_LABEL,
2356
2386
  skuId,
2357
- returnUrl: this.#returnUrl,
2387
+ returnUrl: this.#checkoutRedirectUrl,
2358
2388
  userLoggedIn: sessionData.loggedIn,
2359
2389
  onPaymentAuthorized: async (event, session) => {
2360
2390
  const recaptchaToken = await recaptchaTokenPromise;
@@ -2362,10 +2392,9 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2362
2392
  skuId,
2363
2393
  country,
2364
2394
  currency: offer.price?.currency_code ?? DEFAULT_CURRENCY,
2365
- returnUrl: this.#returnUrl,
2395
+ returnUrl: this.#checkoutRedirectUrl,
2366
2396
  supportedBillingCountries: this.#supportedBillingCountries,
2367
- recaptchaToken,
2368
- entryPoint: this.#entryPoint
2397
+ recaptchaToken
2369
2398
  });
2370
2399
  }
2371
2400
  };
@@ -2388,7 +2417,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2388
2417
  );
2389
2418
  } catch {
2390
2419
  redirectToFallbackCheckout({
2391
- returnUrl: this.#returnUrl,
2420
+ returnUrl: this.#checkoutRedirectUrl,
2392
2421
  skuId,
2393
2422
  countryCode: country
2394
2423
  });
@@ -572,15 +572,21 @@ var resetApplePayConfig = () => {
572
572
  };
573
573
 
574
574
  // src/utils/recaptcha.ts
575
+ var findScriptForKey = (siteKey) => Array.from(
576
+ document.querySelectorAll(
577
+ 'script[src*="recaptcha/api.js"]'
578
+ )
579
+ ).find((script) => script.src.includes(`render=${siteKey}`));
580
+ var pendingLoads = /* @__PURE__ */ new Map();
575
581
  var loadRecaptchaScript = (siteKey) => {
576
- return new Promise((resolve, reject) => {
577
- if (typeof grecaptcha !== "undefined") return resolve();
578
- const existingScript = document.querySelector(
579
- 'script[src*="recaptcha/api.js"]'
580
- );
581
- if (existingScript) {
582
- existingScript.addEventListener("load", () => resolve());
583
- existingScript.addEventListener("error", () => {
582
+ const pending = pendingLoads.get(siteKey);
583
+ if (pending) return pending;
584
+ const ownScript = findScriptForKey(siteKey);
585
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
586
+ const load = new Promise((resolve, reject) => {
587
+ if (ownScript) {
588
+ ownScript.addEventListener("load", () => resolve());
589
+ ownScript.addEventListener("error", () => {
584
590
  reject(new Error("Failed to load existing reCAPTCHA script"));
585
591
  });
586
592
  return;
@@ -595,6 +601,9 @@ var loadRecaptchaScript = (siteKey) => {
595
601
  };
596
602
  document.head.appendChild(script);
597
603
  });
604
+ pendingLoads.set(siteKey, load);
605
+ load.catch(() => pendingLoads.delete(siteKey));
606
+ return load;
598
607
  };
599
608
  var getRecaptchaToken = async (action) => {
600
609
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -1306,8 +1315,13 @@ function isAllowedRedirectUrl(url) {
1306
1315
  return false;
1307
1316
  }
1308
1317
  }
1318
+ var CHECKOUT_REDIRECT_BY_POLICY = {
1319
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
1320
+ ["host_managed" /* HOST_MANAGED */]: () => null
1321
+ };
1322
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
1309
1323
  var writeCheckoutRedirect = (originUrl) => {
1310
- if (!isAllowedRedirectUrl(originUrl)) return;
1324
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
1311
1325
  try {
1312
1326
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
1313
1327
  } catch {
@@ -1694,8 +1708,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
1694
1708
  trackWalletPaymentSuccess(skuId, result.basketId);
1695
1709
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
1696
1710
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
1697
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
1698
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
1711
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
1699
1712
  writeCheckoutRedirect(returnUrl);
1700
1713
  window.location.href = redirectToCheckoutComplete({
1701
1714
  basketId: result.basketId,
@@ -2002,26 +2015,34 @@ var isEligibleForApplePayExpressPaywall = () => isAppleDeviceOrSafari();
2002
2015
  // src/apple-pay-button.ts
2003
2016
  var ENTRY_POINT_CONFIG = {
2004
2017
  ["dual_offer_banner" /* DUAL_OFFER_BANNER */]: {
2005
- isEligible: () => true
2018
+ isEligible: () => true,
2019
+ returnUrl: "current_page" /* CURRENT_PAGE */
2006
2020
  },
2007
2021
  ["free_trial_banner" /* FREE_TRIAL_BANNER */]: {
2008
- isEligible: () => true
2022
+ isEligible: () => true,
2023
+ returnUrl: "current_page" /* CURRENT_PAGE */
2009
2024
  },
2010
2025
  ["article_paywall" /* PAYWALL */]: {
2011
- isEligible: isEligibleForApplePayExpressPaywall
2026
+ isEligible: isEligibleForApplePayExpressPaywall,
2027
+ returnUrl: "current_page" /* CURRENT_PAGE */
2012
2028
  },
2013
2029
  ["article_regwall" /* REGWALL */]: {
2014
2030
  isEligible: () => true,
2015
- enabled: false
2031
+ enabled: false,
2032
+ returnUrl: "current_page" /* CURRENT_PAGE */
2016
2033
  },
2017
2034
  ["free_trial_popup" /* FREE_TRIAL_POPUP */]: {
2018
- isEligible: () => true
2035
+ isEligible: () => true,
2036
+ returnUrl: "current_page" /* CURRENT_PAGE */
2019
2037
  },
2020
2038
  ["subscribe" /* SUBSCRIBE */]: {
2021
- isEligible: () => true
2039
+ isEligible: () => true,
2022
2040
  // Always-on after offer exclusions — host (sma-checkout) owns rollout toggle
2041
+ // The offers page is not a place to return to: the host keeps the article the user arrived from (or home).
2042
+ returnUrl: "host_managed" /* HOST_MANAGED */
2023
2043
  }
2024
2044
  };
2045
+ var DEFAULT_ENTRY_POINT = "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2025
2046
  var TOTAL_LABEL = "The Economist";
2026
2047
  var DEFAULT_CURRENCY = "USD";
2027
2048
  var DEFAULT_TOTAL = "0.00";
@@ -2064,7 +2085,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2064
2085
  if (APPLE_PAY_EXCLUDED_VARIANTS.includes(offer.product?.variant)) {
2065
2086
  return null;
2066
2087
  }
2067
- const resolvedEntryPoint = entryPoint || "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2088
+ const resolvedEntryPoint = entryPoint || DEFAULT_ENTRY_POINT;
2068
2089
  const config = ENTRY_POINT_CONFIG[resolvedEntryPoint];
2069
2090
  if (!config) {
2070
2091
  return null;
@@ -2102,7 +2123,10 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2102
2123
  #readyPromise = null;
2103
2124
  #sessionData = null;
2104
2125
  #paymentOptions = null;
2126
+ /** URL of the page the button is on (sent to payment options). */
2105
2127
  #returnUrl = "";
2128
+ /** `checkout-redirect` to persist after purchase, per the entry point's `ReturnUrlPolicy`; `null` = leave it. */
2129
+ #checkoutRedirectUrl = null;
2106
2130
  #supportedBillingCountries = [];
2107
2131
  #entryPoint = "";
2108
2132
  // ─── Public API ─────────────────────────────────────────────────────────────
@@ -2168,6 +2192,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2168
2192
  this.#sessionData = null;
2169
2193
  this.#paymentOptions = null;
2170
2194
  this.#returnUrl = "";
2195
+ this.#checkoutRedirectUrl = null;
2171
2196
  this.#supportedBillingCountries = [];
2172
2197
  this.querySelector(SEL_CONTAINER)?.remove();
2173
2198
  }
@@ -2236,6 +2261,11 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2236
2261
  /** Captures the current page URL once at mount for reuse across the session lifetime. */
2237
2262
  #captureReturnUrl() {
2238
2263
  this.#returnUrl = captureOriginUrl();
2264
+ const config = ENTRY_POINT_CONFIG[this.#entryPoint || DEFAULT_ENTRY_POINT] ?? ENTRY_POINT_CONFIG[DEFAULT_ENTRY_POINT];
2265
+ this.#checkoutRedirectUrl = resolveCheckoutRedirectUrl(
2266
+ config.returnUrl,
2267
+ this.#returnUrl
2268
+ );
2239
2269
  }
2240
2270
  /**
2241
2271
  * Computes supported billing countries once at mount.
@@ -2362,7 +2392,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2362
2392
  totalAmount,
2363
2393
  totalLabel: TOTAL_LABEL,
2364
2394
  skuId,
2365
- returnUrl: this.#returnUrl,
2395
+ returnUrl: this.#checkoutRedirectUrl,
2366
2396
  userLoggedIn: sessionData.loggedIn,
2367
2397
  onPaymentAuthorized: async (event, session) => {
2368
2398
  const recaptchaToken = await recaptchaTokenPromise;
@@ -2370,10 +2400,9 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2370
2400
  skuId,
2371
2401
  country,
2372
2402
  currency: offer.price?.currency_code ?? DEFAULT_CURRENCY,
2373
- returnUrl: this.#returnUrl,
2403
+ returnUrl: this.#checkoutRedirectUrl,
2374
2404
  supportedBillingCountries: this.#supportedBillingCountries,
2375
- recaptchaToken,
2376
- entryPoint: this.#entryPoint
2405
+ recaptchaToken
2377
2406
  });
2378
2407
  }
2379
2408
  };
@@ -2396,7 +2425,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2396
2425
  );
2397
2426
  } catch {
2398
2427
  redirectToFallbackCheckout({
2399
- returnUrl: this.#returnUrl,
2428
+ returnUrl: this.#checkoutRedirectUrl,
2400
2429
  skuId,
2401
2430
  countryCode: country
2402
2431
  });
@@ -564,15 +564,21 @@ var runtimeConfig = null;
564
564
  var getApplePayConfig = () => runtimeConfig;
565
565
 
566
566
  // src/utils/recaptcha.ts
567
+ var findScriptForKey = (siteKey) => Array.from(
568
+ document.querySelectorAll(
569
+ 'script[src*="recaptcha/api.js"]'
570
+ )
571
+ ).find((script) => script.src.includes(`render=${siteKey}`));
572
+ var pendingLoads = /* @__PURE__ */ new Map();
567
573
  var loadRecaptchaScript = (siteKey) => {
568
- return new Promise((resolve, reject) => {
569
- if (typeof grecaptcha !== "undefined") return resolve();
570
- const existingScript = document.querySelector(
571
- 'script[src*="recaptcha/api.js"]'
572
- );
573
- if (existingScript) {
574
- existingScript.addEventListener("load", () => resolve());
575
- existingScript.addEventListener("error", () => {
574
+ const pending = pendingLoads.get(siteKey);
575
+ if (pending) return pending;
576
+ const ownScript = findScriptForKey(siteKey);
577
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
578
+ const load = new Promise((resolve, reject) => {
579
+ if (ownScript) {
580
+ ownScript.addEventListener("load", () => resolve());
581
+ ownScript.addEventListener("error", () => {
576
582
  reject(new Error("Failed to load existing reCAPTCHA script"));
577
583
  });
578
584
  return;
@@ -587,6 +593,9 @@ var loadRecaptchaScript = (siteKey) => {
587
593
  };
588
594
  document.head.appendChild(script);
589
595
  });
596
+ pendingLoads.set(siteKey, load);
597
+ load.catch(() => pendingLoads.delete(siteKey));
598
+ return load;
590
599
  };
591
600
  var getRecaptchaToken = async (action) => {
592
601
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -564,15 +564,21 @@ var runtimeConfig = null;
564
564
  var getApplePayConfig = () => runtimeConfig;
565
565
 
566
566
  // src/utils/recaptcha.ts
567
+ var findScriptForKey = (siteKey) => Array.from(
568
+ document.querySelectorAll(
569
+ 'script[src*="recaptcha/api.js"]'
570
+ )
571
+ ).find((script) => script.src.includes(`render=${siteKey}`));
572
+ var pendingLoads = /* @__PURE__ */ new Map();
567
573
  var loadRecaptchaScript = (siteKey) => {
568
- return new Promise((resolve, reject) => {
569
- if (typeof grecaptcha !== "undefined") return resolve();
570
- const existingScript = document.querySelector(
571
- 'script[src*="recaptcha/api.js"]'
572
- );
573
- if (existingScript) {
574
- existingScript.addEventListener("load", () => resolve());
575
- existingScript.addEventListener("error", () => {
574
+ const pending = pendingLoads.get(siteKey);
575
+ if (pending) return pending;
576
+ const ownScript = findScriptForKey(siteKey);
577
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
578
+ const load = new Promise((resolve, reject) => {
579
+ if (ownScript) {
580
+ ownScript.addEventListener("load", () => resolve());
581
+ ownScript.addEventListener("error", () => {
576
582
  reject(new Error("Failed to load existing reCAPTCHA script"));
577
583
  });
578
584
  return;
@@ -587,6 +593,9 @@ var loadRecaptchaScript = (siteKey) => {
587
593
  };
588
594
  document.head.appendChild(script);
589
595
  });
596
+ pendingLoads.set(siteKey, load);
597
+ load.catch(() => pendingLoads.delete(siteKey));
598
+ return load;
590
599
  };
591
600
  var getRecaptchaToken = async (action) => {
592
601
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -1298,8 +1307,13 @@ function isAllowedRedirectUrl(url) {
1298
1307
  return false;
1299
1308
  }
1300
1309
  }
1310
+ var CHECKOUT_REDIRECT_BY_POLICY = {
1311
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
1312
+ ["host_managed" /* HOST_MANAGED */]: () => null
1313
+ };
1314
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
1301
1315
  var writeCheckoutRedirect = (originUrl) => {
1302
- if (!isAllowedRedirectUrl(originUrl)) return;
1316
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
1303
1317
  try {
1304
1318
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
1305
1319
  } catch {
@@ -1686,8 +1700,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
1686
1700
  trackWalletPaymentSuccess(skuId, result.basketId);
1687
1701
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
1688
1702
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
1689
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
1690
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
1703
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
1691
1704
  writeCheckoutRedirect(returnUrl);
1692
1705
  window.location.href = redirectToCheckoutComplete({
1693
1706
  basketId: result.basketId,
@@ -1994,26 +2007,34 @@ var isEligibleForApplePayExpressPaywall = () => isAppleDeviceOrSafari();
1994
2007
  // src/apple-pay-button.ts
1995
2008
  var ENTRY_POINT_CONFIG = {
1996
2009
  ["dual_offer_banner" /* DUAL_OFFER_BANNER */]: {
1997
- isEligible: () => true
2010
+ isEligible: () => true,
2011
+ returnUrl: "current_page" /* CURRENT_PAGE */
1998
2012
  },
1999
2013
  ["free_trial_banner" /* FREE_TRIAL_BANNER */]: {
2000
- isEligible: () => true
2014
+ isEligible: () => true,
2015
+ returnUrl: "current_page" /* CURRENT_PAGE */
2001
2016
  },
2002
2017
  ["article_paywall" /* PAYWALL */]: {
2003
- isEligible: isEligibleForApplePayExpressPaywall
2018
+ isEligible: isEligibleForApplePayExpressPaywall,
2019
+ returnUrl: "current_page" /* CURRENT_PAGE */
2004
2020
  },
2005
2021
  ["article_regwall" /* REGWALL */]: {
2006
2022
  isEligible: () => true,
2007
- enabled: false
2023
+ enabled: false,
2024
+ returnUrl: "current_page" /* CURRENT_PAGE */
2008
2025
  },
2009
2026
  ["free_trial_popup" /* FREE_TRIAL_POPUP */]: {
2010
- isEligible: () => true
2027
+ isEligible: () => true,
2028
+ returnUrl: "current_page" /* CURRENT_PAGE */
2011
2029
  },
2012
2030
  ["subscribe" /* SUBSCRIBE */]: {
2013
- isEligible: () => true
2031
+ isEligible: () => true,
2014
2032
  // Always-on after offer exclusions — host (sma-checkout) owns rollout toggle
2033
+ // The offers page is not a place to return to: the host keeps the article the user arrived from (or home).
2034
+ returnUrl: "host_managed" /* HOST_MANAGED */
2015
2035
  }
2016
2036
  };
2037
+ var DEFAULT_ENTRY_POINT = "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2017
2038
  var TOTAL_LABEL = "The Economist";
2018
2039
  var DEFAULT_CURRENCY = "USD";
2019
2040
  var DEFAULT_TOTAL = "0.00";
@@ -2056,7 +2077,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2056
2077
  if (APPLE_PAY_EXCLUDED_VARIANTS.includes(offer.product?.variant)) {
2057
2078
  return null;
2058
2079
  }
2059
- const resolvedEntryPoint = entryPoint || "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2080
+ const resolvedEntryPoint = entryPoint || DEFAULT_ENTRY_POINT;
2060
2081
  const config = ENTRY_POINT_CONFIG[resolvedEntryPoint];
2061
2082
  if (!config) {
2062
2083
  return null;
@@ -2094,7 +2115,10 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2094
2115
  #readyPromise = null;
2095
2116
  #sessionData = null;
2096
2117
  #paymentOptions = null;
2118
+ /** URL of the page the button is on (sent to payment options). */
2097
2119
  #returnUrl = "";
2120
+ /** `checkout-redirect` to persist after purchase, per the entry point's `ReturnUrlPolicy`; `null` = leave it. */
2121
+ #checkoutRedirectUrl = null;
2098
2122
  #supportedBillingCountries = [];
2099
2123
  #entryPoint = "";
2100
2124
  // ─── Public API ─────────────────────────────────────────────────────────────
@@ -2160,6 +2184,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2160
2184
  this.#sessionData = null;
2161
2185
  this.#paymentOptions = null;
2162
2186
  this.#returnUrl = "";
2187
+ this.#checkoutRedirectUrl = null;
2163
2188
  this.#supportedBillingCountries = [];
2164
2189
  this.querySelector(SEL_CONTAINER)?.remove();
2165
2190
  }
@@ -2228,6 +2253,11 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2228
2253
  /** Captures the current page URL once at mount for reuse across the session lifetime. */
2229
2254
  #captureReturnUrl() {
2230
2255
  this.#returnUrl = captureOriginUrl();
2256
+ const config = ENTRY_POINT_CONFIG[this.#entryPoint || DEFAULT_ENTRY_POINT] ?? ENTRY_POINT_CONFIG[DEFAULT_ENTRY_POINT];
2257
+ this.#checkoutRedirectUrl = resolveCheckoutRedirectUrl(
2258
+ config.returnUrl,
2259
+ this.#returnUrl
2260
+ );
2231
2261
  }
2232
2262
  /**
2233
2263
  * Computes supported billing countries once at mount.
@@ -2354,7 +2384,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2354
2384
  totalAmount,
2355
2385
  totalLabel: TOTAL_LABEL,
2356
2386
  skuId,
2357
- returnUrl: this.#returnUrl,
2387
+ returnUrl: this.#checkoutRedirectUrl,
2358
2388
  userLoggedIn: sessionData.loggedIn,
2359
2389
  onPaymentAuthorized: async (event, session) => {
2360
2390
  const recaptchaToken = await recaptchaTokenPromise;
@@ -2362,10 +2392,9 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2362
2392
  skuId,
2363
2393
  country,
2364
2394
  currency: offer.price?.currency_code ?? DEFAULT_CURRENCY,
2365
- returnUrl: this.#returnUrl,
2395
+ returnUrl: this.#checkoutRedirectUrl,
2366
2396
  supportedBillingCountries: this.#supportedBillingCountries,
2367
- recaptchaToken,
2368
- entryPoint: this.#entryPoint
2397
+ recaptchaToken
2369
2398
  });
2370
2399
  }
2371
2400
  };
@@ -2388,7 +2417,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2388
2417
  );
2389
2418
  } catch {
2390
2419
  redirectToFallbackCheckout({
2391
- returnUrl: this.#returnUrl,
2420
+ returnUrl: this.#checkoutRedirectUrl,
2392
2421
  skuId,
2393
2422
  countryCode: country
2394
2423
  });
@@ -10,7 +10,8 @@ export type ApplePaySessionConfig = {
10
10
  totalAmount: string;
11
11
  totalLabel: string;
12
12
  skuId: string;
13
- returnUrl: string;
13
+ /** `checkout-redirect` to persist, or `null` to leave the host's value untouched. */
14
+ returnUrl: string | null;
14
15
  userLoggedIn: boolean;
15
16
  onPaymentAuthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent, session: ApplePaySession) => Promise<void>;
16
17
  onCancel?: () => void;
@@ -74,7 +74,7 @@ function isAllowedRedirectUrl(url) {
74
74
  }
75
75
  }
76
76
  var writeCheckoutRedirect = (originUrl) => {
77
- if (!isAllowedRedirectUrl(originUrl)) return;
77
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
78
78
  try {
79
79
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
80
80
  } catch {
@@ -100,15 +100,21 @@ var redirectToCheckoutFallback = (params) => {
100
100
  };
101
101
 
102
102
  // src/utils/recaptcha.ts
103
+ var findScriptForKey = (siteKey) => Array.from(
104
+ document.querySelectorAll(
105
+ 'script[src*="recaptcha/api.js"]'
106
+ )
107
+ ).find((script) => script.src.includes(`render=${siteKey}`));
108
+ var pendingLoads = /* @__PURE__ */ new Map();
103
109
  var loadRecaptchaScript = (siteKey) => {
104
- return new Promise((resolve, reject) => {
105
- if (typeof grecaptcha !== "undefined") return resolve();
106
- const existingScript = document.querySelector(
107
- 'script[src*="recaptcha/api.js"]'
108
- );
109
- if (existingScript) {
110
- existingScript.addEventListener("load", () => resolve());
111
- existingScript.addEventListener("error", () => {
110
+ const pending = pendingLoads.get(siteKey);
111
+ if (pending) return pending;
112
+ const ownScript = findScriptForKey(siteKey);
113
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
114
+ const load = new Promise((resolve, reject) => {
115
+ if (ownScript) {
116
+ ownScript.addEventListener("load", () => resolve());
117
+ ownScript.addEventListener("error", () => {
112
118
  reject(new Error("Failed to load existing reCAPTCHA script"));
113
119
  });
114
120
  return;
@@ -123,6 +129,9 @@ var loadRecaptchaScript = (siteKey) => {
123
129
  };
124
130
  document.head.appendChild(script);
125
131
  });
132
+ pendingLoads.set(siteKey, load);
133
+ load.catch(() => pendingLoads.delete(siteKey));
134
+ return load;
126
135
  };
127
136
  var getRecaptchaToken = async (action) => {
128
137
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -14,15 +14,13 @@
14
14
  * 4. Handling structured BFF errors → deterministic UI actions per errorType
15
15
  */
16
16
  import type { SessionResponse } from './types';
17
- import { ApplePayEntryPoint } from '../../constants';
18
17
  export type PaymentHandlerConfig = {
19
18
  skuId: string;
20
19
  country: string;
21
20
  currency: string;
22
- returnUrl: string;
21
+ /** `checkout-redirect` to persist, or `null` to leave the host's value untouched. */
22
+ returnUrl: string | null;
23
23
  supportedBillingCountries: string[];
24
24
  recaptchaToken: string;
25
- /** When FREE_TRIAL_POPUP and the session is logged in, complete is opened with status=nspc. */
26
- entryPoint?: ApplePayEntryPoint | '';
27
25
  };
28
26
  export declare function handlePaymentAuthorized(event: ApplePayJS.ApplePayPaymentAuthorizedEvent, session: ApplePaySession, sessionData: SessionResponse, config: PaymentHandlerConfig): Promise<void>;
@@ -249,7 +249,7 @@ function isAllowedRedirectUrl(url) {
249
249
  }
250
250
  }
251
251
  var writeCheckoutRedirect = (originUrl) => {
252
- if (!isAllowedRedirectUrl(originUrl)) return;
252
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
253
253
  try {
254
254
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
255
255
  } catch {
@@ -364,8 +364,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
364
364
  trackWalletPaymentSuccess(skuId, result.basketId);
365
365
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
366
366
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
367
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
368
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
367
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
369
368
  writeCheckoutRedirect(returnUrl);
370
369
  window.location.href = redirectToCheckoutComplete({
371
370
  basketId: result.basketId,
package/dist/src/index.js CHANGED
@@ -569,15 +569,21 @@ var configureApplePay = (config) => {
569
569
  var getApplePayConfig = () => runtimeConfig;
570
570
 
571
571
  // src/utils/recaptcha.ts
572
+ var findScriptForKey = (siteKey) => Array.from(
573
+ document.querySelectorAll(
574
+ 'script[src*="recaptcha/api.js"]'
575
+ )
576
+ ).find((script) => script.src.includes(`render=${siteKey}`));
577
+ var pendingLoads = /* @__PURE__ */ new Map();
572
578
  var loadRecaptchaScript = (siteKey) => {
573
- return new Promise((resolve, reject) => {
574
- if (typeof grecaptcha !== "undefined") return resolve();
575
- const existingScript = document.querySelector(
576
- 'script[src*="recaptcha/api.js"]'
577
- );
578
- if (existingScript) {
579
- existingScript.addEventListener("load", () => resolve());
580
- existingScript.addEventListener("error", () => {
579
+ const pending = pendingLoads.get(siteKey);
580
+ if (pending) return pending;
581
+ const ownScript = findScriptForKey(siteKey);
582
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
583
+ const load = new Promise((resolve, reject) => {
584
+ if (ownScript) {
585
+ ownScript.addEventListener("load", () => resolve());
586
+ ownScript.addEventListener("error", () => {
581
587
  reject(new Error("Failed to load existing reCAPTCHA script"));
582
588
  });
583
589
  return;
@@ -592,6 +598,9 @@ var loadRecaptchaScript = (siteKey) => {
592
598
  };
593
599
  document.head.appendChild(script);
594
600
  });
601
+ pendingLoads.set(siteKey, load);
602
+ load.catch(() => pendingLoads.delete(siteKey));
603
+ return load;
595
604
  };
596
605
  var getRecaptchaToken = async (action) => {
597
606
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
@@ -1303,8 +1312,13 @@ function isAllowedRedirectUrl(url) {
1303
1312
  return false;
1304
1313
  }
1305
1314
  }
1315
+ var CHECKOUT_REDIRECT_BY_POLICY = {
1316
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
1317
+ ["host_managed" /* HOST_MANAGED */]: () => null
1318
+ };
1319
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
1306
1320
  var writeCheckoutRedirect = (originUrl) => {
1307
- if (!isAllowedRedirectUrl(originUrl)) return;
1321
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
1308
1322
  try {
1309
1323
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
1310
1324
  } catch {
@@ -1611,17 +1625,6 @@ var shippingContactDetails = (shippingContact) => {
1611
1625
  return { emailAddress };
1612
1626
  };
1613
1627
 
1614
- // src/constants.ts
1615
- var ApplePayEntryPoint = /* @__PURE__ */ ((ApplePayEntryPoint2) => {
1616
- ApplePayEntryPoint2["PAYWALL"] = "article_paywall";
1617
- ApplePayEntryPoint2["REGWALL"] = "article_regwall";
1618
- ApplePayEntryPoint2["DUAL_OFFER_BANNER"] = "dual_offer_banner";
1619
- ApplePayEntryPoint2["FREE_TRIAL_BANNER"] = "free_trial_banner";
1620
- ApplePayEntryPoint2["FREE_TRIAL_POPUP"] = "free_trial_popup";
1621
- ApplePayEntryPoint2["SUBSCRIBE"] = "subscribe";
1622
- return ApplePayEntryPoint2;
1623
- })(ApplePayEntryPoint || {});
1624
-
1625
1628
  // src/clients/payment-checkout/payment-handler.ts
1626
1629
  var failApplePaySession = (session, errors = []) => {
1627
1630
  session.completePayment({
@@ -1702,8 +1705,7 @@ async function handlePaymentAuthorized(event, session, sessionData, config) {
1702
1705
  trackWalletPaymentSuccess(skuId, result.basketId);
1703
1706
  session.completePayment({ status: ApplePaySession.STATUS_SUCCESS });
1704
1707
  const successEmail = sessionData.loggedIn ? sessionData.emailAddress : validatedEmail;
1705
- const isFreeTrialPopup = config.entryPoint === "free_trial_popup" /* FREE_TRIAL_POPUP */;
1706
- const userStatus = isFreeTrialPopup && sessionData.loggedIn ? "nspc" : sessionData.loggedIn ? "lex" : "nex";
1708
+ const userStatus = sessionData.loggedIn ? "lex" : "nex";
1707
1709
  writeCheckoutRedirect(returnUrl);
1708
1710
  window.location.href = redirectToCheckoutComplete({
1709
1711
  basketId: result.basketId,
@@ -2007,29 +2009,48 @@ var isNativeButtonEnabled = (hostname = window.location.hostname, override, enab
2007
2009
  // src/utils/applePayExpressEligibility.ts
2008
2010
  var isEligibleForApplePayExpressPaywall = () => isAppleDeviceOrSafari();
2009
2011
 
2012
+ // src/constants.ts
2013
+ var ApplePayEntryPoint = /* @__PURE__ */ ((ApplePayEntryPoint2) => {
2014
+ ApplePayEntryPoint2["PAYWALL"] = "article_paywall";
2015
+ ApplePayEntryPoint2["REGWALL"] = "article_regwall";
2016
+ ApplePayEntryPoint2["DUAL_OFFER_BANNER"] = "dual_offer_banner";
2017
+ ApplePayEntryPoint2["FREE_TRIAL_BANNER"] = "free_trial_banner";
2018
+ ApplePayEntryPoint2["FREE_TRIAL_POPUP"] = "free_trial_popup";
2019
+ ApplePayEntryPoint2["SUBSCRIBE"] = "subscribe";
2020
+ return ApplePayEntryPoint2;
2021
+ })(ApplePayEntryPoint || {});
2022
+
2010
2023
  // src/apple-pay-button.ts
2011
2024
  var ENTRY_POINT_CONFIG = {
2012
2025
  ["dual_offer_banner" /* DUAL_OFFER_BANNER */]: {
2013
- isEligible: () => true
2026
+ isEligible: () => true,
2027
+ returnUrl: "current_page" /* CURRENT_PAGE */
2014
2028
  },
2015
2029
  ["free_trial_banner" /* FREE_TRIAL_BANNER */]: {
2016
- isEligible: () => true
2030
+ isEligible: () => true,
2031
+ returnUrl: "current_page" /* CURRENT_PAGE */
2017
2032
  },
2018
2033
  ["article_paywall" /* PAYWALL */]: {
2019
- isEligible: isEligibleForApplePayExpressPaywall
2034
+ isEligible: isEligibleForApplePayExpressPaywall,
2035
+ returnUrl: "current_page" /* CURRENT_PAGE */
2020
2036
  },
2021
2037
  ["article_regwall" /* REGWALL */]: {
2022
2038
  isEligible: () => true,
2023
- enabled: false
2039
+ enabled: false,
2040
+ returnUrl: "current_page" /* CURRENT_PAGE */
2024
2041
  },
2025
2042
  ["free_trial_popup" /* FREE_TRIAL_POPUP */]: {
2026
- isEligible: () => true
2043
+ isEligible: () => true,
2044
+ returnUrl: "current_page" /* CURRENT_PAGE */
2027
2045
  },
2028
2046
  ["subscribe" /* SUBSCRIBE */]: {
2029
- isEligible: () => true
2047
+ isEligible: () => true,
2030
2048
  // Always-on after offer exclusions — host (sma-checkout) owns rollout toggle
2049
+ // The offers page is not a place to return to: the host keeps the article the user arrived from (or home).
2050
+ returnUrl: "host_managed" /* HOST_MANAGED */
2031
2051
  }
2032
2052
  };
2053
+ var DEFAULT_ENTRY_POINT = "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2033
2054
  var TOTAL_LABEL = "The Economist";
2034
2055
  var DEFAULT_CURRENCY = "USD";
2035
2056
  var DEFAULT_TOTAL = "0.00";
@@ -2072,7 +2093,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2072
2093
  if (APPLE_PAY_EXCLUDED_VARIANTS.includes(offer.product?.variant)) {
2073
2094
  return null;
2074
2095
  }
2075
- const resolvedEntryPoint = entryPoint || "dual_offer_banner" /* DUAL_OFFER_BANNER */;
2096
+ const resolvedEntryPoint = entryPoint || DEFAULT_ENTRY_POINT;
2076
2097
  const config = ENTRY_POINT_CONFIG[resolvedEntryPoint];
2077
2098
  if (!config) {
2078
2099
  return null;
@@ -2110,7 +2131,10 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2110
2131
  #readyPromise = null;
2111
2132
  #sessionData = null;
2112
2133
  #paymentOptions = null;
2134
+ /** URL of the page the button is on (sent to payment options). */
2113
2135
  #returnUrl = "";
2136
+ /** `checkout-redirect` to persist after purchase, per the entry point's `ReturnUrlPolicy`; `null` = leave it. */
2137
+ #checkoutRedirectUrl = null;
2114
2138
  #supportedBillingCountries = [];
2115
2139
  #entryPoint = "";
2116
2140
  // ─── Public API ─────────────────────────────────────────────────────────────
@@ -2176,6 +2200,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2176
2200
  this.#sessionData = null;
2177
2201
  this.#paymentOptions = null;
2178
2202
  this.#returnUrl = "";
2203
+ this.#checkoutRedirectUrl = null;
2179
2204
  this.#supportedBillingCountries = [];
2180
2205
  this.querySelector(SEL_CONTAINER)?.remove();
2181
2206
  }
@@ -2244,6 +2269,11 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2244
2269
  /** Captures the current page URL once at mount for reuse across the session lifetime. */
2245
2270
  #captureReturnUrl() {
2246
2271
  this.#returnUrl = captureOriginUrl();
2272
+ const config = ENTRY_POINT_CONFIG[this.#entryPoint || DEFAULT_ENTRY_POINT] ?? ENTRY_POINT_CONFIG[DEFAULT_ENTRY_POINT];
2273
+ this.#checkoutRedirectUrl = resolveCheckoutRedirectUrl(
2274
+ config.returnUrl,
2275
+ this.#returnUrl
2276
+ );
2247
2277
  }
2248
2278
  /**
2249
2279
  * Computes supported billing countries once at mount.
@@ -2370,7 +2400,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2370
2400
  totalAmount,
2371
2401
  totalLabel: TOTAL_LABEL,
2372
2402
  skuId,
2373
- returnUrl: this.#returnUrl,
2403
+ returnUrl: this.#checkoutRedirectUrl,
2374
2404
  userLoggedIn: sessionData.loggedIn,
2375
2405
  onPaymentAuthorized: async (event, session) => {
2376
2406
  const recaptchaToken = await recaptchaTokenPromise;
@@ -2378,10 +2408,9 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2378
2408
  skuId,
2379
2409
  country,
2380
2410
  currency: offer.price?.currency_code ?? DEFAULT_CURRENCY,
2381
- returnUrl: this.#returnUrl,
2411
+ returnUrl: this.#checkoutRedirectUrl,
2382
2412
  supportedBillingCountries: this.#supportedBillingCountries,
2383
- recaptchaToken,
2384
- entryPoint: this.#entryPoint
2413
+ recaptchaToken
2385
2414
  });
2386
2415
  }
2387
2416
  };
@@ -2404,7 +2433,7 @@ var ApplePayButton = class _ApplePayButton extends HTMLElement {
2404
2433
  );
2405
2434
  } catch {
2406
2435
  redirectToFallbackCheckout({
2407
- returnUrl: this.#returnUrl,
2436
+ returnUrl: this.#checkoutRedirectUrl,
2408
2437
  skuId,
2409
2438
  countryCode: country
2410
2439
  });
@@ -7,7 +7,23 @@
7
7
  *
8
8
  * Matches sma-checkout: src/lib/navigate-to-checkout/index.tsx
9
9
  */
10
- export declare const writeCheckoutRedirect: (originUrl: string) => void;
10
+ /**
11
+ * What the post-checkout "return to" target (`checkout-redirect`, read by the onboarding app once the user has
12
+ * finished onboarding) should be. Chosen per entry point in `ENTRY_POINT_CONFIG` (apple-pay-button.ts).
13
+ */
14
+ export declare enum ReturnUrlPolicy {
15
+ /** Return the user to the page the button is on, e.g. the article behind a paywall. */
16
+ CURRENT_PAGE = "current_page",
17
+ /**
18
+ * Leave `checkout-redirect` untouched: the host owns it. sma-checkout's /subscribe pages store the article the
19
+ * user arrived from (and never themselves), so overwriting it would send the user back to the offers page.
20
+ * With nothing stored, onboarding returns the user to the home page.
21
+ */
22
+ HOST_MANAGED = "host_managed"
23
+ }
24
+ export declare const resolveCheckoutRedirectUrl: (policy: ReturnUrlPolicy, currentPageUrl: string) => string | null;
25
+ /** Persists the return target. `null` (see `ReturnUrlPolicy.HOST_MANAGED`) leaves the stored value as it is. */
26
+ export declare const writeCheckoutRedirect: (originUrl: string | null) => void;
11
27
  /**
12
28
  * Captures the current page URL (the article the user is reading).
13
29
  * Must be called before any redirect occurs.
@@ -42,12 +58,11 @@ export declare const decodeSku: (sku: string) => string;
42
58
  * Always appended when non-empty to preserve geo-context across the redirect.
43
59
  *
44
60
  * The origin article URL is written to localStorage by the caller via
45
- * writeCheckoutRedirect() so sma-checkout can return the reader after
46
- * passwordless confirmation (`nspc`) or after onboarding.
61
+ * writeCheckoutRedirect() before this redirect fires.
47
62
  */
48
63
  export declare const redirectToCheckoutComplete: (params: {
49
64
  basketId: string;
50
- status: "nex" | "lex" | "nspc";
65
+ status: "nex" | "lex";
51
66
  skuId: string;
52
67
  email?: string;
53
68
  country?: string;
@@ -10,8 +10,18 @@ function isAllowedRedirectUrl(url) {
10
10
  return false;
11
11
  }
12
12
  }
13
+ var ReturnUrlPolicy = /* @__PURE__ */ ((ReturnUrlPolicy2) => {
14
+ ReturnUrlPolicy2["CURRENT_PAGE"] = "current_page";
15
+ ReturnUrlPolicy2["HOST_MANAGED"] = "host_managed";
16
+ return ReturnUrlPolicy2;
17
+ })(ReturnUrlPolicy || {});
18
+ var CHECKOUT_REDIRECT_BY_POLICY = {
19
+ ["current_page" /* CURRENT_PAGE */]: (currentPageUrl) => currentPageUrl,
20
+ ["host_managed" /* HOST_MANAGED */]: () => null
21
+ };
22
+ var resolveCheckoutRedirectUrl = (policy, currentPageUrl) => CHECKOUT_REDIRECT_BY_POLICY[policy](currentPageUrl);
13
23
  var writeCheckoutRedirect = (originUrl) => {
14
- if (!isAllowedRedirectUrl(originUrl)) return;
24
+ if (originUrl === null || !isAllowedRedirectUrl(originUrl)) return;
15
25
  try {
16
26
  localStorage.setItem(CHECKOUT_REDIRECT_KEY, originUrl);
17
27
  } catch {
@@ -53,10 +63,12 @@ var redirectToCheckoutFallback = (params) => {
53
63
  return url.pathname + url.search;
54
64
  };
55
65
  export {
66
+ ReturnUrlPolicy,
56
67
  buildQueryString,
57
68
  captureOriginUrl,
58
69
  decodeSku,
59
70
  redirectToCheckoutComplete,
60
71
  redirectToCheckoutFallback,
72
+ resolveCheckoutRedirectUrl,
61
73
  writeCheckoutRedirect
62
74
  };
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * reCAPTCHA v3 token acquisition.
3
3
  *
4
- * Dynamically injects the Google reCAPTCHA script loader into the DOM
5
- * because it is not loaded globally on article/paywall pages.
4
+ * Dynamically injects the Google reCAPTCHA script loader for this package's
5
+ * site key. Another reCAPTCHA script on the page (e.g. the host's own key) is
6
+ * not reused, because it does not register our key.
6
7
  *
7
8
  * The site key is provided at runtime via configureApplePay({ recaptchaSiteKey }).
8
9
  */
@@ -3,15 +3,21 @@ var runtimeConfig = null;
3
3
  var getApplePayConfig = () => runtimeConfig;
4
4
 
5
5
  // src/utils/recaptcha.ts
6
+ var findScriptForKey = (siteKey) => Array.from(
7
+ document.querySelectorAll(
8
+ 'script[src*="recaptcha/api.js"]'
9
+ )
10
+ ).find((script) => script.src.includes(`render=${siteKey}`));
11
+ var pendingLoads = /* @__PURE__ */ new Map();
6
12
  var loadRecaptchaScript = (siteKey) => {
7
- return new Promise((resolve, reject) => {
8
- if (typeof grecaptcha !== "undefined") return resolve();
9
- const existingScript = document.querySelector(
10
- 'script[src*="recaptcha/api.js"]'
11
- );
12
- if (existingScript) {
13
- existingScript.addEventListener("load", () => resolve());
14
- existingScript.addEventListener("error", () => {
13
+ const pending = pendingLoads.get(siteKey);
14
+ if (pending) return pending;
15
+ const ownScript = findScriptForKey(siteKey);
16
+ if (ownScript && typeof grecaptcha !== "undefined") return Promise.resolve();
17
+ const load = new Promise((resolve, reject) => {
18
+ if (ownScript) {
19
+ ownScript.addEventListener("load", () => resolve());
20
+ ownScript.addEventListener("error", () => {
15
21
  reject(new Error("Failed to load existing reCAPTCHA script"));
16
22
  });
17
23
  return;
@@ -26,6 +32,9 @@ var loadRecaptchaScript = (siteKey) => {
26
32
  };
27
33
  document.head.appendChild(script);
28
34
  });
35
+ pendingLoads.set(siteKey, load);
36
+ load.catch(() => pendingLoads.delete(siteKey));
37
+ return load;
29
38
  };
30
39
  var getRecaptchaToken = async (action) => {
31
40
  const siteKey = getApplePayConfig()?.recaptchaSiteKey;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@economist/web-apple-pay",
3
3
  "description": "Web component package for Apple Pay checkout UI",
4
- "version": "1.15.1-beta.1",
4
+ "version": "1.15.1",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",