Skip to content

PoC HWB #2298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: canary
Choose a base branch
from
Draft

PoC HWB #2298

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
95 changes: 95 additions & 0 deletions core/app/[locale]/(default)/cart/page-data.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client';

import { getSessionCustomerAccessToken } from '~/auth';
import { client } from '~/client';
import { FragmentOf, graphql, VariablesOf } from '~/client/graphql';
import { getShippingZones } from '~/client/management/get-shipping-zones';
import { TAGS } from '~/client/tags';
import { getPreferredCurrencyCode } from '~/lib/currency';

export const PhysicalItemFragment = graphql(`
fragment PhysicalItemFragment on CartPhysicalItem {
@@ -262,6 +265,98 @@ export const getCart = async (variables: Variables) => {
return data;
};

const PaymentWalletsQuery = graphql(`
query PaymentWalletsQuery($filters: PaymentWalletsFilterInput) {
site {
paymentWallets(filter: $filters) {
edges {
node {
entityId
}
}
}
}
}
`);

type PaymentWalletsVariables = VariablesOf<typeof PaymentWalletsQuery>;

export const getPaymentWallets = async (variables: PaymentWalletsVariables) => {
const customerAccessToken = await getSessionCustomerAccessToken();

const { data } = await client.fetch({
document: PaymentWalletsQuery,
customerAccessToken,
fetchOptions: { cache: 'no-store' },
variables,
});

return removeEdgesAndNodes(data.site.paymentWallets).map(({ entityId }) => entityId);
};

const PaymentWalletWithInitializationDataQuery = graphql(`
query PaymentWalletWithInitializationDataQuery($entityId: String!, $cartId: String!) {
site {
paymentWalletWithInitializationData(
filter: { paymentWalletEntityId: $entityId, cartEntityId: $cartId }
) {
clientToken
initializationData
}
}
}
`);

export const getPaymentWalletWithInitializationData = async (entityId: string, cartId: string) => {
const { data } = await client.fetch({
document: PaymentWalletWithInitializationDataQuery,
variables: {
entityId,
cartId,
},
customerAccessToken: await getSessionCustomerAccessToken(),
fetchOptions: { cache: 'no-store' },
});

return data.site.paymentWalletWithInitializationData;
};

const CurrencyQuery = graphql(`
query Currency($currencyCode: currencyCode!) {
site {
currency(currencyCode: $currencyCode) {
display {
decimalPlaces
symbol
}
name
code
}
}
}
`);

export const getCurrencyData = async (currencyCode?: string) => {
const code = await getPreferredCurrencyCode(currencyCode);

if (!code) {
throw new Error('Could not get currency code');
}

const customerAccessToken = await getSessionCustomerAccessToken();

const { data } = await client.fetch({
document: CurrencyQuery,
fetchOptions: { cache: 'no-store' },
variables: {
currencyCode: code,
},
customerAccessToken,
});

return data.site.currency;
};

export const getShippingCountries = async (geography: FragmentOf<typeof GeographyFragment>) => {
const hasAccessToken = Boolean(process.env.BIGCOMMERCE_ACCESS_TOKEN);
const shippingZones = hasAccessToken ? await getShippingZones() : [];
49 changes: 48 additions & 1 deletion core/app/[locale]/(default)/cart/page.tsx
Original file line number Diff line number Diff line change
@@ -12,7 +12,13 @@ import { updateCouponCode } from './_actions/update-coupon-code';
import { updateLineItem } from './_actions/update-line-item';
import { updateShippingInfo } from './_actions/update-shipping-info';
import { CartViewed } from './_components/cart-viewed';
import { getCart, getShippingCountries } from './page-data';
import {
getCart,
getCurrencyData,
getPaymentWallets,
getPaymentWalletWithInitializationData,
getShippingCountries,
} from './page-data';

interface Props {
params: Promise<{ locale: string }>;
@@ -28,6 +34,36 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
};
}

const createWalletButtonsInitOptions = async (
walletButtons: string[],
cart: {
entityId: string;
currencyCode: string;
},
) => {
const currencyData = await getCurrencyData(cart.currencyCode);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this request can be made concurrently, as the requests below don't depend on the result of this request.


return Streamable.all(
walletButtons.map(async (entityId) => {
const initData = await getPaymentWalletWithInitializationData(entityId, cart.entityId);
const methodId = entityId.split('.').join('');

return {
methodId,
containerId: `${methodId}-button`,
[methodId]: {
cartId: cart.entityId,
currency: {
code: currencyData?.code,
decimalPlaces: currencyData?.display.decimalPlaces,
},
...initData,
},
};
}),
);
};

const getAnalyticsData = async (cartId: string) => {
const data = await getCart({ cartId });

@@ -88,6 +124,16 @@ export default async function Cart({ params }: Props) {
);
}

const walletButtons = await getPaymentWallets({
filters: {
cartEntityId: cartId,
},
});

const walletButtonsInitOptions = Streamable.from(() =>
createWalletButtonsInitOptions(walletButtons, cart),
);

const lineItems = [...cart.lineItems.physicalItems, ...cart.lineItems.digitalItems];

const formattedLineItems = lineItems.map((item) => ({
@@ -277,6 +323,7 @@ export default async function Cart({ params }: Props) {
}}
summaryTitle={t('CheckoutSummary.title')}
title={t('title')}
walletButtonsInitOptions={walletButtonsInitOptions}
/>
</CartAnalyticsProvider>
<CartViewed
282 changes: 282 additions & 0 deletions core/app/api/wallets/graphql/route.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,282 @@
import { print } from 'graphql';
import { graphql as gql, HttpResponse } from 'msw';
import { NextRequest } from 'next/server';
import { beforeEach, describe, expect, test } from 'vitest';

import { graphql } from '~/client/graphql';
import { server } from '~/msw.server';

import { POST } from './route';

// Mock the API requests
beforeEach(() => {
server.use(
gql.query('PaymentWalletWithInitializationDataQuery', () => {
return HttpResponse.json({ data: { site: { paymentWalletWithInitializationData: null } } });
}),
gql.mutation('CreatePaymentWalletIntentMutation', () => {
return HttpResponse.json({
data: {
payment: {
paymentWallet: {
createPaymentWalletIntent: {
paymentWalletIntentData: {
__typename: 'PayPalCommercePaymentWalletIntentData',
orderId: '123',
approvalUrl: 'https://example.com/approval',
initializationEntityId: '456',
},
errors: [],
},
},
},
},
});
}),
);
});

describe('query validation', () => {
test('route handler with valid query', async () => {
const query = graphql(`
query PaymentWalletWithInitializationDataQuery(
$paymentWalletEntityId: String!
$cartEntityId: String
) {
site {
paymentWalletWithInitializationData(
filter: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId }
) {
initializationData
}
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(query),
variables: JSON.stringify({
paymentWalletEntityId: '123',
cartEntityId: '456',
}),
}),
});

