From 3a598fab2fde53c2db0434882257bd2b6cc29d62 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 20 Nov 2026 04:33:24 +0530 Subject: [PATCH 1/4] feat(vault): createDetachedCardForm from the root, with every CardForm setting and update() --- .../package.json | 2 +- .../src/DetachedCardField.res | 55 ++++++++ .../src/DetachedCardHost.res | 121 ++++++++++++++++++ .../src/DetachedCardLink.res | 58 +++++++++ .../src/VaultFormHost.res | 32 +++-- .../src/createDetachedCardForm.mjs | 97 ++++++++++++++ .../src/detachedSettings.mjs | 96 ++++++++++++++ .../src/public.ts | 62 +++++++++ .../src/standalone-entry.mjs | 7 + .../test/detached.test.mjs | 96 ++++++++++++++ 10 files changed, 616 insertions(+), 10 deletions(-) create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardField.res create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardLink.res create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/detachedSettings.mjs create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/package.json b/packages/@juspay-tech/react-native-hyperswitch-vault/package.json index 39d30d02..2ec6c329 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/package.json +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/package.json @@ -56,7 +56,7 @@ "build:clean": "rescript clean && rescript && tsc -p tsconfig.build.json && rollup -c", "clean": "rescript clean", "prepack": "rescript && tsc -p tsconfig.build.json && rollup -c", - "test": "rescript && node --no-warnings --test test/logging.test.mjs" + "test": "rescript && node --no-warnings --test test/logging.test.mjs test/detached.test.mjs" }, "peerDependencies": { "react": "*", diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardField.res b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardField.res new file mode 100644 index 00000000..5273ae0b --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardField.res @@ -0,0 +1,55 @@ +/* + * One field of a detached card form, in a React root of its own. It gives its children the widget + * context a would, built over the form's shared store, so the fields of every root edit + * one card. While the Host is submitting, or the form is disabled, the fields are disabled as they + * would be in a . + */ +@react.component +let make = ( + ~store: VaultCardStore.t, + ~link: DetachedCardLink.t, + ~session: option=?, + ~sdkAuthorization: option=?, + ~vaultDetails: option=?, + ~environment: VaultFormOptions.vaultEnvironment, + ~appearance: option=?, + ~locale: option=?, + ~localisation: option=?, + ~customEndpoints: option=?, + ~disabled: option=?, + ~accessible: option=?, + ~enabledCardSchemes: option>=?, + ~cardholderName: option=?, + ~unstyled: option=?, + ~children: React.element, +) => { + let submitting = React.useSyncExternalStore( + ~subscribe=DetachedCardLink.subscribe(link, ...), + ~getSnapshot=DetachedCardLink.isSubmitting(link, ...), + ) + + let host = DetachedCardHost.useShared( + ~store, + ~link, + ~ownsFormLogs=false, + ~session, + ~sdkAuthorization, + ~vaultDetails, + ~environment, + ~appearance, + ~locale, + ~localisation, + ~customEndpoints, + ~disabled=submitting || disabled->Option.getOr(false), + ~accessible, + ~enabledCardSchemes, + ~cardholderName, + ~unstyled, + ~onReady=None, + ~onChange=None, + ) + + + children + +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res new file mode 100644 index 00000000..5eeca3cd --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res @@ -0,0 +1,121 @@ +/* + * The non-visual root of a detached card form, rendered once by the screen that owns the form. It + * holds the form's tokenizer and reports the form's state; the fields render in roots of their own + * (DetachedCardField). Unmounting it ends the form: the card is cleared and tokenize() refuses. + */ + +/* + * The provider's hook, over a store and a logger the form shares across roots. It takes + * every setting a takes, with the same defaults, so a detached form behaves as that form + * would. Only the Host root logs what belongs to the form as a whole (`ownsFormLogs`). + */ +/* + * How long the Host waits, after the last field registered, before it logs the form's settings. + * Each field is a root of its own and registers on its own, so without the wait the settings would + * be logged once per field, each time with one more field in the list. + */ +let fieldsSettleMs = 500 + +let useShared = ( + ~store: VaultCardStore.t, + ~link: DetachedCardLink.t, + ~ownsFormLogs: bool, + ~session: option, + ~sdkAuthorization: option, + ~vaultDetails: option, + ~environment: VaultFormOptions.vaultEnvironment, + ~appearance: option, + ~locale: option, + ~localisation: option, + ~customEndpoints: option, + ~disabled: bool, + ~accessible: option, + ~enabledCardSchemes: option>, + ~cardholderName: option, + ~unstyled: option, + ~onReady: option unit>, + ~onChange: option unit>, +) => + VaultFormHost.useHost( + ~store, + ~loggerFor=DetachedCardLink.loggerFor(link, ...), + ~ownsFormLogs, + ~fieldsSettleMs, + ~session=session->Option.map(VaultFormOptions.sessionToJson), + ~sdkAuthorization, + ~vaultDetails, + ~environment, + ~appearance, + ~locale, + ~localisation, + ~disabled, + ~accessible, + ~enabledCardSchemes=enabledCardSchemes->Option.getOr([]), + ~eligibility=None, + ~customEndpoints, + ~cardholderNameMode=cardholderName->Option.getOr(#collect), + ~onReady, + ~onChange, + ~unstyled=unstyled->Option.getOr(CardFieldOptions.defaultUnstyled), + ~defaultErrorDisplay=CardFieldOptions.defaultErrorDisplayComposable, + ) + +@react.component +let make = ( + ~store: VaultCardStore.t, + ~link: DetachedCardLink.t, + ~session: option=?, + ~sdkAuthorization: option=?, + ~vaultDetails: option=?, + ~environment: VaultFormOptions.vaultEnvironment, + ~appearance: option=?, + ~locale: option=?, + ~localisation: option=?, + ~customEndpoints: option=?, + ~disabled: option=?, + ~accessible: option=?, + ~enabledCardSchemes: option>=?, + ~cardholderName: option=?, + ~unstyled: option=?, + ~onReady: option unit>=?, + ~onChange: option unit>=?, +) => { + let host = useShared( + ~store, + ~link, + ~ownsFormLogs=true, + ~session, + ~sdkAuthorization, + ~vaultDetails, + ~environment, + ~appearance, + ~locale, + ~localisation, + ~customEndpoints, + ~disabled=disabled->Option.getOr(false), + ~accessible, + ~enabledCardSchemes, + ~cardholderName, + ~unstyled, + ~onReady, + ~onChange, + ) + + React.useEffectOnEveryRender(() => { + link.machinery = Some(host.machinery) + link.focusField = Some(host.focusField) + link->DetachedCardLink.setSubmitting(host.machinery.isSubmitting) + None + }) + + React.useEffect0(() => Some( + () => { + link.machinery = None + link.focusField = None + link->DetachedCardLink.setSubmitting(false) + store->VaultCardStore.dispatch(CardStateReducer.Reset) + }, + )) + + React.null +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardLink.res b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardLink.res new file mode 100644 index 00000000..d6310ed8 --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardLink.res @@ -0,0 +1,58 @@ +/* + * What a detached card form's Host shares with its Fields. Each Field sits in a React root of its + * own, so it cannot read the Host's context; it reads this instead. + * + * The card is NOT here. It lives in the VaultCardStore that the Host and every Field subscribe to. + * This holds only the Host's machinery (so the form's handle can tokenize through it), whether a + * submit is in flight (so every Field disables itself, as it would inside a ), and the + * form's one logger (so the logs of every root carry one session_id, as a 's do). + */ +type t = { + mutable machinery: option, + mutable focusField: option unit>, + mutable submitting: bool, + mutable listeners: array<(int, unit => unit)>, + mutable nextListenerId: int, + // The form's logger and the URL it was made for ("" when the form logs nowhere). + mutable logger: option<(string, VaultLogger.t)>, +} + +let make = (): t => { + machinery: None, + focusField: None, + submitting: false, + listeners: [], + nextListenerId: 0, + logger: None, +} + +let subscribe = (link: t, listener: unit => unit) => { + link.nextListenerId = link.nextListenerId + 1 + let id = link.nextListenerId + link.listeners = link.listeners->Array.concat([(id, listener)]) + () => link.listeners = link.listeners->Array.filter(((other, _)) => other !== id) +} + +let isSubmitting = (link: t, ()) => link.submitting + +let setSubmitting = (link: t, submitting: bool) => + if link.submitting !== submitting { + link.submitting = submitting + link.listeners->Array.forEach(((_, listener)) => listener()) + } + +/* + * The form's logger: made by whichever root asks first, then the same one for every root. A new + * logging URL (the form's endpoints or environment changed) gets a new logger, as it does in a + * ; the roots flush the old one as they let go of it. + */ +let loggerFor = (link: t, ~url: option, ~platform: string) => { + let key = url->Option.getOr("") + switch link.logger { + | Some((current, logger)) if current === key => logger + | _ => + let logger = VaultLogger.make(~url, ~platform) + link.logger = Some((key, logger)) + logger + } +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/VaultFormHost.res b/packages/@juspay-tech/react-native-hyperswitch-vault/src/VaultFormHost.res index cc02b019..a0292ef3 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/VaultFormHost.res +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/VaultFormHost.res @@ -23,6 +23,14 @@ type host = { let useHost = ( ~store: option=?, + // A detached form's roots each run this hook over one store. These three keep its logs one form's: + // `loggerFor` hands every root the same logger; only the Host root (`ownsFormLogs`) logs what + // belongs to the form as a whole; and `fieldsSettleMs` is how long its settings log waits after + // the last field arrived, because its fields mount in roots of their own, one after another, + // where a 's arrive in one commit. A passes none of them. + ~loggerFor: option<(~url: option, ~platform: string) => VaultLogger.t>=?, + ~ownsFormLogs: bool=true, + ~fieldsSettleMs: int=0, ~session: option, ~sdkAuthorization: option, @@ -71,17 +79,20 @@ let useHost = ( | Ready({authorization}) => authorization | Unusable(_) => "" } - let logger = React.useMemo1( - () => VaultLogger.make(~url=loggingUrl, ~platform=(ReactNative.Platform.os :> string)), - [loggingUrl], - ) + let logger = React.useMemo1(() => { + let platform = (ReactNative.Platform.os :> string) + switch loggerFor { + | Some(shared) => shared(~url=loggingUrl, ~platform) + | None => VaultLogger.make(~url=loggingUrl, ~platform) + } + }, [loggingUrl]) // A session that replaces another starts the logger afresh, as web loads its frames afresh for // each. The first session to arrive does not: what the customer did before it keeps its session_id. let lastResolvedSdkAuthorizationRef = React.useRef("") React.useEffect2(() => { if resolvedSdkAuthorization !== "" { let previous = lastResolvedSdkAuthorizationRef.current - if previous !== "" && previous !== resolvedSdkAuthorization { + if ownsFormLogs && previous !== "" && previous !== resolvedSdkAuthorization { logger->VaultLogger.startNewSession } lastResolvedSdkAuthorizationRef.current = resolvedSdkAuthorization @@ -332,13 +343,14 @@ let useHost = ( ~paymentId, ) } - if loggedSessionStatus === "consumed" || loggedSettingsRef.current === key { + if !ownsFormLogs || loggedSessionStatus === "consumed" || loggedSettingsRef.current === key { None - } else if hasFields { + } else if hasFields && fieldsSettleMs <= 0 { logSettings() None } else { - let timer = setTimeout(logSettings, 1000) + // Restarted by every change to `settings`, so a field that arrives resets the wait. + let timer = setTimeout(logSettings, hasFields ? fieldsSettleMs : 1000) Some(() => clearTimeout(timer)) } }, (settings, resolvedSdkAuthorization, logger, hasFields)) @@ -420,7 +432,9 @@ let useHost = ( // Once per logger session, as web logs it once per frame. let coBadgedLoggedInRef = React.useRef("") React.useEffect3(() => { - if controller.values.isCoBadged && coBadgedLoggedInRef.current !== logger.sessionId { + if ( + ownsFormLogs && controller.values.isCoBadged && coBadgedLoggedInRef.current !== logger.sessionId + ) { coBadgedLoggedInRef.current = logger.sessionId logUserEvent(~eventName=CARD_SCHEME_SELECTION, ~value="Card detected as co-badged") } diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs new file mode 100644 index 00000000..b3ce1965 --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs @@ -0,0 +1,97 @@ +/* + * `createDetachedCardForm(config)` — a card form whose fields are NOT its children. Each field may + * sit in a React root of its own (one native view per field, the way a hosted checkout lays them + * out), and the form still collects and tokenizes one card. + * + * const form = createDetachedCardForm({vaultDetails, environment: 'sandbox', onChange}); + * + * // once, in the screen that owns the form + * // in its own root + * // in its own root + * // in its own root + * + * const result = await form.tokenize(); + * form.update({appearance}); // every root re-renders; the card is kept + * + * WHERE THE CARD LIVES. In one VaultCardStore, created here and shared by the Host and every Field. + * The handle below never exposes it: no store, no card values, only the card-free snapshot the + * `change` event already carries. Unmounting the Host clears the store and makes tokenize() refuse. + * + * SAME FIELDS. The fields are the root entry's CardNumberField / CardExpiryField / CardCVCField / + * CardholderNameField, unchanged; `Field` only gives them the widget context a would. + * + * SAME SETTINGS. `config` takes what takes as props, with the same defaults, and + * `update()` is what a prop change is to a . The settings live in detachedSettings.mjs, + * apart from the card. + */ +import * as React from 'react'; +import { make as DetachedCardHostImpl } from './DetachedCardHost.bs.js'; +import { make as DetachedCardFieldImpl } from './DetachedCardField.bs.js'; +import { make as makeLink } from './DetachedCardLink.bs.js'; +import { make as makeStore } from './VaultCardStore.bs.js'; +import { tokenizeIncompleteFieldSet } from './VaultResult.bs.js'; +import { makeSettings } from './detachedSettings.mjs'; + +const EVENTS = ['ready', 'change']; + +const noHostMessage = + 'The card form has no Host mounted. Render before calling tokenize().'; + +export function createDetachedCardForm(config = {}) { + const store = makeStore(); + const link = makeLink(); + const settings = makeSettings(config); + const listeners = { ready: new Set(), change: new Set() }; + let latest = null; + + const announce = (event, payload) => { + if (event === 'change') latest = payload; + const configured = settings.callbacks()[event === 'ready' ? 'onReady' : 'onChange']; + if (typeof configured === 'function') configured(payload); + for (const listener of listeners[event]) listener(payload); + }; + /* Made once: a new function on every render would be a new prop on every render. */ + const onReady = (event) => announce('ready', event); + const onChange = (event) => announce('change', event); + + /* Each root subscribes for itself: roots share no parent that could pass the settings down. */ + const useSettings = () => + React.useSyncExternalStore(settings.subscribe, settings.get, settings.get); + + const Host = () => + React.createElement(DetachedCardHostImpl, { ...useSettings(), store, link, onReady, onChange }); + Host.displayName = 'DetachedCardFormHost'; + + const Field = ({ children }) => + React.createElement(DetachedCardFieldImpl, { ...useSettings(), store, link }, children); + Field.displayName = 'DetachedCardFormField'; + + return { + Host, + Field, + /* The only route to a token. Refuses, never throws, when no Host is mounted. */ + tokenize: () => + link.machinery + ? link.machinery.tokenize() + : Promise.resolve(tokenizeIncompleteFieldSet(noHostMessage)), + reset: () => { + if (link.machinery) link.machinery.reset(); + }, + focus: (field) => { + if (link.focusField) link.focusField(field); + }, + /* A prop change, for a form that has no props. Never touches the card. */ + update: (changes) => settings.update(changes), + /* The last card-free snapshot, or null before the form has emitted. */ + getState: () => latest, + on: (event, listener) => { + if (!EVENTS.includes(event)) { + throw new Error( + `createDetachedCardForm: unknown event "${event}"; expected one of ${EVENTS.join(', ')}.` + ); + } + listeners[event].add(listener); + return () => listeners[event].delete(listener); + }, + }; +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/detachedSettings.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/detachedSettings.mjs new file mode 100644 index 00000000..099b653e --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/detachedSettings.mjs @@ -0,0 +1,96 @@ +/* + * The settings of one detached card form, held outside React so that roots which share no parent + * can all read them and all hear when they change. + * + * NOT THE CARD. The card is in the form's VaultCardStore. Nothing here reads or writes it, which is + * why a setting can change (a new appearance, a new locale) without the customer losing what they + * typed. + * + * `get()` returns the SAME object until a setting really changes. React's useSyncExternalStore + * needs that: a new object on every call would re-render every root forever. + */ + +/* The settings a detached form reads. The two callbacks are kept apart: see callbacks(). */ +const SETTINGS = [ + 'session', + 'sdkAuthorization', + 'vaultDetails', + 'environment', + 'customEndpoints', + 'locale', + 'localisation', + 'appearance', + 'disabled', + 'accessible', + 'enabledCardSchemes', + 'cardholderName', + 'unstyled', +]; + +/* + * Callers pass the web's lowercase names ('sandbox') as well as the vault's ('SANDBOX'). The form + * then reads the name exactly as does (VaultConfirm.normalizeEnvironment). + */ +const environmentOf = (value) => (typeof value === 'string' ? value.toUpperCase() : 'PROD'); + +/* + * Settings are plain data, so two values that print the same ARE the same setting. A caller that + * rebuilds an equal object on every render (or parses one from JSON) therefore changes nothing. + */ +const sameValue = (a, b) => { + if (Object.is(a, b)) return true; + if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false; + try { + return JSON.stringify(a) === JSON.stringify(b); + } catch { + return false; + } +}; + +export function makeSettings(initial = {}) { + let given = { ...initial }; + const listeners = new Set(); + + const read = (previous) => { + const next = {}; + let changed = previous === null; + for (const key of SETTINGS) { + const value = key === 'environment' ? environmentOf(given[key]) : given[key]; + /* Keep the old object for an equal value, so nothing downstream sees a change. */ + if (previous !== null && sameValue(previous[key], value)) { + next[key] = previous[key]; + } else { + next[key] = value; + changed = true; + } + } + return changed ? next : previous; + }; + + let current = read(null); + + return { + /* What every root renders with. Stable until update() changes a setting. */ + get: () => current, + + /* onReady / onChange as last given. Read when an event fires, so replacing one re-renders nothing. */ + callbacks: () => ({ onReady: given.onReady, onChange: given.onChange }), + + /* + * Merges `changes` over the settings so far. A key set to `undefined` goes back to its default; + * a key left out keeps its value. Roots are told only when a setting really changed. + */ + update(changes = {}) { + given = { ...given, ...changes }; + const next = read(current); + if (next === current) return; + current = next; + for (const listener of [...listeners]) listener(); + }, + + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/public.ts b/packages/@juspay-tech/react-native-hyperswitch-vault/src/public.ts index b6e77024..80fb2366 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/public.ts +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/public.ts @@ -163,6 +163,68 @@ export declare const createCardForm: ( config?: Partial> ) => CardFormInstance; +/* + * What a detached form takes: every setting a merchant can pass, with the same defaults. + * `environment` also accepts the web's lowercase names, and is optional (PROD when left out). + */ +export type DetachedCardFormConfig = Partial< + Pick< + CardFormProps, + | 'session' + | 'sdkAuthorization' + | 'vaultDetails' + | 'customEndpoints' + | 'locale' + | 'localisation' + | 'appearance' + | 'disabled' + | 'accessible' + | 'enabledCardSchemes' + | 'cardholderName' + | 'unstyled' + | 'onReady' + | 'onChange' + > +> & { + readonly environment?: + | CardFormProps['environment'] + | 'prod' + | 'prod_eu' + | 'sandbox' + | 'integ'; +}; + +/* + * A card form whose fields are not its children: render `Host` once, and each field inside a + * `Field` in whatever React root it lives in. The handle carries no card data. + */ +export type DetachedCardFormInstance = { + readonly Host: React.ComponentType; + readonly Field: React.ComponentType<{ children: React.ReactNode }>; + + tokenize(): Promise; + reset(): void; + focus(field: VaultField): void; + + /* + * What a prop change is to a . Merges over the settings so far; a key set to + * `undefined` returns to its default. Every root re-renders, and the card is kept. + */ + update(changes: DetachedCardFormConfig): void; + + getState(): VaultCardFormChange | null; + + on(event: 'ready', listener: (event: VaultCardFormEvent) => void): () => void; + on( + event: 'change', + listener: (event: VaultCardFormChange) => void + ): () => void; +}; + +export declare const createDetachedCardForm: ( + config?: DetachedCardFormConfig +) => DetachedCardFormInstance; + export type VaultFieldStyles = fieldStyles; export type VaultCardNumberStyles = fieldStyles; export type VaultCardExpiryStyles = expiryStyles; diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/standalone-entry.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/standalone-entry.mjs index 5893f113..00e54baf 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/standalone-entry.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/standalone-entry.mjs @@ -22,6 +22,7 @@ import { make as CardExpiryFieldImpl } from './CardExpiryField.bs.js'; import { make as CardCVCFieldImpl } from './CardCVCField.bs.js'; import { make as CardholderNameFieldImpl } from './CardholderNameField.bs.js'; import { createCardForm as createCardFormImpl } from './createCardForm.mjs'; +import { createDetachedCardForm as createDetachedCardFormImpl } from './createDetachedCardForm.mjs'; export const CardForm = CardFormImpl; export const CardNumberField = CardNumberFieldImpl; @@ -37,3 +38,9 @@ export const HyperswitchVaultForm = HyperswitchVaultFormImpl; * drive it with method calls the way the web's `cardForm()` object is driven. */ export const createCardForm = createCardFormImpl; + +/* + * A card form whose fields each sit in a React root of their own (one native view per field). + * Exported from the root only: no subpath, so every React Native version's Metro resolves it. + */ +export const createDetachedCardForm = createDetachedCardFormImpl; diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs new file mode 100644 index 00000000..2d2f2284 --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs @@ -0,0 +1,96 @@ +// The detached card form's two shared pieces that hold no card: its settings and its logger. +// Runs on the ReScript output (`rescript` first). The form itself needs a React renderer and +// React Native, so it is exercised where those exist. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { makeSettings } from '../src/detachedSettings.mjs'; +import * as DetachedCardLink from '../src/DetachedCardLink.bs.js'; + +const LOG_URL = 'https://app.hyperswitch.io/api/logs/sdk'; + +test('settings: the defaults are a \'s, and the environment is read as the web spells it', () => { + assert.equal(makeSettings().get().environment, 'PROD'); + assert.equal(makeSettings({ environment: 'sandbox' }).get().environment, 'SANDBOX'); + const settings = makeSettings({ locale: 'fr', disabled: true, enabledCardSchemes: ['visa'] }).get(); + assert.equal(settings.locale, 'fr'); + assert.equal(settings.disabled, true); + assert.deepEqual(settings.enabledCardSchemes, ['visa']); + assert.equal(settings.appearance, undefined); +}); + +test('settings: the callbacks are not settings, so replacing one tells no root', () => { + const first = () => {}; + const second = () => {}; + const settings = makeSettings({ onChange: first }); + let told = 0; + settings.subscribe(() => told++); + assert.equal('onChange' in settings.get(), false); + settings.update({ onChange: second }); + assert.equal(told, 0); + assert.equal(settings.callbacks().onChange, second); +}); + +test('settings: get() is the same object until a setting really changes', () => { + const settings = makeSettings({ appearance: { variables: { colorText: '#000' } } }); + const before = settings.get(); + assert.equal(settings.get(), before); + + let told = 0; + settings.subscribe(() => told++); + settings.update({ appearance: { variables: { colorText: '#000' } } }); + assert.equal(told, 0, 'an equal appearance, rebuilt by the caller, is not a change'); + assert.equal(settings.get(), before); + + settings.update({ appearance: { variables: { colorText: '#fff' } } }); + assert.equal(told, 1); + assert.notEqual(settings.get(), before); + assert.equal(settings.get().appearance.variables.colorText, '#fff'); +}); + +test('settings: update merges, keeps what it was not given, and undefined returns a key to its default', () => { + const vaultDetails = { vaultType: 'hyperswitch', vaultData: { sdkAuthorization: 'abc' } }; + const settings = makeSettings({ vaultDetails, locale: 'fr', environment: 'sandbox' }); + settings.update({ locale: 'de' }); + assert.equal(settings.get().locale, 'de'); + assert.equal(settings.get().vaultDetails, vaultDetails, 'an untouched setting keeps its object'); + assert.equal(settings.get().environment, 'SANDBOX'); + + settings.update({ locale: undefined, environment: undefined }); + assert.equal(settings.get().locale, undefined); + assert.equal(settings.get().environment, 'PROD'); +}); + +test('settings: every subscribed root is told once per change, and not after it unsubscribes', () => { + const settings = makeSettings(); + const told = { host: 0, number: 0 }; + settings.subscribe(() => told.host++); + const leave = settings.subscribe(() => told.number++); + settings.update({ disabled: true }); + leave(); + settings.update({ disabled: false }); + assert.deepEqual(told, { host: 2, number: 1 }); +}); + +test('logger: every root of one form gets the same logger, so its logs carry one session_id', () => { + const link = DetachedCardLink.make(); + const fromHost = DetachedCardLink.loggerFor(link, LOG_URL, 'android'); + const fromField = DetachedCardLink.loggerFor(link, LOG_URL, 'android'); + assert.equal(fromField, fromHost); + assert.equal(fromField.sessionId, fromHost.sessionId); +}); + +test('logger: a new logging URL gets a new logger, and two forms never share one', () => { + const link = DetachedCardLink.make(); + const first = DetachedCardLink.loggerFor(link, LOG_URL, 'android'); + const moved = DetachedCardLink.loggerFor(link, 'https://eu.hyperswitch.io/api/logs/sdk', 'android'); + assert.notEqual(moved, first); + assert.equal(DetachedCardLink.loggerFor(link, 'https://eu.hyperswitch.io/api/logs/sdk', 'android'), moved); + + const silent = DetachedCardLink.loggerFor(link, undefined, 'android'); + assert.equal(silent.url, undefined); + assert.equal(DetachedCardLink.loggerFor(link, undefined, 'android'), silent); + + const other = DetachedCardLink.loggerFor(DetachedCardLink.make(), LOG_URL, 'android'); + assert.notEqual(other, first); +}); From a0917c3a4acf517c8d3cceaff9256331b608b5cd Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 2 Dec 2026 11:59:47 +0530 Subject: [PATCH 2/4] fix(vault): tokenize() right after update() uses the new settings, not the previous session update() changes a detached form's settings at once, but the Host reads them when React next draws it, and its session (from sdkAuthorization / vaultDetails) is worked out while it draws. So update({sdkAuthorization: fresh}) followed straight away by tokenize() ran with the previous session: an old-session request, or a wrong session_consumed refusal after the session had been replaced. (Found in review.) tokenize() now waits until the Host has committed the settings that are current when it is called (commitGate.mjs), then runs. It never waits forever: if the Host unmounts it refuses as before (no Host mounted), and if no commit comes within 5 seconds it refuses with tokenization_failed and "did not apply its new settings in time". With nothing pending it runs at once, as before. Tests: the gate on its own (waits for the current settings, follows the newest update, ends on unmount, times out instead of hanging). --- .../src/commitGate.mjs | 61 ++++++++++++ .../src/createDetachedCardForm.mjs | 43 +++++++-- .../test/detached.test.mjs | 95 ++++++++++++++++++- 3 files changed, 188 insertions(+), 11 deletions(-) create mode 100644 packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs new file mode 100644 index 00000000..2a3fda85 --- /dev/null +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs @@ -0,0 +1,61 @@ +/* + * Which settings has the detached form's Host actually drawn with? tokenize() asks this before it + * runs. + * + * WHY. `update()` changes the settings at once, but the Host only reads them when React next draws + * it, a moment later. The Host's session (from `sdkAuthorization` / `vaultDetails`) is worked out + * while it draws, so a tokenize() called right after update({sdkAuthorization: fresh}) would still + * run with the previous session: an old-session request, or a wrong `session_consumed` refusal. + * So tokenize() waits until the Host has committed the settings that are current when it is called. + * + * It never waits forever: if the Host goes away the wait ends as `closed`, and if no commit comes + * within `timeoutMs` it ends as `timeout`. Plain data and timers only, so it is tested without React. + */ +export function makeCommitGate({ timeoutMs = 5000, setTimer = setTimeout, clearTimer = clearTimeout } = {}) { + let mounted = false; + let drawn; + const waiters = new Set(); + + const settle = (waiter, outcome) => { + if (!waiters.delete(waiter)) return; + clearTimer(waiter.timer); + waiter.resolve(outcome); + }; + + return { + /* The Host committed a render made with `settings` (the settings object it read). */ + committed(settings) { + mounted = true; + drawn = settings; + for (const waiter of [...waiters]) { + if (waiter.current() === drawn) settle(waiter, 'current'); + } + }, + + /* The Host unmounted: nothing can be drawn any more. */ + closed() { + mounted = false; + drawn = undefined; + for (const waiter of [...waiters]) settle(waiter, 'closed'); + }, + + /* Whether the Host has drawn with exactly `settings`. */ + isDrawn(settings) { + return mounted && drawn === settings; + }, + + /* + * Resolves 'current' once the Host has drawn with what `current()` returns at that moment, + * 'closed' if it unmounts first (or none is mounted), 'timeout' after `timeoutMs`. + */ + whenDrawn(current) { + if (!mounted) return Promise.resolve('closed'); + if (drawn === current()) return Promise.resolve('current'); + return new Promise((resolve) => { + const waiter = { current, resolve, timer: undefined }; + waiter.timer = setTimer(() => settle(waiter, 'timeout'), timeoutMs); + waiters.add(waiter); + }); + }, + }; +} diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs index b3ce1965..75afac1e 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs @@ -23,24 +23,32 @@ * SAME SETTINGS. `config` takes what takes as props, with the same defaults, and * `update()` is what a prop change is to a . The settings live in detachedSettings.mjs, * apart from the card. + * + * UPDATE, THEN TOKENIZE. update() changes the settings at once, but the Host reads them when React + * next draws it. So tokenize() waits until the Host has drawn the settings that are current when + * it is called (commitGate.mjs): update({sdkAuthorization: fresh}) followed by tokenize() uses the + * fresh session, never the previous one. */ import * as React from 'react'; import { make as DetachedCardHostImpl } from './DetachedCardHost.bs.js'; import { make as DetachedCardFieldImpl } from './DetachedCardField.bs.js'; import { make as makeLink } from './DetachedCardLink.bs.js'; import { make as makeStore } from './VaultCardStore.bs.js'; -import { tokenizeIncompleteFieldSet } from './VaultResult.bs.js'; +import { tokenizeFailedWith, tokenizeIncompleteFieldSet } from './VaultResult.bs.js'; +import { makeCommitGate } from './commitGate.mjs'; import { makeSettings } from './detachedSettings.mjs'; const EVENTS = ['ready', 'change']; const noHostMessage = 'The card form has no Host mounted. Render before calling tokenize().'; +const notDrawnMessage = 'The card form did not apply its new settings in time. Try again.'; export function createDetachedCardForm(config = {}) { const store = makeStore(); const link = makeLink(); const settings = makeSettings(config); + const gate = makeCommitGate(); const listeners = { ready: new Set(), change: new Set() }; let latest = null; @@ -58,8 +66,18 @@ export function createDetachedCardForm(config = {}) { const useSettings = () => React.useSyncExternalStore(settings.subscribe, settings.get, settings.get); - const Host = () => - React.createElement(DetachedCardHostImpl, { ...useSettings(), store, link, onReady, onChange }); + const Host = () => { + const current = useSettings(); + /* + * After every commit, record what the Host drew with. A parent's effects run after its child's, + * so by now the link already holds the machinery of this very render. + */ + React.useEffect(() => { + gate.committed(current); + }); + React.useEffect(() => () => gate.closed(), []); + return React.createElement(DetachedCardHostImpl, { ...current, store, link, onReady, onChange }); + }; Host.displayName = 'DetachedCardFormHost'; const Field = ({ children }) => @@ -69,11 +87,20 @@ export function createDetachedCardForm(config = {}) { return { Host, Field, - /* The only route to a token. Refuses, never throws, when no Host is mounted. */ - tokenize: () => - link.machinery - ? link.machinery.tokenize() - : Promise.resolve(tokenizeIncompleteFieldSet(noHostMessage)), + /* + * The only route to a token. Refuses, never throws, when no Host is mounted. Runs with the + * settings that are current when it is called: after an update() it waits for the Host to draw + * them (never with the previous session), and refuses if that does not happen in time. + */ + tokenize: () => { + if (!link.machinery) return Promise.resolve(tokenizeIncompleteFieldSet(noHostMessage)); + if (gate.isDrawn(settings.get())) return link.machinery.tokenize(); + return gate.whenDrawn(settings.get).then((outcome) => { + if (outcome === 'current' && link.machinery) return link.machinery.tokenize(); + if (outcome === 'timeout') return tokenizeFailedWith('tokenization_failed', notDrawnMessage); + return tokenizeIncompleteFieldSet(noHostMessage); + }); + }, reset: () => { if (link.machinery) link.machinery.reset(); }, diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs index 2d2f2284..25fe86fa 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs @@ -1,9 +1,11 @@ -// The detached card form's two shared pieces that hold no card: its settings and its logger. -// Runs on the ReScript output (`rescript` first). The form itself needs a React renderer and -// React Native, so it is exercised where those exist. +// The detached card form's shared pieces that hold no card: its settings, its logger, and the +// gate that makes tokenize() wait for the Host to draw new settings. Runs on the ReScript output +// (`rescript` first). The form itself needs a React renderer and React Native, so it is exercised +// where those exist. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { makeCommitGate } from '../src/commitGate.mjs'; import { makeSettings } from '../src/detachedSettings.mjs'; import * as DetachedCardLink from '../src/DetachedCardLink.bs.js'; @@ -94,3 +96,90 @@ test('logger: a new logging URL gets a new logger, and two forms never share one const other = DetachedCardLink.loggerFor(DetachedCardLink.make(), LOG_URL, 'android'); assert.notEqual(other, first); }); + +/* A timer the test fires by hand, so no test waits on the clock. */ +const manualTimers = () => { + const due = new Map(); + let next = 0; + return { + setTimer: (fn) => { + next += 1; + due.set(next, fn); + return next; + }, + clearTimer: (id) => due.delete(id), + fireAll: () => { + for (const [id, fn] of [...due]) { + due.delete(id); + fn(); + } + }, + pending: () => due.size, + }; +}; + +test('gate: after update(), tokenize waits for the Host to draw the new settings, never the old ones', async () => { + const settings = makeSettings({ sdkAuthorization: 'old', environment: 'sandbox' }); + const timers = manualTimers(); + const gate = makeCommitGate(timers); + + gate.committed(settings.get()); + assert.equal(gate.isDrawn(settings.get()), true, 'drawn with what is current: run now'); + + settings.update({ sdkAuthorization: 'fresh' }); + assert.equal(gate.isDrawn(settings.get()), false, 'the Host has not drawn the fresh session yet'); + + let outcome = null; + const waiting = gate.whenDrawn(settings.get).then((value) => { + outcome = value; + }); + const before = settings.get(); + gate.committed({ ...before, sdkAuthorization: 'old' }); // a commit of some other render + await Promise.resolve(); + assert.equal(outcome, null, 'still waiting: that commit was not of the current settings'); + + gate.committed(settings.get()); + await waiting; + assert.equal(outcome, 'current'); + assert.equal(timers.pending(), 0, 'its timer was cleared'); +}); + +test('gate: the wait follows the newest update, not the one current when tokenize was called', async () => { + const settings = makeSettings({ sdkAuthorization: 'a' }); + const gate = makeCommitGate(manualTimers()); + gate.committed(settings.get()); + + settings.update({ sdkAuthorization: 'b' }); + const waiting = gate.whenDrawn(settings.get); + settings.update({ sdkAuthorization: 'c' }); + const drawnB = settings.get(); + gate.committed(makeSettings({ sdkAuthorization: 'b' }).get()); + gate.committed(drawnB); + assert.equal(await waiting, 'current'); +}); + +test('gate: an unmounted Host ends the wait; with none mounted it ends at once', async () => { + const gate = makeCommitGate(manualTimers()); + assert.equal(await gate.whenDrawn(() => ({})), 'closed', 'no Host was ever mounted'); + + const settings = makeSettings({ sdkAuthorization: 'x' }); + gate.committed(settings.get()); + settings.update({ sdkAuthorization: 'y' }); + const waiting = gate.whenDrawn(settings.get); + gate.closed(); + assert.equal(await waiting, 'closed'); + assert.equal(gate.isDrawn(settings.get()), false); +}); + +test('gate: a wait that sees no commit times out instead of hanging', async () => { + const timers = manualTimers(); + const gate = makeCommitGate(timers); + const settings = makeSettings({ sdkAuthorization: 'x' }); + gate.committed(settings.get()); + settings.update({ sdkAuthorization: 'y' }); + const waiting = gate.whenDrawn(settings.get); + assert.equal(timers.pending(), 1); + timers.fireAll(); + assert.equal(await waiting, 'timeout'); +}); + From 1550bc83e82cfe52ce16b68059fdc73e8a9a2a79 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 3 Dec 2026 11:19:20 +0530 Subject: [PATCH 3/4] fix(vault): a save runs only with the settings it was called with tokenize() waited for the Host to draw whichever settings were newest when it committed. So if newer settings replaced the ones a save was called with before the Host drew them (update(A), tokenize(), then update(B) at once; or, in the vault's own engine, a tokenize command carrying A followed by B's props), the save ran with B's session, one it was not called for. (Found in review.) tokenize() now keeps the settings it was called with and waits for exactly those. If newer settings replace them first, it refuses without sending anything: tokenization_failed, "The card form's settings changed before the save could run. Nothing was sent; try again." It checks once more just before it runs. Everything else is as before: no wait when the settings are already drawn, a refusal when the Host unmounts, tokenization_failed after 5 seconds with no commit. Tests: the gate test that expected the wait to follow the newest settings now expects the save to be refused when they are replaced, refused at once when already replaced, and to keep waiting through a commit of older settings. --- .../src/commitGate.mjs | 25 +++++++-- .../src/createDetachedCardForm.mjs | 20 +++++-- .../test/detached.test.mjs | 56 ++++++++++++++----- 3 files changed, 76 insertions(+), 25 deletions(-) diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs index 2a3fda85..9b1beeb9 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/commitGate.mjs @@ -8,9 +8,19 @@ * run with the previous session: an old-session request, or a wrong `session_consumed` refusal. * So tokenize() waits until the Host has committed the settings that are current when it is called. * + * A SAVE BELONGS TO THE SETTINGS IT WAS CALLED WITH. If newer settings replace them before the Host + * draws them (another update(), or, in the vault's own engine, the next props from native), the wait + * ends as `superseded` and the save is refused, unsent: it never runs with a session it was not + * called for. The merchant can save again. + * * It never waits forever: if the Host goes away the wait ends as `closed`, and if no commit comes * within `timeoutMs` it ends as `timeout`. Plain data and timers only, so it is tested without React. */ + +/* What a save refused as `superseded` says (here and for native's equivalent, native/out.mjs). */ +export const settingsChangedMessage = + "The card form's settings changed before the save could run. Nothing was sent; try again."; + export function makeCommitGate({ timeoutMs = 5000, setTimer = setTimeout, clearTimer = clearTimeout } = {}) { let mounted = false; let drawn; @@ -28,7 +38,8 @@ export function makeCommitGate({ timeoutMs = 5000, setTimer = setTimeout, clearT mounted = true; drawn = settings; for (const waiter of [...waiters]) { - if (waiter.current() === drawn) settle(waiter, 'current'); + if (drawn === waiter.wanted) settle(waiter, 'current'); + else if (waiter.current() !== waiter.wanted) settle(waiter, 'superseded'); } }, @@ -45,14 +56,16 @@ export function makeCommitGate({ timeoutMs = 5000, setTimer = setTimeout, clearT }, /* - * Resolves 'current' once the Host has drawn with what `current()` returns at that moment, - * 'closed' if it unmounts first (or none is mounted), 'timeout' after `timeoutMs`. + * Resolves 'current' once the Host has drawn with exactly `wanted`; 'superseded' if, at a commit, + * `current()` (the newest settings) is no longer `wanted`; 'closed' if the Host unmounts first + * (or none is mounted); 'timeout' after `timeoutMs`. */ - whenDrawn(current) { + whenDrawn(wanted, current = () => wanted) { if (!mounted) return Promise.resolve('closed'); - if (drawn === current()) return Promise.resolve('current'); + if (drawn === wanted) return Promise.resolve('current'); + if (current() !== wanted) return Promise.resolve('superseded'); return new Promise((resolve) => { - const waiter = { current, resolve, timer: undefined }; + const waiter = { wanted, current, resolve, timer: undefined }; waiter.timer = setTimer(() => settle(waiter, 'timeout'), timeoutMs); waiters.add(waiter); }); diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs index 75afac1e..aa72f8f7 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs @@ -35,7 +35,7 @@ import { make as DetachedCardFieldImpl } from './DetachedCardField.bs.js'; import { make as makeLink } from './DetachedCardLink.bs.js'; import { make as makeStore } from './VaultCardStore.bs.js'; import { tokenizeFailedWith, tokenizeIncompleteFieldSet } from './VaultResult.bs.js'; -import { makeCommitGate } from './commitGate.mjs'; +import { makeCommitGate, settingsChangedMessage } from './commitGate.mjs'; import { makeSettings } from './detachedSettings.mjs'; const EVENTS = ['ready', 'change']; @@ -89,14 +89,22 @@ export function createDetachedCardForm(config = {}) { Field, /* * The only route to a token. Refuses, never throws, when no Host is mounted. Runs with the - * settings that are current when it is called: after an update() it waits for the Host to draw - * them (never with the previous session), and refuses if that does not happen in time. + * settings that are current when it is called, and only with those: after an update() it waits + * for the Host to draw them (never with the previous session); if newer settings replace them + * before that, or it does not happen in time, it refuses without sending anything. */ tokenize: () => { if (!link.machinery) return Promise.resolve(tokenizeIncompleteFieldSet(noHostMessage)); - if (gate.isDrawn(settings.get())) return link.machinery.tokenize(); - return gate.whenDrawn(settings.get).then((outcome) => { - if (outcome === 'current' && link.machinery) return link.machinery.tokenize(); + const wanted = settings.get(); + if (gate.isDrawn(wanted)) return link.machinery.tokenize(); + return gate.whenDrawn(wanted, settings.get).then((outcome) => { + if (outcome === 'current' && link.machinery) { + /* Checked again: a later commit may have replaced them before this ran. */ + return gate.isDrawn(wanted) + ? link.machinery.tokenize() + : tokenizeFailedWith('tokenization_failed', settingsChangedMessage); + } + if (outcome === 'superseded') return tokenizeFailedWith('tokenization_failed', settingsChangedMessage); if (outcome === 'timeout') return tokenizeFailedWith('tokenization_failed', notDrawnMessage); return tokenizeIncompleteFieldSet(noHostMessage); }); diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs index 25fe86fa..73d7c87d 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/test/detached.test.mjs @@ -130,7 +130,7 @@ test('gate: after update(), tokenize waits for the Host to draw the new settings assert.equal(gate.isDrawn(settings.get()), false, 'the Host has not drawn the fresh session yet'); let outcome = null; - const waiting = gate.whenDrawn(settings.get).then((value) => { + const waiting = gate.whenDrawn(settings.get(), settings.get).then((value) => { outcome = value; }); const before = settings.get(); @@ -144,18 +144,48 @@ test('gate: after update(), tokenize waits for the Host to draw the new settings assert.equal(timers.pending(), 0, 'its timer was cleared'); }); -test('gate: the wait follows the newest update, not the one current when tokenize was called', async () => { - const settings = makeSettings({ sdkAuthorization: 'a' }); - const gate = makeCommitGate(manualTimers()); +test('gate: a save waits for the settings it was called with, and is refused if newer ones replace them', async () => { + const settings = makeSettings({ sdkAuthorization: 'old' }); + const timers = manualTimers(); + const gate = makeCommitGate(timers); + gate.committed(settings.get()); + + /* Called for A (update(A), or a native command carrying A). */ + settings.update({ sdkAuthorization: 'A' }); + const accepted = settings.get(); + let outcome = null; + const waiting = gate.whenDrawn(accepted, settings.get).then((value) => { + outcome = value; + }); + + /* B replaces A before the Host draws A. */ + settings.update({ sdkAuthorization: 'B' }); + await Promise.resolve(); + assert.equal(outcome, null, 'nothing decided until the Host commits'); gate.committed(settings.get()); + await waiting; + assert.equal(outcome, 'superseded', "a save called for A never runs with B's session"); + assert.equal(gate.isDrawn(accepted), false); + assert.equal(timers.pending(), 0, 'its timer was cleared'); - settings.update({ sdkAuthorization: 'b' }); - const waiting = gate.whenDrawn(settings.get); - settings.update({ sdkAuthorization: 'c' }); - const drawnB = settings.get(); - gate.committed(makeSettings({ sdkAuthorization: 'b' }).get()); - gate.committed(drawnB); - assert.equal(await waiting, 'current'); + /* Replaced before it was ever drawn, and only then asked for: refused at once. */ + settings.update({ sdkAuthorization: 'C' }); + const stale = settings.get(); + settings.update({ sdkAuthorization: 'D' }); + assert.equal(await gate.whenDrawn(stale, settings.get), 'superseded'); + + /* A commit of something older while the wanted settings are still the newest: keep waiting. */ + const wanted = settings.get(); + let later = null; + const pending = gate.whenDrawn(wanted, settings.get).then((value) => { + later = value; + }); + gate.committed(stale); + await Promise.resolve(); + assert.equal(later, null); + gate.committed(wanted); + await pending; + assert.equal(later, 'current'); }); test('gate: an unmounted Host ends the wait; with none mounted it ends at once', async () => { @@ -165,7 +195,7 @@ test('gate: an unmounted Host ends the wait; with none mounted it ends at once', const settings = makeSettings({ sdkAuthorization: 'x' }); gate.committed(settings.get()); settings.update({ sdkAuthorization: 'y' }); - const waiting = gate.whenDrawn(settings.get); + const waiting = gate.whenDrawn(settings.get(), settings.get); gate.closed(); assert.equal(await waiting, 'closed'); assert.equal(gate.isDrawn(settings.get()), false); @@ -177,7 +207,7 @@ test('gate: a wait that sees no commit times out instead of hanging', async () = const settings = makeSettings({ sdkAuthorization: 'x' }); gate.committed(settings.get()); settings.update({ sdkAuthorization: 'y' }); - const waiting = gate.whenDrawn(settings.get); + const waiting = gate.whenDrawn(settings.get(), settings.get); assert.equal(timers.pending(), 1); timers.fireAll(); assert.equal(await waiting, 'timeout'); From 440500d7ba76146538e98b05c0fb165528a83f8e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 3 Dec 2026 12:02:43 +0530 Subject: [PATCH 4/4] docs(vault): one Host per detached form, and getState() is null once it unmounts Review follow-up. A detached form has exactly one Host: every Host points the form at its own tokenizer, with its own guard against a second submit, and the first to unmount clears the card under any other. The rule is now stated where the code is (createDetachedCardForm.mjs, as createCardForm.mjs states its own, and DetachedCardHost.res), with what unmounting the Host means: the card is cleared, tokenize() refuses, and no final change is sent. getState() now returns null once the Host unmounts, instead of the last snapshot of a card that is gone. The useShared comment in DetachedCardHost.res moves back above useShared. --- .../src/DetachedCardHost.res | 21 +++++++++++++------ .../src/createDetachedCardForm.mjs | 18 +++++++++++++++- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res index 5eeca3cd..5c2cdb6b 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/DetachedCardHost.res @@ -1,14 +1,18 @@ /* * The non-visual root of a detached card form, rendered once by the screen that owns the form. It * holds the form's tokenizer and reports the form's state; the fields render in roots of their own - * (DetachedCardField). Unmounting it ends the form: the card is cleared and tokenize() refuses. + * (DetachedCardField). + * + * ONE HOST PER FORM. Every render of a Host points the form's link at that Host's tokenizer, and + * its cleanup empties the link and resets the shared store. A second Host of the same form would + * point the link at its own tokenizer (with its own guard against a second submit), and whichever + * unmounted first would clear the card under the other. So a form has exactly one Host + * (createDetachedCardForm.mjs says the same to its callers). + * + * Unmounting the Host ends the form: the card is cleared, tokenize() refuses, and no final `change` + * is sent. */ -/* - * The provider's hook, over a store and a logger the form shares across roots. It takes - * every setting a takes, with the same defaults, so a detached form behaves as that form - * would. Only the Host root logs what belongs to the form as a whole (`ownsFormLogs`). - */ /* * How long the Host waits, after the last field registered, before it logs the form's settings. * Each field is a root of its own and registers on its own, so without the wait the settings would @@ -16,6 +20,11 @@ */ let fieldsSettleMs = 500 +/* + * The provider's hook, over a store and a logger the form shares across roots. It takes + * every setting a takes, with the same defaults, so a detached form behaves as that form + * would. Only the Host root logs what belongs to the form as a whole (`ownsFormLogs`). + */ let useShared = ( ~store: VaultCardStore.t, ~link: DetachedCardLink.t, diff --git a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs index aa72f8f7..eee1c61f 100644 --- a/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs +++ b/packages/@juspay-tech/react-native-hyperswitch-vault/src/createDetachedCardForm.mjs @@ -13,6 +13,15 @@ * const result = await form.tokenize(); * form.update({appearance}); // every root re-renders; the card is kept * + * ONE HOST PER FORM. Render `form.Host` exactly once for each form. Every Host points the form at + * its own tokenizer, with its own guard against a second submit, and the first Host to unmount + * clears the card under any other, so two Hosts of one form would give one card two tokenizers. + * Create one form for each Host. + * + * UNMOUNTING THE HOST ENDS THE FORM. The card is cleared, tokenize() refuses (no Host mounted), no + * final `change` is sent, and getState() returns null until a Host is mounted again and the form + * emits. + * * WHERE THE CARD LIVES. In one VaultCardStore, created here and shared by the Host and every Field. * The handle below never exposes it: no store, no card values, only the card-free snapshot the * `change` event already carries. Unmounting the Host clears the store and makes tokenize() refuse. @@ -75,7 +84,14 @@ export function createDetachedCardForm(config = {}) { React.useEffect(() => { gate.committed(current); }); - React.useEffect(() => () => gate.closed(), []); + React.useEffect( + () => () => { + gate.closed(); + /* The form has ended: no snapshot of a card that is gone. */ + latest = null; + }, + [] + ); return React.createElement(DetachedCardHostImpl, { ...current, store, link, onReady, onChange }); }; Host.displayName = 'DetachedCardFormHost';