Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,61 @@ describe('createFormSession', () => {
expect(errorOf(result)?.message).toMatch(/init blew up/);
});

it('keeps unsupported_configuration when the provider failed because it cannot run here', async () => {
const session = createFormSession(fakeAdapter(), { readyTimeoutMs: 1000 });
session.fail(
Object.assign(new Error('The card fields cannot run in this app.'), {
code: 'unsupported_configuration',
})
);
const result = await session.tokenize();
expect(result.status).toBe('error');
expect(errorOf(result)?.code).toBe('unsupported_configuration');
expect(errorOf(result)?.message).toBe(
'The card fields cannot run in this app.'
);
});

it('does not let a failure carry any other code through', async () => {
const session = createFormSession(fakeAdapter(), { readyTimeoutMs: 1000 });
session.fail(Object.assign(new Error('odd'), { code: 'session_expired' }));
const result = await session.tokenize();
expect(errorOf(result)?.code).toBe('tokenization_failed');
});

it('a save in flight when the form fails keeps its own result, and the form stays failed', async () => {
let finish: (result: TokenizeResult) => void = () => {};
const session = createFormSession(
fakeAdapter(
() =>
new Promise<TokenizeResult>((resolve) => {
finish = resolve;
})
)
);
session.attachCollector({});
const inFlight = session.tokenize();
await Promise.resolve();
expect(session.status).toBe('tokenizing');

session.fail(
Object.assign(new Error('The card form stopped.'), {
code: 'unsupported_configuration',
})
);
const unknown: TokenizeResult = {
status: 'error',
vaultType: 'vgs',
error: { code: 'unknown_outcome', message: 'cut off', type: 'api_error' },
};
finish(unknown);
expect(await inFlight).toEqual(unknown);
expect(session.status).toBe('error');
expect(errorOf(await session.tokenize())?.code).toBe(
'unsupported_configuration'
);
});