const response = await POST(request);
const data: unknown = await response.json();

expect(data).toMatchObject({ site: { paymentWalletWithInitializationData: null } });
});

test('route handler with invalid query name', async () => {
const query = graphql(`
query FooBar($paymentWalletEntityId: String!, $cartEntityId: String) {
site {
paymentWalletWithInitializationData(
filter: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId }
) {
initializationData
}
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(query),
variables: JSON.stringify({
paymentWalletEntityId: '123',
cartEntityId: '456',
}),
}),
});

const response = await POST(request);
const text = await response.text();

expect(response.status).toBe(403);
expect(text).toBe('Operation not allowed');
});

test('route handler with invalid query data', async () => {
const query = graphql(`
query PaymentWalletWithInitializationDataQuery {
site {
settings {
storeName
}
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(query),
}),
});

const response = await POST(request);
const text = await response.text();

expect(response.status).toBe(400);
expect(text).toBe('Query is invalid');
});
});

describe('mutation validation', () => {
test('route handler with valid mutation', async () => {
const mutation = graphql(`
mutation CreatePaymentWalletIntentMutation(
$paymentWalletEntityId: String!
$cartEntityId: String!
) {
payment {
paymentWallet {
createPaymentWalletIntent(
input: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId }
) {
paymentWalletIntentData {
__typename
... on PayPalCommercePaymentWalletIntentData {
orderId
approvalUrl
initializationEntityId
}
}
errors {
__typename
... on CreatePaymentWalletIntentGenericError {
message
}
... on Error {
message
}
}
}
}
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(mutation),
variables: JSON.stringify({
paymentWalletEntityId: '123',
cartEntityId: '456',
}),
}),
});

const response = await POST(request);
const data: unknown = await response.json();

expect(data).toMatchObject({
payment: {
paymentWallet: {
createPaymentWalletIntent: {
errors: [],
paymentWalletIntentData: {
__typename: 'PayPalCommercePaymentWalletIntentData',
approvalUrl: 'https://example.com/approval',
initializationEntityId: '456',
orderId: '123',
},
},
},
},
});
});

test('route handler with invalid mutation name', async () => {
const mutation = graphql(`
mutation FooBar($paymentWalletEntityId: String!, $cartEntityId: String!) {
payment {
paymentWallet {
createPaymentWalletIntent(
input: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId }
) {
paymentWalletIntentData {
__typename
... on PayPalCommercePaymentWalletIntentData {
orderId
approvalUrl
initializationEntityId
}
}
errors {
__typename
... on CreatePaymentWalletIntentGenericError {
message
}
... on Error {
message
}
}
}
}
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(mutation),
variables: JSON.stringify({
paymentWalletEntityId: '123',
cartEntityId: '456',
}),
}),
});

const response = await POST(request);
const text = await response.text();

expect(response.status).toBe(403);
expect(text).toBe('Operation not allowed');
});

