@funnelfox/billing 0.13.2 → 0.14.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.
@@ -561,7 +561,7 @@ exports.PaymentMethod = void 0;
561
561
  /**
562
562
  * @fileoverview Constants for Funnefox SDK
563
563
  */
564
- const SDK_VERSION = '0.13.2';
564
+ const SDK_VERSION = '0.14.0';
565
565
  const DEFAULTS = {
566
566
  BASE_URL: 'https://billing.funnelfox.com',
567
567
  REGION: 'default',
@@ -603,6 +603,7 @@ const API_ENDPOINTS = {
603
603
  CREATE_PAYMENT: '/v1/checkout/create_payment',
604
604
  RESUME_PAYMENT: '/v1/checkout/resume_payment',
605
605
  ONE_CLICK: '/v1/checkout/one_click',
606
+ ONE_CLICK_WALLET_SESSION: '/v1/checkout/one_click_wallet_session',
606
607
  CREATE_SIMPLE_CLIENT_SESSION: '/v1/checkout/create_simple_client_session',
607
608
  RECALCULATE_TAX: '/v1/checkout/recalculate_tax',
608
609
  };
@@ -806,7 +807,7 @@ async function overlayNativeApplePayButton(wrapper, options) {
806
807
  'height:100%',
807
808
  '--apple-pay-button-width:100%',
808
809
  '--apple-pay-button-height:100%',
809
- '--apple-pay-button-border-radius:28px',
810
+ `--apple-pay-button-border-radius:${options.borderRadius ?? 28}px`,
810
811
  'display:block',
811
812
  'cursor:pointer',
812
813
  'z-index:1',
@@ -1610,6 +1611,13 @@ class APIClient {
1610
1611
  body: JSON.stringify(payload),
1611
1612
  }, timeoutMs));
1612
1613
  }
1614
+ /** `one_click_wallet_session`: prepares the wallet re-auth button of a one-click upsell. */
1615
+ async oneClickWalletSession(payload, timeoutMs) {
1616
+ return (await this.requestOnce(API_ENDPOINTS.ONE_CLICK_WALLET_SESSION, {
1617
+ method: 'POST',
1618
+ body: JSON.stringify(payload),
1619
+ }, timeoutMs));
1620
+ }
1613
1621
  /** `resume_payment`, POSTed exactly once (see `requestOnce`). */