it('maps an adapter rejection to tokenization_failed and recovers status', async () => {
const session = createFormSession(
fakeAdapter(async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import { createDeferred } from './deferred';
import type { ProviderAdapter } from './ProviderAdapter';
import { errorResult, messageOf } from './results';
import type { FormStatus, TokenizeResult } from './types';
import type { FormStatus, TokenizeErrorCode, TokenizeResult } from './types';

export const DEFAULT_READY_TIMEOUT_MS = 10_000;

/*
* A provider failure that says why the provider cannot run in this app keeps its code on every later
* tokenize(): the Hyperswitch vault's card form, when its native fields cannot run here, fails with
* unsupported_configuration (providers/hyperswitch/adapter.tsx). Any other failure, such as a
* provider SDK that threw while starting, stays tokenization_failed.
*/
const KEPT_FAILURE_CODES: readonly TokenizeErrorCode[] = [
'unsupported_configuration',
];

function failureCodeOf(error: unknown): TokenizeErrorCode {
const code = (error as { code?: unknown } | null | undefined)?.code;
return (
KEPT_FAILURE_CODES.find((kept) => kept === code) ?? 'tokenization_failed'
);
}

export interface CreateFormSessionOptions {
readyTimeoutMs?: number;
}
Expand Down Expand Up @@ -60,7 +77,7 @@ export function createFormSession(
if (failure) {
return errorResult(
vaultType,
'tokenization_failed',
failureCodeOf(failure.error),
messageOf(failure.error)
);
}
Expand All @@ -74,12 +91,17 @@ export function createFormSession(
}

status = 'tokenizing';
/*
* The save keeps its own result (a token, a refusal, unknown_outcome). The form goes back to
* ready only if it did not fail while the save was in flight: a failure is final, and every
* later save refuses with it.
*/
try {
const result = await adapter.tokenize(collector, providerData);
status = 'ready';
status = failure ? 'error' : 'ready';
return result;
} catch (error) {
status = 'ready';
status = failure ? 'error' : 'ready';
return errorResult(vaultType, 'tokenization_failed', messageOf(error));
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { createRef } from 'react';
import { render, screen, waitFor } from '@testing-library/react-native';

/* The vault is an optional peer, so stand one in and record what it is handed.
The adapter types it as `any`, so only this test pins the prop names. */
const vaultProps: {
form?: Record<string, any>;
fields: Record<string, any>;
/* When set, the stand-in refuses like the real vault does where its native fields cannot run. */
refuseWith?: { code: string; message: string };
} = { fields: {} };

jest.mock(
Expand All @@ -15,6 +18,7 @@ jest.mock(
Fragment,
createElement,
forwardRef,
useEffect,
useImperativeHandle,
} = require('react');
const { Text } = require('react-native');
Expand All @@ -29,10 +33,15 @@ jest.mock(
return {
/* The adapter treats the ref as the collector, so it must resolve. */
CardForm: forwardRef(
({ children, ...rest }: Record<string, any>, ref: unknown) => {
({ children, onError, ...rest }: Record<string, any>, ref: unknown) => {
vaultProps.form = rest;
useImperativeHandle(ref, () => ({ tokenize: async () => ({}) }), []);
return createElement(Fragment, null, children);
/* The real vault reports a refusal from an effect, and draws no field. */
const refusal = vaultProps.refuseWith;
useEffect(() => {
if (refusal) onError?.(refusal);
}, [refusal, onError]);
return refusal ? null : createElement(Fragment, null, children);
}
),
CardNumberField: field('cardNumber'),
Expand Down Expand Up @@ -85,6 +94,7 @@ const session = (value: Partial<PaymentMethodsSession>) =>
beforeEach(() => {
vaultProps.form = undefined;
vaultProps.fields = {};
vaultProps.refuseWith = undefined;
registerAdapter(hyperswitchVaultAdapter);
});

Expand Down Expand Up @@ -262,3 +272,58 @@ describe('hyperswitch adapter — the environment', () => {
expect(vaultProps.form?.environment).toBe('PROD');
});
});

describe('hyperswitch adapter — a vault that cannot run in this app', () => {
const refusal = {
code: 'unsupported_configuration',
message: "This app was not built with the vault's native card fields.",
};

it('passes the refusal to onError, never reports ready, and a later save gives the same code', async () => {
vaultProps.refuseWith = refusal;
const onReady = jest.fn();
const onError = jest.fn();
const ref = createRef<any>();
render(
<SessionContext.Provider value={session({})}>
<CardForm
ref={ref}
vaultDetails={details}
onReady={onReady}
onError={onError}
>
<CardNumberField />
</CardForm>
</SessionContext.Provider>
);

await waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
const reported = onError.mock.calls[0]?.[0] as {
code?: string;
message?: string;
};
expect(reported.code).toBe('unsupported_configuration');
expect(reported.message).toBe(refusal.message);
expect(onReady).not.toHaveBeenCalled();

const result = await ref.current.tokenize();
expect(result.status).toBe('error');
expect(result.error.code).toBe('unsupported_configuration');
expect(result.error.message).toBe(refusal.message);
expect(onReady).not.toHaveBeenCalled();
});

it('still reports ready when the vault runs', async () => {
const onReady = jest.fn();
const onError = jest.fn();
render(
<SessionContext.Provider value={session({})}>
<CardForm vaultDetails={details} onReady={onReady} onError={onError}>
<CardNumberField />
</CardForm>
</SessionContext.Provider>
);
await waitFor(() => expect(onReady).toHaveBeenCalled());
expect(onError).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useEffect, useMemo, useRef } from 'react';
import { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
import { useColorScheme } from 'react-native';

import { fieldChange } from '../../core/fieldChange';
Expand Down Expand Up @@ -74,6 +74,30 @@ const Host: ProviderAdapter['Host'] = ({
const data = vaultData as HyperswitchVaultData;
const formRef = useRef<any>(null);

/*
* The vault's card fields are native only: where they cannot run (an app built without them, an
* over-the-air update onto an older build, a form that stops), the vault's CardForm draws no field
* and calls onError with unsupported_configuration. That error goes on to the merchant, and the
* form is never reported ready: its ref exists, but there is nothing to collect. The vault's form
* is a child, so its error arrives before this component's first effect decides "ready".
*/
const refused = useRef(false);
const onErrorRef = useRef(onError);
onErrorRef.current = onError;
const onVaultError = useCallback((error: any) => {
refused.current = true;
const failure = new Error(
typeof error?.message === 'string' && error.message !== ''
? error.message
: 'The Hyperswitch vault card form cannot run in this app.'
) as Error & { code?: string };
failure.code =
typeof error?.code === 'string'
? error.code
: 'unsupported_configuration';
onErrorRef.current(failure);
}, []);

const session = useContext(SessionContext);
const form = useContext(FormContext);
const locale = session?.locale ?? undefined;
Expand Down Expand Up @@ -111,13 +135,16 @@ const Host: ProviderAdapter['Host'] = ({
// );

useEffect(() => {
/* The vault said it cannot run here: its error already went out, so no "ready". */
if (refused.current) return;
if (formRef.current) onReady(formRef.current);
else onError(new Error('The Hyperswitch vault form did not mount.'));
}, [onReady, onError]);

return (
<VaultCardForm
ref={formRef}
onError={onVaultError}
// session={vaultSession}
vaultDetails={{
vaultType: 'hyperswitch',
Expand Down
Loading