test('route handler with invalid mutation data', async () => {
const query = graphql(`
mutation CreatePaymentWalletIntentMutation {
logout {
result
}
}
`);

const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: print(query),
}),
});

const response = await POST(request);
const text = await response.text();

expect(response.status).toBe(400);
expect(text).toBe('Query is invalid');
});
});

test('route handler with invalid operation', async () => {
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', {
method: 'POST',
body: JSON.stringify({
query: 'fragment Foo on Bar { baz }',
}),
});

const response = await POST(request);
const text = await response.text();

expect(response.status).toBe(400);
expect(text).toBe('No operation found');
});
143 changes: 143 additions & 0 deletions core/app/api/wallets/graphql/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { OperationDefinitionNode, parse, SelectionNode } from 'graphql';
import { NextRequest } from 'next/server';
import { z } from 'zod';

import { client } from '~/client';
import { graphql } from '~/client/graphql';

const ENABLE_LIST = [
{
name: 'PaymentWalletWithInitializationDataQuery',

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned earlier (#2298 (comment)), I think we should not enforce specific operation names. Otherwise, the exact operation names become a part of the API contract and we're not free to change in the future. Also, ideally I want to move the filtering logic out of Catalyst to the API layer so the clients won't be coupled to a specific version of Catalyst.

type: 'query',
allowedFields: {
site: {
paymentWalletWithInitializationData: true, // allow any subfields of paymentWallets
},
},
},
{
name: 'CreatePaymentWalletIntentMutation',
type: 'mutation',
allowedFields: {
payment: {
paymentWallet: {
createPaymentWalletIntent: {
paymentWalletIntentData: true,
errors: true,
},
},
},
},
},
{
name: 'CheckoutRedirectMutation',
type: 'mutation',
allowedFields: {
cart: {
createCartRedirectUrls: true,
},
},
},
{
name: 'AddCheckoutBillingAddressMutation',
type: 'mutation',
allowedFields: {
checkout: {
billingAddress: true,
},
},
},
{
name: 'UpdateCheckoutBillingAddressMutation',
type: 'mutation',
allowedFields: {
checkout: {
billingAddress: true,
},
},
},
];

export const POST = async (request: NextRequest) => {
const body: unknown = await request.json();
const { document, variables } = z
.object({ document: z.string(), variables: z.string().optional() })
.parse(body);

const ast = parse(document, { noLocation: true });

// Validate operation structure
const operation = ast.definitions.find(
(definition): definition is OperationDefinitionNode =>
definition.kind === 'OperationDefinition',
);

if (!operation) return new Response('No operation found', { status: 400 });

const config = ENABLE_LIST.find(
(entry) => entry.name === operation.name?.value && entry.type === operation.operation,
);

if (!config) return new Response('Operation not allowed', { status: 403 });

try {
assertFieldsAllowed(operation.selectionSet.selections, config.allowedFields);
} catch {
return new Response('Query is invalid', { status: 400 });
}

const response = await client.fetch({
document: graphql(document),
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
variables: variables ? JSON.parse(variables) : undefined,
errorPolicy: 'ignore',
});

return new Response(JSON.stringify(response), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
};

interface Allowed {
[key: string]: Allowed | boolean | null | undefined;
}

function assertFieldsAllowed(
selections: readonly SelectionNode[],
allowed: Allowed,
path: string[] = ['site'],
): asserts selections is readonly SelectionNode[] {
selections.forEach((selection) => {
if (selection.kind !== 'Field') return;

const fieldName = selection.name.value;
const currentPath = [...path, fieldName];

if (!(fieldName in allowed)) {
throw new Error(`Disallowed field: ${currentPath.join('.')}`);
}

const allowedValue = allowed[fieldName];

if (allowedValue === true) {
// All descendants allowed
return;
}

if (typeof allowedValue === 'object' && allowedValue !== null) {
if (!selection.selectionSet) {
throw new Error(`Expected subfields for: ${currentPath.join('.')}`);
}

assertFieldsAllowed(selection.selectionSet.selections, allowedValue, currentPath);

return;
}

if (typeof allowedValue !== 'object' && selection.selectionSet) {
throw new Error(`Field ${currentPath.join('.')} does not allow subfields`);
}
// If allowedValue is falsy and no selectionSet, it's fine (already checked above)
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use client';

import { useEffect, useRef } from 'react';

import { Stream, Streamable, useStreamable } from '@/vibes/soul/lib/streamable';
import { WalletButtonsInitializer } from '~/lib/wallet-buttons';
import { InitializeButtonProps } from '~/lib/wallet-buttons/types';

export const ClientWalletButtons = ({
walletButtonsInitOptions,
cartId,
}: {
walletButtonsInitOptions: Streamable<InitializeButtonProps[]>;
cartId: string;
}) => {
const isMountedRef = useRef(false);
const initButtonProps = useStreamable(walletButtonsInitOptions);

useEffect(() => {
if (!isMountedRef.current && initButtonProps.length) {
isMountedRef.current = true;

const initWalletButtons = async () => {
await new WalletButtonsInitializer().initialize(initButtonProps);
};

void initWalletButtons();
}
}, [cartId, initButtonProps]);

return (
<Stream fallback={null} value={walletButtonsInitOptions}>
{(buttonOptions) => (
<div style={{ display: 'flex', alignItems: 'end', flexDirection: 'column' }}>
{buttonOptions.map((button) =>
button.containerId ? <div id={button.containerId} key={button.containerId} /> : null,
)}
</div>
)}
</Stream>
);
};
4 changes: 2 additions & 2 deletions core/lib/currency.ts
Original file line number Diff line number Diff line change
@@ -5,9 +5,9 @@ import { cookies } from 'next/headers';
import type { CurrencyCode } from '~/components/header/fragment';
import { CurrencyCodeSchema } from '~/components/header/schema';

export async function getPreferredCurrencyCode(): Promise<CurrencyCode | undefined> {
export async function getPreferredCurrencyCode(code?: string): Promise<CurrencyCode | undefined> {
const cookieStore = await cookies();
const currencyCode = cookieStore.get('currencyCode')?.value;
const currencyCode = cookieStore.get('currencyCode')?.value || code;

if (!currencyCode) {
return undefined;
9 changes: 9 additions & 0 deletions core/lib/wallet-buttons/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export class InitializationError extends Error {
constructor() {
super(
'Unable to initialize the checkout button because the required script has not been loaded yet.',
);

this.name = 'InitializationError';
}
}
53 changes: 53 additions & 0 deletions core/lib/wallet-buttons/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { InitializationError } from './error';
import { InitializeButtonProps } from './types';

export class WalletButtonsInitializer {
private origin = window.location.origin;
private checkoutSdkUrl = `${this.origin}/v1/loader.js`;

async initialize(
walletButtonsInitOptions: InitializeButtonProps[],
): Promise<InitializeButtonProps[]> {
await this.initializeCheckoutKitLoader();

const checkoutButtonInitializer = await this.initCheckoutButtonInitializer();

return walletButtonsInitOptions.map((buttonOption) => {
checkoutButtonInitializer.initializeWalletButton(buttonOption);

return buttonOption;
});
}

private async initializeCheckoutKitLoader(): Promise<void> {
if (window.checkoutKitLoader) {
return;
}

await new Promise((resolve, reject) => {
const script = document.createElement('script');

script.type = 'text/javascript';
script.defer = true;
script.src = this.checkoutSdkUrl;

script.onload = resolve;
script.onerror = reject;
script.onabort = reject;

document.body.append(script);
});
}

private async initCheckoutButtonInitializer() {
if (!window.checkoutKitLoader) {
throw new InitializationError();
}

const checkoutButtonModule = await window.checkoutKitLoader.load('wallet-button');

return checkoutButtonModule.createWalletButtonInitializer({
graphQLEndpoint: 'api/wallets/graphql',
});
}
}
25 changes: 25 additions & 0 deletions core/lib/wallet-buttons/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
declare global {
interface Window {
checkoutKitLoader?: CheckoutKitLoader;
}
}

interface CheckoutKitLoader {
load(moduleName: string): Promise<CheckoutKitModule>;
}

interface CheckoutKitModule {
createWalletButtonInitializer(options: {
graphQLEndpoint: string;
}): CheckoutHeadlessButtonInitializer;
}

interface CheckoutHeadlessButtonInitializer {
initializeWalletButton(option: InitializeButtonProps): void;
}

export interface InitializeButtonProps {
[key: string]: unknown;
containerId: string;
methodId: string;
}
3 changes: 3 additions & 0 deletions core/msw.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { setupServer } from 'msw/node';

export const server = setupServer();
9 changes: 7 additions & 2 deletions core/package.json
Original file line number Diff line number Diff line change
@@ -10,7 +10,8 @@
"build:analyze": "ANALYZE=true npm run build",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest"
},
"dependencies": {
"@bigcommerce/catalyst-client": "workspace:^",
@@ -90,11 +91,15 @@
"dotenv-cli": "^8.0.0",
"eslint": "^8.57.1",
"eslint-config-next": "15.2.3",
"msw": "^2.7.4",
"postcss": "^8.5.3",
"prettier": "^3.5.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"tailwindcss": "^4.1.4",
"tailwindcss-animate": "1.0.7",
"typescript": "^5.8.3"
"typescript": "^5.8.3",
"vite": "^6.3.5",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.1.1"
}
}
15 changes: 15 additions & 0 deletions core/vibes/soul/sections/cart/client.tsx
Original file line number Diff line number Diff line change
@@ -13,11 +13,14 @@ import {
} from 'react';
import { useFormStatus } from 'react-dom';

import { Streamable } from '@/vibes/soul/lib/streamable';
import { Button } from '@/vibes/soul/primitives/button';
import { toast } from '@/vibes/soul/primitives/toaster';
import { StickySidebarLayout } from '@/vibes/soul/sections/sticky-sidebar-layout';
import { ClientWalletButtons } from 'components/wallet-buttons/_components/client-wallet-buttons';
import { useEvents } from '~/components/analytics/events';
import { Image } from '~/components/image';
import { InitializeButtonProps } from '~/lib/wallet-buttons/types';

import { CouponCodeForm, CouponCodeFormState } from './coupon-code-form';
import { cartLineItemActionFormDataSchema } from './schema';
@@ -125,6 +128,8 @@ export interface CartProps<LineItem extends CartLineItem> {
decrementLineItemLabel?: string;
incrementLineItemLabel?: string;
cart: Cart<LineItem>;
walletButtonsInitOptions?: Streamable<InitializeButtonProps[]>;
cartId: string;
couponCode?: CouponCode;
shipping?: Shipping;
}
@@ -169,6 +174,8 @@ export function CartClient<LineItem extends CartLineItem>({
deleteLineItemLabel,
lineItemAction,
checkoutAction,
walletButtonsInitOptions,
cartId,
checkoutLabel = 'Checkout',
emptyState = defaultEmptyState,
summaryTitle,
@@ -271,6 +278,14 @@ export function CartClient<LineItem extends CartLineItem>({
{checkoutLabel}
<ArrowRight size={20} strokeWidth={1} />
</CheckoutButton>
{walletButtonsInitOptions && (
<div className="mt-4">
<ClientWalletButtons
cartId={cartId}
walletButtonsInitOptions={walletButtonsInitOptions}
/>
</div>
)}
</div>
}
sidebarPosition="after"
13 changes: 13 additions & 0 deletions core/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { loadEnv } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';

export default defineConfig(({ mode }) => ({
plugins: [tsconfigPaths()],
test: {
environment: 'node',
env: loadEnv(mode, process.cwd(), ''),
exclude: ['**/node_modules/**', '**/dist/**', '**/tests/**'],
setupFiles: ['./vitest.setup.ts'],
},
}));
7 changes: 7 additions & 0 deletions core/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { afterAll, afterEach, beforeAll } from 'vitest';

import { server } from './msw.server';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
546 changes: 310 additions & 236 deletions pnpm-lock.yaml

Large diffs are not rendered by default.