1614
1622
  async resumePaymentOnce(params) {
1615
1623
  return (await this.requestOnce(API_ENDPOINTS.RESUME_PAYMENT, {
@@ -3086,7 +3094,7 @@ function warnIfOverlayNotFound() {
3086
3094
  function toPrimerError(message, error) {
3087
3095
  return error instanceof PrimerError ? error : new PrimerError(message, error);
3088
3096
  }
3089
- function callSafely(fn) {
3097
+ function callSafely$1(fn) {
3090
3098
  try {
3091
3099
  fn();
3092
3100
  }
@@ -3169,7 +3177,7 @@ async function runOneClickThreeDS(params) {
3169
3177
  // A repeated tokenization would start a second reveal timer, so the challenge
3170
3178
  // (and the caller's onThreeDSStart) would be reported twice: refuse it.
3171
3179
  if (settled || tokenized) {
3172
- callSafely(() => handler.handleFailure());
3180
+ callSafely$1(() => handler.handleFailure());
3173
3181
  return;
3174
3182
  }
3175
3183
  tokenized = true;
@@ -3179,7 +3187,7 @@ async function runOneClickThreeDS(params) {
3179
3187
  revealed = true;
3180
3188
  showOverlay();
3181
3189
  warnIfOverlayNotFound();
3182
- callSafely(params.onChallengeShown);
3190
+ callSafely$1(params.onChallengeShown);
3183
3191
  // The whole timeout belongs to the challenge the customer can see.
3184
3192
  if (timer) {
3185
3193
  clearTimeout(timer);
@@ -3191,7 +3199,7 @@ async function runOneClickThreeDS(params) {
3191
3199
  };
3192
3200
  const onResumeSuccess = async (data, handler) => {
3193
3201
  if (settled) {
3194
- callSafely(() => handler.handleFailure());
3202
+ callSafely$1(() => handler.handleFailure());
3195
3203
  return;
3196
3204
  }
3197
3205
  // The challenge is over: the timeout bounds only the challenge, never the POST.
@@ -3211,7 +3219,7 @@ async function runOneClickThreeDS(params) {
3211
3219
  });
3212
3220
  }
3213
3221
  catch (error) {
3214
- callSafely(() => handler.handleFailure());
3222
+ callSafely$1(() => handler.handleFailure());
3215
3223
  settle({
3216
3224
  kind: 'error',
3217
3225
  error: error,
@@ -3223,11 +3231,11 @@ async function runOneClickThreeDS(params) {
3223
3231
  if (response?.status === 'success' &&
3224
3232
  resumeData?.checkout_status === 'succeeded' &&
3225
3233
  !resumeData.action_required_token) {
3226
- callSafely(() => handler.handleSuccess());
3234
+ callSafely$1(() => handler.handleSuccess());
3227
3235
  }
3228
3236
  else {
3229
3237
  // A chained action token is never continued (no second challenge).
3230
- callSafely(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3238
+ callSafely$1(() => handler.handleFailure(resumeData?.failed_message_for_user || undefined));
3231
3239
  }
3232
3240
  settle({ kind: 'resumed', response });
3233
3241
  };
@@ -3336,6 +3344,10 @@ let defaultConfig = null;
3336
3344
  function configure(config) {
3337
3345
  defaultConfig = config;
3338
3346
  }
3347
+ /** The base URL from `configure()`, else the production one. */
3348
+ function defaultBaseUrl() {
3349
+ return defaultConfig?.baseUrl || DEFAULTS.BASE_URL;
3350
+ }
3339
3351
  function resolveConfig(options, functionName) {
3340
3352
  const { orgId, apiConfig } = options || {};
3341
3353
  const finalOrgId = orgId || defaultConfig?.orgId;
@@ -3410,9 +3422,6 @@ function buildOneClickRequest(options) {
3410
3422
  if (options.citCardNetworks !== undefined) {
3411
3423
  payload.cit_card_networks = options.citCardNetworks;
3412
3424
  }
3413
- if (options.citGooglePayPanOnly !== undefined) {
3414
- payload.cit_google_pay_pan_only = options.citGooglePayPanOnly;
3415
- }
3416
3425
  return payload;
3417
3426
  }
3418
3427
  function silentPurchase(options) {
@@ -3460,7 +3469,11 @@ const IDEMPOTENCY_KEY_IN_PROGRESS = 'idempotency_key_in_progress';
3460
3469
  const ONE_CLICK_RETRY_DELAYS_MS = [1000, 2000, 4000];
3461
3470
  /** Longer than the backend's wait for the user's lock (~12.6 s). */
3462
3471
  const ONE_CLICK_TIMEOUT_MS = 25000;
3472
+ /** org + external id of the customers with a one-click purchase running (silent or wallet). */
3463
3473
  const oneClickInFlight = new Set();
3474
+ function oneClickInFlightKey(orgId, externalId) {
3475
+ return `${orgId}\u0000${externalId}`;
3476
+ }
3464
3477
  /** A random UUID v4, or `null` when the browser has no crypto (then one_click is not retried). */
3465
3478
  function createIdempotencyKey() {
3466
3479
  const cryptoApi = typeof crypto === 'undefined' ? undefined : crypto;
@@ -3726,7 +3739,7 @@ function callHook(name, hook, info) {
3726
3739
  }
3727
3740
  catch (error) {
3728
3741
  // eslint-disable-next-line no-console
3729
- console.error(`[FunnelfoxSDK] silentPurchase ${name} hook threw`, error);
3742
+ console.error(`[FunnelfoxSDK] ${name} hook threw`, error);
3730
3743
  }
3731
3744
  }
3732
3745
  async function silentPurchaseDetailed(options) {
@@ -3736,7 +3749,7 @@ async function silentPurchaseDetailed(options) {
3736
3749
  }
3737
3750
  }
3738
3751
  const { orgId, baseUrl, externalId } = options;
3739
- const inFlightKey = `${orgId}\u0000${externalId}`;
3752
+ const inFlightKey = oneClickInFlightKey(orgId, externalId);
3740
3753
  if (oneClickInFlight.has(inFlightKey)) {
3741
3754
  return {
3742
3755
  outcome: 'error',
@@ -4035,6 +4048,762 @@ async function getAvailableStripePaymentMethods(params) {
4035
4048
  : [exports.PaymentMethod.PAYMENT_CARD];
4036
4049
  }
4037
4050
 
4051
+ /**
4052
+ * @fileoverview One-click upsell confirmed in the Apple Pay / Google Pay sheet (FFB-829).
4053
+ *
4054
+ * Primer (PRMSUP-10609): a saved wallet token must not be charged as a customer-initiated
4055
+ * payment, so the customer confirms the upsell in the wallet sheet again and the backend charges
4056
+ * that fresh, single-use token. The button is rendered from a client session the backend prepares
4057
+ * for the upsell (`one_click_wallet_session`). Apple Pay opens its sheet only from the tap itself,
4058
+ * with no request in between, so the session is prepared when the screen loads and kept alive
4059
+ * until the tap.
4060
+ */
4061
+ const WALLET_SESSION_INVALID = 'wallet_session_invalid';
4062
+ const WALLETS = ['APPLE_PAY', 'GOOGLE_PAY'];
4063
+ const SESSION_REQUEST_TIMEOUT_MS = 15000;
4064
+ /** How long Primer may take to report the payment methods the device can show. */
4065
+ const METHODS_TIMEOUT_MS = 10000;
4066
+ /**
4067
+ * The session is prepared again this long before it expires. The backend hands back an unused
4068
+ * session only while it has at least 10 minutes to live, so 15 always yields a fresh one.
4069
+ */
4070
+ const REFRESH_BEFORE_EXPIRY_MS = 15 * 60 * 1000;
4071
+ /** A tap on a session with less left than this is refused and the session is replaced. */
4072
+ const TAP_MIN_REMAINING_MS = 60 * 1000;
4073
+ /** Bounds the refresh timer for a session shorter than the refresh margin; a tap still checks it. */
4074
+ const MIN_REFRESH_DELAY_MS = 60 * 1000;
4075
+ const DEFAULT_BUTTON_HEIGHT = 54;
4076
+ const DEFAULT_BUTTON_RADIUS = 28;
4077
+ /** The backend sends naive UTC timestamps; without a zone `Date.parse` would read local time. */
4078
+ function parseUtc(value) {
4079
+ const hasZone = /([zZ]|[+-]\d{2}:?\d{2})$/.test(value);
4080
+ return Date.parse(hasZone ? value : `${value}Z`);
4081
+ }
4082
+ function parseWalletSession(data) {
4083
+ const expiresAt = data.expires_at ? parseUtc(data.expires_at) : NaN;
4084
+ if (!WALLETS.includes(data.wallet) ||
4085
+ !data.client_token ||
4086
+ !data.session_id ||
4087
+ !data.order_id ||
4088
+ !Number.isFinite(expiresAt)) {
4089
+ throw new APIError('Invalid one_click_wallet_session response', null, {
4090
+ response: data,
4091
+ });
4092
+ }
4093
+ return {
4094
+ wallet: data.wallet,
4095
+ clientToken: data.client_token,
4096
+ sessionId: data.session_id,
4097
+ orderId: data.order_id,
4098
+ amount: data.amount ?? null,
4099
+ currency: data.currency ?? null,
4100
+ expiresAt,
4101
+ };
4102
+ }
4103
+ /** `null` = the customer's saved method is not a Primer wallet. */
4104
+ async function prepareSession(apiClient, options) {
4105
+ const response = await apiClient.oneClickWalletSession({
4106
+ pp_ident: options.priceId,
4107
+ external_id: options.externalId,
4108
+ client_metadata: options.clientMetadata || {},
4109
+ }, SESSION_REQUEST_TIMEOUT_MS);
4110
+ if (response?.status !== 'success' || !response.data) {
4111
+ throw new APIError('one_click_wallet_session failed', null, { response });
4112
+ }
4113
+ if (response.data.wallet === null) {
4114
+ return null;
4115
+ }
4116
+ return parseWalletSession(response.data);
4117
+ }
4118
+ /** Primer's wallet options for the requested style; a type the wallet lacks becomes `plain`. */
4119
+ function primerWalletOptions(wallet, style) {
4120
+ const buttonType = style.buttonType || 'plain';
4121
+ const buttonColor = style.buttonColor || 'black';
4122
+ if (wallet === 'APPLE_PAY') {
4123
+ return {
4124
+ applePay: {
4125
+ buttonType: buttonType === 'buy' ? 'buy' : 'plain',
4126
+ buttonStyle: buttonColor,
4127
+ },
4128
+ };
4129
+ }
4130
+ return {
4131
+ googlePay: {
4132
+ buttonType: buttonType === 'continue' ? 'plain' : buttonType,
4133
+ buttonColor: buttonColor === 'black' ? 'black' : 'white',
4134
+ buttonSizeMode: 'fill',
4135
+ },
4136
+ };
4137
+ }
4138
+ function toError(message, error) {
4139
+ if (error instanceof FunnefoxSDKError) {
4140
+ return error;
4141
+ }
4142
+ return new PrimerError(message, error);
4143
+ }
4144
+ function callSafely(fn) {
4145
+ try {
4146
+ fn();
4147
+ }
4148
+ catch {
4149
+ // Primer handler calls are best effort once the outcome is decided.
4150
+ }
4151
+ }
4152
+ function isApiErrorWithCode(error, code) {
4153
+ return (error instanceof APIError &&
4154
+ (error.errorCode === code ||
4155
+ getResponseErrorCodes(error.response).includes(code)));
4156
+ }
4157
+ /** One mounted wallet button and the attempts made with it. */
4158
+ class WalletUpsell {
4159
+ constructor(container, options, session) {
4160
+ this.container = container;
4161
+ this.options = options;
4162
+ this.rendered = null;
4163
+ this.generation = 0;
4164
+ this.destroyed = false;
4165
+ /** An outcome other than `cancelled` was reported: the button stays disabled. */
4166
+ this.finished = false;
4167
+ this.disabledByCaller = false;
4168
+ this.refreshing = null;
4169
+ this.refreshTimer = null;
4170
+ this.attemptRunning = false;
4171
+ this.tokenizeStarted = false;
4172
+ /** The wallet token reached us: from here the attempt ends only with the charge's answer. */
4173
+ this.charging = false;
4174
+ this.threeDS = null;
4175
+ this.onVisibilityChange = () => {
4176
+ if (document.visibilityState === 'visible' && this.expiresSoon()) {
4177
+ this.refresh();
4178
+ }
4179
+ };
4180
+ this.session = session;
4181
+ this.apiClient = WalletUpsell.apiClientFor(options);
4182
+ this.inFlightKey = oneClickInFlightKey(options.orgId, options.externalId);
4183
+ }
4184
+ static apiClientFor(options) {
4185
+ return new APIClient({
4186
+ baseUrl: options.baseUrl || defaultBaseUrl(),
4187
+ orgId: options.orgId,
4188
+ timeout: DEFAULTS.REQUEST_TIMEOUT,
4189
+ retryAttempts: DEFAULTS.RETRY_ATTEMPTS,
4190
+ });
4191
+ }
4192
+ /** Renders the button for the current session: `false` when the device cannot show the wallet. */
4193
+ async render() {
4194
+ const generation = ++this.generation;
4195
+ const session = this.session;
4196
+ const style = this.options.style || {};
4197
+ await new PrimerWrapper().ensurePrimerLoaded();
4198
+ let reportMethods = () => { };
4199
+ let methodsTimer = null;
4200
+ const methods = new Promise((resolve, reject) => {
4201
+ reportMethods = resolve;
4202
+ methodsTimer = setTimeout(() => reject(new PrimerError('Primer did not report the available payment methods')), METHODS_TIMEOUT_MS);
4203
+ }).finally(() => clearTimeout(methodsTimer));
4204
+ // A dedicated instance: the checkouts' HeadlessManager caches by client token, and a
4205
+ // remounted upsell gets the same token back, so the cache would hand out a headless whose
4206
+ // callbacks belong to a destroyed mount.
4207
+ const headless = await window.Primer.createHeadless(session.clientToken, {
4208
+ paymentHandling: PRIMER_DEFAULTS.PAYMENT_HANDLING,
4209
+ apiVersion: PRIMER_DEFAULTS.API_VERSION,
4210
+ ...primerWalletOptions(session.wallet, style),
4211
+ onAvailablePaymentMethodsLoad: (items) => reportMethods(items.map(item => item.type)),
4212
+ onTokenizeShouldStart: () => this.onTap(generation),
4213
+ onTokenizeStart: () => {
4214
+ if (generation === this.generation) {
4215
+ this.tokenizeStarted = true;
4216
+ }
4217
+ },
4218
+ onPaymentMethodAction: action => {
4219
+ if (action === 'PAYMENT_METHOD_UNSELECTED') {
4220
+ this.onSheetClosed(generation);
4221
+ }
4222
+ },
4223
+ onTokenizeSuccess: (data, handler) => this.onTokenized(generation, data, handler),
4224
+ onTokenizeError: (error) => this.onPrimerFailure(generation, 'Wallet tokenization failed', error),
4225
+ onResumeSuccess: (data, handler) => this.onResumed(generation, data, handler),
4226
+ onResumeError: (error) => this.onResumeError(generation, error),
4227
+ onCheckoutFail: (error) => this.onPrimerFailure(generation, 'Primer checkout failed', error),
4228
+ });
4229
+ await headless.start();
4230
+ const available = await methods;
4231
+ if (!available.includes(session.wallet)) {
4232
+ return false;
4233
+ }
4234
+ const manager = await headless.createPaymentMethodManager(session.wallet);
4235
+ if (!manager || typeof manager.createButton !== 'function') {
4236
+ throw new PrimerError(`No ${session.wallet} button manager`);
4237
+ }
4238
+ const rendered = this.mountButton(generation, manager.createButton(), session.wallet, style);
4239
+ try {
4240
+ await rendered.button.render(rendered.wrapper, {});
4241
+ if (session.wallet === 'APPLE_PAY' && rendered.nativeOverlay === null) {
4242
+ rendered.nativeOverlay = await this.overlayAppleType(rendered, style);
4243
+ }
4244
+ }
4245
+ catch (error) {
4246
+ this.removeButton(rendered);
4247
+ throw error;
4248
+ }
4249
+ if (this.destroyed || generation !== this.generation) {
4250
+ this.removeButton(rendered);
4251
+ return true;
4252
+ }
4253
+ const previous = this.rendered;
4254
+ this.rendered = rendered;
4255
+ if (previous) {
4256
+ this.removeButton(previous);
4257
+ }
4258
+ this.applyDisabled();
4259
+ this.scheduleRefresh();
4260
+ return true;
4261
+ }
4262
+ mountButton(generation, button, wallet, style) {
4263
+ // Primer does not size its wallet buttons (FFB-169), so the wrapper's rules do.
4264
+ const wrapper = document.createElement('div');
4265
+ wrapper.className = generateId('funnelfox-wallet-upsell');
4266
+ const height = style.height ?? DEFAULT_BUTTON_HEIGHT;
4267
+ const radius = style.borderRadius ?? DEFAULT_BUTTON_RADIUS;
4268
+ const styleEl = document.createElement('style');
4269
+ styleEl.textContent = [
4270
+ `.${wrapper.className}{width:100%!important}`,
4271
+ `.${wrapper.className} button{height:${height}px!important;border-radius:${radius}px!important}`,
4272
+ wallet === 'APPLE_PAY' && style.buttonType === 'continue'
4273
+ ? `.${wrapper.className} > button{opacity:0!important}`
4274
+ : '',
4275
+ ].join('\n');
4276
+ document.head.appendChild(styleEl);
4277
+ this.container.appendChild(wrapper);
4278
+ return { generation, button, wrapper, styleEl, nativeOverlay: null };
4279
+ }
4280
+ /** PRD-1426: WebKit draws only the legacy Apple Pay types, so `continue` uses Apple's element. */
4281
+ async overlayAppleType(rendered, style) {
4282
+ if (style.buttonType !== 'continue') {
4283
+ return null;
4284
+ }
4285
+ const overlay = await overlayNativeApplePayButton(rendered.wrapper, {
4286
+ buttonType: style.buttonType,
4287
+ buttonStyle: style.buttonColor || 'black',
4288
+ borderRadius: style.borderRadius ?? DEFAULT_BUTTON_RADIUS,
4289
+ });
4290
+ if (!overlay) {
4291
+ // Apple's element could not load: show Primer's own (plain) button.
4292
+ rendered.styleEl.textContent = rendered.styleEl.textContent.replace(`.${rendered.wrapper.className} > button{opacity:0!important}`, '');
4293
+ }
4294
+ return overlay;
4295
+ }
4296
+ removeButton(rendered) {
4297
+ callSafely(() => rendered.button.clean());
4298
+ rendered.nativeOverlay?.remove();
4299
+ rendered.wrapper.remove();
4300
+ rendered.styleEl.remove();
4301
+ }
4302
+ applyDisabled() {
4303
+ const rendered = this.rendered;
4304
+ if (!rendered) {
4305
+ return;
4306
+ }
4307
+ const disabled = this.finished || this.disabledByCaller;
4308
+ void Promise.resolve(rendered.button.setDisabled(disabled)).catch(() => { });
4309
+ if (rendered.nativeOverlay) {
4310
+ rendered.nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
4311
+ rendered.nativeOverlay.style.opacity = disabled ? '0.5' : '';
4312
+ }
4313
+ }
4314
+ setDisabled(disabled) {
4315
+ this.disabledByCaller = disabled;
4316
+ this.applyDisabled();
4317
+ }
4318
+ destroy() {
4319
+ if (this.destroyed) {
4320
+ return;
4321
+ }
4322
+ this.destroyed = true;
4323
+ this.generation += 1;
4324
+ if (this.attemptRunning && !this.charging) {
4325
+ // Primer's callbacks for this mount are ignored from now on, so nothing else ends it.
4326
+ this.attemptRunning = false;
4327
+ oneClickInFlight.delete(this.inFlightKey);
4328
+ }
4329
+ this.clearRefresh();
4330
+ if (typeof document !== 'undefined') {
4331
+ document.removeEventListener('visibilitychange', this.onVisibilityChange);
4332
+ }
4333
+ if (this.rendered) {
4334
+ this.removeButton(this.rendered);
4335
+ this.rendered = null;
4336
+ }
4337
+ }
4338
+ // ---------- session life ----------
4339
+ watchVisibility() {
4340
+ if (typeof document !== 'undefined') {
4341
+ document.addEventListener('visibilitychange', this.onVisibilityChange);
4342
+ }
4343
+ }
4344
+ expiresSoon(minRemainingMs = REFRESH_BEFORE_EXPIRY_MS) {
4345
+ return this.session.expiresAt - Date.now() < minRemainingMs;
4346
+ }
4347
+ clearRefresh() {
4348
+ if (this.refreshTimer) {
4349
+ clearTimeout(this.refreshTimer);
4350
+ this.refreshTimer = null;
4351
+ }
4352
+ }
4353
+ scheduleRefresh() {
4354
+ this.clearRefresh();
4355
+ if (this.destroyed || this.finished) {
4356
+ return;
4357
+ }
4358
+ const delay = Math.max(this.session.expiresAt - REFRESH_BEFORE_EXPIRY_MS - Date.now(), MIN_REFRESH_DELAY_MS);
4359
+ this.refreshTimer = setTimeout(() => {
4360
+ this.refreshTimer = null;
4361
+ this.refresh();
4362
+ }, delay);
4363
+ }
4364
+ /** Replaces the session and the button before the session expires; never during an attempt. */
4365
+ refresh() {
4366
+ // An attempt ends either for good or as `cancelled`, which checks the session again.
4367
+ if (this.refreshing ||
4368
+ this.destroyed ||
4369
+ this.finished ||
4370
+ this.attemptRunning) {
4371
+ return;
4372
+ }
4373
+ this.refreshing = this.replaceSession().finally(() => {
4374
+ this.refreshing = null;
4375
+ });
4376
+ }
4377
+ async replaceSession() {
4378
+ let failure = null;
4379
+ try {
4380
+ const next = await prepareSession(this.apiClient, this.options);
4381
+ if (this.destroyed || this.finished) {
4382
+ return;
4383
+ }
4384
+ if (!next || next.wallet !== this.session.wallet) {
4385
+ failure = new FunnefoxSDKError('The wallet upsell is no longer available for this customer', 'wallet_upsell_unavailable');
4386
+ }
4387
+ else {
4388
+ this.session = next;
4389
+ if (!(await this.render())) {
4390
+ failure = new FunnefoxSDKError('This device can no longer show the wallet', 'wallet_upsell_unavailable');
4391
+ }
4392
+ }
4393
+ }
4394
+ catch (error) {
4395
+ failure = toError('Failed to prepare the wallet upsell again', error);
4396
+ }
4397
+ if (failure && !this.destroyed && !this.finished && !this.attemptRunning) {
4398
+ // The button can no longer charge: the caller takes its own path.
4399
+ this.report({
4400
+ outcome: 'error',
4401
+ orderId: null,
4402
+ threeDSChallenged: false,
4403
+ error: failure,
4404
+ });
4405
+ }
4406
+ }
4407
+ // ---------- attempt ----------
4408
+ onTap(generation) {
4409
+ if (generation !== this.generation ||
4410
+ this.destroyed ||
4411
+ this.finished ||
4412
+ this.disabledByCaller ||
4413
+ this.refreshing ||
4414
+ // Double tap, either wallet.
4415
+ this.attemptRunning ||
4416
+ oneClickInFlight.has(this.inFlightKey)) {
4417
+ return false;
4418
+ }
4419
+ if (this.expiresSoon(TAP_MIN_REMAINING_MS)) {
4420
+ // Apple Pay needs the tap itself to open the sheet: the customer taps the new button.
4421
+ this.refresh();
4422
+ return false;
4423
+ }
4424
+ this.attemptRunning = true;
4425
+ this.tokenizeStarted = false;
4426
+ oneClickInFlight.add(this.inFlightKey);
4427
+ callHook('onStart', this.options.onStart, undefined);
4428
+ return true;
4429
+ }
4430
+ onSheetClosed(generation) {
4431
+ if (generation !== this.generation ||
4432
+ !this.attemptRunning ||
4433
+ this.tokenizeStarted) {
4434
+ return;
4435
+ }
4436
+ this.finish({
4437
+ outcome: 'cancelled',
4438
+ orderId: null,
4439
+ threeDSChallenged: false,
4440
+ });
4441
+ }
4442
+ onPrimerFailure(generation, message, error) {
4443
+ if (generation !== this.generation || !this.attemptRunning) {
4444
+ return;
4445
+ }
4446
+ if (this.threeDS) {
4447
+ this.endThreeDS('failed');
4448
+ this.finish({
4449
+ outcome: '3ds_failed',
4450
+ orderId: this.session.orderId,
4451
+ threeDSChallenged: this.threeDSChallenged(),
4452
+ error: toError('3DS authentication failed', error),
4453
+ });
4454
+ return;
4455
+ }
4456
+ this.finish({
4457
+ outcome: 'error',
4458
+ orderId: null,
4459
+ threeDSChallenged: false,
4460
+ error: toError(message, error),
4461
+ });
4462
+ }
4463
+ onTokenized(generation, data, handler) {
4464
+ if (generation !== this.generation ||
4465
+ !this.attemptRunning ||
4466
+ this.threeDS) {
4467
+ callSafely(() => handler.handleFailure());
4468
+ return;
4469
+ }
4470
+ this.tokenizeStarted = true;
4471
+ this.charging = true;
4472
+ void this.charge(data.token, handler, false).catch(error => {
4473
+ callSafely(() => handler.handleFailure());
4474
+ this.finish({
4475
+ outcome: 'error',
4476
+ orderId: this.session.orderId,
4477
+ threeDSChallenged: false,
4478
+ error: toError('Wallet upsell charge failed', error),
4479
+ });
4480
+ });
4481
+ }
4482
+ async charge(paymentMethodToken, handler, retried) {
4483
+ const session = this.session;
4484
+ const payload = {
4485
+ pp_ident: this.options.priceId,
4486
+ external_id: this.options.externalId,
4487
+ client_metadata: (this.options.clientMetadata ||
4488
+ {}),
4489
+ payment_method_token: paymentMethodToken,
4490
+ session_id: session.sessionId,
4491
+ };
4492
+ const idempotencyKey = createIdempotencyKey();
4493
+ if (idempotencyKey) {
4494
+ payload.idempotency_key = idempotencyKey;
4495
+ }
4496
+ let response;
4497
+ try {
4498
+ response = await postOneClick(this.apiClient, payload);
4499
+ }
4500
+ catch (error) {
4501
+ if (!retried &&
4502
+ isApiErrorWithCode(error, WALLET_SESSION_INVALID) &&
4503
+ (await this.sameAmountSession())) {
4504
+ // Nothing was charged and the customer approved this very amount: one more try.
4505
+ return this.charge(paymentMethodToken, handler, true);
4506
+ }
4507
+ callSafely(() => handler.handleFailure());
4508
+ this.finish(this.chargeFailure(error, Boolean(idempotencyKey)));
4509
+ return;
4510
+ }
4511
+ const step = mapOneClickResponse(response);
4512
+ if (step.kind === 'result') {
4513
+ const result = step.result;
4514
+ if (result.outcome === 'succeeded' || result.outcome === 'processing') {
4515
+ callSafely(() => handler.handleSuccess());
4516
+ }
4517
+ else {
4518
+ callSafely(() => handler.handleFailure(result.failedMessageForUser || undefined));
4519
+ }
4520
+ this.finish(result);
4521
+ return;
4522
+ }
4523
+ this.startThreeDS(step.orderId || session.orderId, step.actionToken, handler);
4524
+ }
4525
+ /** A new session for the same amount the customer approved in the sheet. */
4526
+ async sameAmountSession() {
4527
+ try {
4528
+ const next = await prepareSession(this.apiClient, this.options);
4529
+ if (!next ||
4530
+ next.wallet !== this.session.wallet ||
4531
+ next.amount !== this.session.amount ||
4532
+ next.currency !== this.session.currency) {
4533
+ return false;
4534
+ }
4535
+ this.session = next;
4536
+ return true;
4537
+ }
4538
+ catch {
4539
+ return false;
4540
+ }
4541
+ }
4542
+ chargeFailure(error, keyed) {
4543
+ if (isApiErrorWithCode(error, DOUBLE_PURCHASE)) {
4544
+ return {
4545
+ outcome: 'already_purchased',
4546
+ orderId: null,
4547
+ threeDSChallenged: false,
4548
+ };
4549
+ }
4550
+ if (keyed && isRetryableOneClickError(error)) {
4551
+ // The charge may have gone through: the caller must not start a new payment.
4552
+ return {
4553
+ outcome: 'processing',
4554
+ orderId: this.session.orderId,
4555
+ threeDSChallenged: false,
4556
+ error: error,
4557
+ failedRequest: 'one_click',
4558
+ };
4559
+ }
4560
+ return {
4561
+ outcome: 'error',
4562
+ orderId: null,
4563
+ threeDSChallenged: false,
4564
+ error: error instanceof Error ? error : toError('one_click failed', error),
4565
+ failedRequest: 'one_click',
4566
+ };
4567
+ }
4568
+ // ---------- 3DS ----------
4569
+ threeDSChallenged() {
4570
+ return Boolean(this.threeDS?.challenged);
4571
+ }
4572
+ startThreeDS(orderId, actionToken, handler) {
4573
+ const intent = getPrimerTokenIntent(actionToken);
4574
+ if (!intent || !PRIMER_3DS_INTENTS.includes(intent)) {
4575
+ callSafely(() => handler.handleFailure());
4576
+ this.finish({
4577
+ outcome: 'error',
4578
+ orderId,
4579
+ threeDSChallenged: false,
4580
+ error: new PrimerError('Unsupported one-click action: the action token is not a Primer 3DS client token', { intent }),
4581
+ });
4582
+ return;
4583
+ }
4584
+ const timeoutMs = DEFAULT_THREE_DS_TIMEOUT_MS;
4585
+ const threeDS = {
4586
+ orderId,
4587
+ challenged: false,
4588
+ revealTimer: null,
4589
+ timer: null,
4590
+ showOverlay: hidePrimerOverlay(),
4591
+ };
4592
+ this.threeDS = threeDS;
4593
+ const onTimeout = () => {
4594
+ threeDS.timer = null;
4595
+ if (!threeDS.challenged) {
4596
+ // The overlay is about to be shown: the reveal restarts the timer.
4597
+ return;
4598
+ }
4599
+ this.endThreeDS('abandoned');
4600
+ this.finish({
4601
+ outcome: '3ds_abandoned',
4602
+ orderId,
4603
+ threeDSChallenged: true,
4604
+ });
4605
+ dismissPrimerOverlay();
4606
+ };
4607
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4608
+ threeDS.revealTimer = setTimeout(() => {
4609
+ threeDS.revealTimer = null;
4610
+ threeDS.challenged = true;
4611
+ threeDS.showOverlay();
4612
+ warnIfOverlayNotFound();
4613
+ callHook('onThreeDSStart', this.options.onThreeDSStart, { orderId });
4614
+ if (threeDS.timer) {
4615
+ clearTimeout(threeDS.timer);
4616
+ }
4617
+ threeDS.timer = setTimeout(onTimeout, timeoutMs);
4618
+ }, THREE_DS_OVERLAY_REVEAL_DELAY_MS);
4619
+ handler.continueWithNewClientToken(actionToken);
4620
+ }
4621
+ /** Stops the 3DS timers; reports `onThreeDSEnd` once, and only after `onThreeDSStart`. */
4622
+ endThreeDS(result) {
4623
+ const threeDS = this.threeDS;
4624
+ if (!threeDS) {
4625
+ return;
4626
+ }
4627
+ if (threeDS.timer) {
4628
+ clearTimeout(threeDS.timer);
4629
+ threeDS.timer = null;
4630
+ }
4631
+ if (threeDS.revealTimer) {
4632
+ clearTimeout(threeDS.revealTimer);
4633
+ threeDS.revealTimer = null;
4634
+ }
4635
+ threeDS.showOverlay();
4636
+ if (threeDS.challenged) {
4637
+ callHook('onThreeDSEnd', this.options.onThreeDSEnd, { result });
4638
+ }
4639
+ }
4640
+ async onResumed(generation, data, handler) {
4641
+ const threeDS = this.threeDS;
4642
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4643
+ callSafely(() => handler.handleFailure());
4644
+ return;
4645
+ }
4646
+ // The challenge is over: the timeout bounds only the challenge, never the POST.
4647
+ if (threeDS.timer) {
4648
+ clearTimeout(threeDS.timer);
4649
+ threeDS.timer = null;
4650
+ }
4651
+ if (threeDS.revealTimer) {
4652
+ clearTimeout(threeDS.revealTimer);
4653
+ threeDS.revealTimer = null;
4654
+ }
4655
+ let response;
4656
+ try {
4657
+ response = await this.apiClient.resumePaymentOnce({
4658
+ orderId: threeDS.orderId,
4659
+ resumeToken: data.resumeToken,
4660
+ });
4661
+ }
4662
+ catch (error) {
4663
+ callSafely(() => handler.handleFailure());
4664
+ this.endThreeDS('error');
4665
+ this.finish({
4666
+ outcome: 'error',
4667
+ orderId: threeDS.orderId,
4668
+ threeDSChallenged: threeDS.challenged,
4669
+ error: error,
4670
+ failedRequest: 'resume_payment',
4671
+ });
4672
+ return;
4673
+ }
4674
+ const mapped = mapResumeResponse(response, threeDS.orderId, threeDS.challenged);
4675
+ if (mapped.result.outcome === 'succeeded' ||
4676
+ mapped.result.outcome === 'processing') {
4677
+ callSafely(() => handler.handleSuccess());
4678
+ }
4679
+ else {
4680
+ callSafely(() => handler.handleFailure(mapped.result.failedMessageForUser || undefined));
4681
+ }
4682
+ this.endThreeDS(mapped.threeDS);
4683
+ this.finish(mapped.result);
4684
+ }
4685
+ onResumeError(generation, error) {
4686
+ const threeDS = this.threeDS;
4687
+ if (generation !== this.generation || !this.attemptRunning || !threeDS) {
4688
+ return;
4689
+ }
4690
+ if (isThreeDSCloseError(error)) {
4691
+ this.endThreeDS('abandoned');
4692
+ this.finish({
4693
+ outcome: '3ds_abandoned',
4694
+ orderId: threeDS.orderId,
4695
+ threeDSChallenged: threeDS.challenged,
4696
+ });
4697
+ return;
4698
+ }
4699
+ this.endThreeDS('failed');
4700
+ this.finish({
4701
+ outcome: '3ds_failed',
4702
+ orderId: threeDS.orderId,
4703
+ threeDSChallenged: threeDS.challenged,
4704
+ error: toError('3DS authentication failed', error),
4705
+ });
4706
+ }
4707
+ // ---------- result ----------
4708
+ /** Ends the running attempt with its one result; later calls for it are ignored. */
4709
+ finish(result) {
4710
+ if (!this.attemptRunning) {
4711
+ return;
4712
+ }
4713
+ this.attemptRunning = false;
4714
+ this.tokenizeStarted = false;
4715
+ this.charging = false;
4716
+ this.threeDS = null;
4717
+ oneClickInFlight.delete(this.inFlightKey);
4718
+ this.report(result);
4719
+ }
4720
+ report(result) {
4721
+ if (result.outcome !== 'cancelled') {
4722
+ this.finished = true;
4723
+ this.clearRefresh();
4724
+ this.applyDisabled();
4725
+ }
4726
+ else if (this.expiresSoon()) {
4727
+ this.refresh();
4728
+ }
4729
+ if (result.outcome === 'error' && result.error) {
4730
+ const error = result.error;
4731
+ getErrorImage(this.options.orgId, {
4732
+ baseUrl: this.options.baseUrl || defaultBaseUrl(),
4733
+ message: error.message,
4734
+ code: error.code,
4735
+ req_id: error.response?.req_id,
4736
+ });
4737
+ }
4738
+ if (!this.destroyed) {
4739
+ callHook('onResult', this.options.onResult, result);
4740
+ }
4741
+ }
4742
+ }
4743
+ function validate(container, options) {
4744
+ if (typeof HTMLElement === 'undefined' ||
4745
+ !(container instanceof HTMLElement)) {
4746
+ throw new ValidationError('container', 'must be an HTMLElement', container);
4747
+ }
4748
+ for (const field of ['orgId', 'priceId', 'externalId']) {
4749
+ if (!options?.[field]) {
4750
+ throw new ValidationError(field, 'is required', options?.[field]);
4751
+ }
4752
+ }
4753
+ if (typeof options.onResult !== 'function') {
4754
+ throw new ValidationError('onResult', 'must be a function', options.onResult);
4755
+ }
4756
+ }
4757
+ /**
4758
+ * Mounts Primer's native Apple Pay / Google Pay button for a one-click upsell. Rejects only with
4759
+ * `ValidationError`; any `mounted: false` leaves nothing in `container`.
4760
+ */
4761
+ async function mountWalletUpsell(container, options) {
4762
+ validate(container, options);
4763
+ let session;
4764
+ try {
4765
+ session = await prepareSession(WalletUpsell.apiClientFor(options), options);
4766
+ }
4767
+ catch (error) {
4768
+ return {
4769
+ mounted: false,
4770
+ reason: 'error',
4771
+ error: error instanceof Error
4772
+ ? error
4773
+ : toError('one_click_wallet_session failed', error),
4774
+ };
4775
+ }
4776
+ if (!session) {
4777
+ return { mounted: false, reason: 'not_wallet' };
4778
+ }
4779
+ const upsell = new WalletUpsell(container, options, session);
4780
+ try {
4781
+ if (!(await upsell.render())) {
4782
+ upsell.destroy();
4783
+ return {
4784
+ mounted: false,
4785
+ reason: 'wallet_unavailable',
4786
+ wallet: session.wallet,
4787
+ };
4788
+ }
4789
+ }
4790
+ catch (error) {
4791
+ upsell.destroy();
4792
+ return {
4793
+ mounted: false,
4794
+ reason: 'error',
4795
+ error: toError('Failed to mount the wallet button', error),
4796
+ };
4797
+ }
4798
+ upsell.watchVisibility();
4799
+ return {
4800
+ mounted: true,
4801
+ wallet: session.wallet,
4802
+ setDisabled: (disabled) => upsell.setDisabled(disabled),
4803
+ destroy: () => upsell.destroy(),
4804
+ };
4805
+ }
4806
+
4038
4807
  /**
4039
4808
  * @fileoverview Main entry point for @funnelfox/billing
4040
4809
  */
@@ -4044,6 +4813,7 @@ const Billing = {
4044
4813
  createClientSession: createClientSession,
4045
4814
  initMethod: initMethod,
4046
4815
  silentPurchase: silentPurchase,
4816
+ mountWalletUpsell,
4047
4817
  getAvailablePaymentMethods: getAvailablePaymentMethods,
4048
4818
  stripe: {
4049
4819
  createCardForm: createStripeCardForm,
@@ -4076,5 +4846,6 @@ exports.createCheckout = createCheckout;
4076
4846
  exports.createClientSession = createClientSession;
4077
4847
  exports.getAvailablePaymentMethods = getAvailablePaymentMethods;
4078
4848
  exports.loadStripe = loadStripe;
4849
+ exports.mountWalletUpsell = mountWalletUpsell;
4079
4850
  exports.resolveTaxDisplay = resolveTaxDisplay;
4080
4851
  exports.toPaymentFailure = toPaymentFailure;