Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
3e76c0b
fix(commerce): carry shopper customization details through add-to-cart
ajaynes-godaddy Nov 13, 2026
cc8b6c6
chore: add changeset for cart customization fields
ajaynes-godaddy Nov 13, 2026
454ab95
fix(commerce-storefront): show selected add-ons in the cart drawer
ajaynes-godaddy Nov 14, 2026
b014094
fix(commerce-server): validate cart customization before creating the…
ajaynes-godaddy Nov 14, 2026
fcde81e
fix(commerce-server): reject malformed cart item shapes with 400 inst…
ajaynes-godaddy Nov 17, 2026
369d84f
fix(commerce-server): force metafield type to JSON server-side
ajaynes-godaddy Nov 17, 2026
a9e6460
fix(commerce-storefront): show addon surcharges and drop blank addon …
ajaynes-godaddy Nov 17, 2026
21697dc
Merge branch 'main' into airobuild-9325/widen-cart-contract
ajaynes-godaddy Nov 19, 2026
f4256d4
fix(commerce-server): map order-api BAD_USER_INPUT to 400, not 502
ajaynes-godaddy Nov 19, 2026
8a6552e
docs(commerce-server): document order-api's same-SKU merge limitation
ajaynes-godaddy Nov 19, 2026
b52c9b8
fix(commerce-storefront): stop addItem from forwarding the whole call…
ajaynes-godaddy Nov 19, 2026
c43a612
fix(commerce-server): add a single parseCartItemInput for both cart r…
ajaynes-godaddy Nov 19, 2026
2d84c4a
fix(commerce-server): scope BAD_USER_INPUT mapping to the add-item ro…
ajaynes-godaddy Nov 19, 2026
6888f28
fix(commerce-server): allowlist details/metafields fields and drop th…
ajaynes-godaddy Nov 19, 2026
3c95afb
fix(commerce): drop metafields from the browser-facing cart shape
ajaynes-godaddy Nov 19, 2026
5d5a10d
fix(commerce-storefront): route the addon surcharge through the messa…
ajaynes-godaddy Nov 19, 2026
c8909c7
docs(commerce-storefront): document the details/metafields contract o…
ajaynes-godaddy Nov 19, 2026
760c747
docs(commerce-storefront): clarify productAssetUrl wording, cap the s…
ajaynes-godaddy Nov 19, 2026
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
6 changes: 6 additions & 0 deletions .changeset/cart-customization-details.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@godaddy/gd-commerce-server": patch
"@godaddy/gd-commerce-storefront": patch
---

Carry optional `details` (`productAssetUrl`, `selectedAddons`) and `metafields` through every add-to-cart call, so a shopper's product customization reaches checkout and the order instead of staying client-side only. Existing calls without these fields behave exactly as before.
204 changes: 203 additions & 1 deletion packages/commerce-server/src/lib/commerce/order-subgraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* - Money values are integers in the currency's smallest unit (cents for USD).
*/

import { InvalidRequestError } from './errors';
import type { Money } from './gql';

export interface OrderStorefrontEndpointInput {
Expand Down Expand Up @@ -190,6 +191,26 @@ export interface CreateDraftLineItemInput {
details?: LineItemDetailsInput;
}

// Distinct from `LineItemDetailsInput`: the GraphQL `AddLineItemInput.details.selectedAddons`
// field takes `{ optionId, values: [{ inputValue | optionValueId }] }` — the catalog-option
// *input* shape — not the `{ attribute, sku, values: [{ name, costAdjustment }] }` *output*
// shape a line item returns once built.
export interface AddLineItemSelectedAddonInput {
optionId: string;
values: Array<{ inputValue: string }>;
}

export interface AddLineItemDetailsInput {
productAssetUrl?: string;
selectedAddons?: AddLineItemSelectedAddonInput[];
}

export interface AddLineItemMetafieldInput {
key: string;
value: string;
type: 'JSON';
}

export interface AddLineItemBySkuIdInput {
orderId: string;
skuId: string;
Expand All @@ -198,7 +219,8 @@ export interface AddLineItemBySkuIdInput {
fulfillmentMode?: string;
status?: string;
type?: string;
details?: LineItemDetailsInput;
details?: AddLineItemDetailsInput;
metafields?: AddLineItemMetafieldInput[];
}

export interface UpdateLineItemByIdInput {
Expand Down Expand Up @@ -275,10 +297,178 @@ export interface EmptyCartOrderInput {
currencyCode?: string;
}

export const PRODUCT_ASSET_URL_MAX_LENGTH = 2048;
export const SELECTED_ADDON_VALUE_MAX_LENGTH = 500;
export const MAX_SELECTED_ADDONS = 20;
export const MAX_METAFIELDS = 10;
export const METAFIELD_VALUE_MAX_LENGTH = 2000;

// JSON is the only metafield type the storefront's add-to-cart surface supports — no `type`
// field here, so a client can't request a different one.
export interface AddToCartMetafieldInput {
key: string;
value: string;
}

// KNOWN LIMITATION (order-api behavior, not this file's): adding the same skuId twice produces
// two distinct line items only when at least one of the two adds includes `details.selectedAddons`.
// order-api's line-matching (`findMatchingLineItem`) looks at `selectedAddons` alone — it ignores
// `details.productAssetUrl` and `metafields` entirely. So two adds of the same skuId that differ
// only by `metafields` or `productAssetUrl`, with no `selectedAddons` on either, merge into one
// line: the quantities combine, and the second add's `details`/`metafields` silently overwrite the
// first's rather than merging with them (`buildLineItemFromSku` spreads the stored line and then
// replaces both fields wholesale). A caller that needs metafield-only or image-only customizations
// to stay on distinct lines must also include a distinguishing `selectedAddons` entry.
// Tracked as a follow-up against order-api; see `createFromSkuId.ts`'s own design-doc link.
export interface AddToCartItemInput {
skuId: string;
name: string;
quantity: number;
details?: AddLineItemDetailsInput;
metafields?: AddToCartMetafieldInput[];
}

// Only TEXT/NUMBER catalog options (shopper-typed `inputValue`) are supported here. A LIST
// option's pre-defined `optionValueId` is a distinct, unvalidated shape — out of scope for this
// change (see the ticket's addon-value-shape decision) — so reject it explicitly rather than
// letting it reach `order-api` unchecked or crash on a missing `inputValue`.
function assertSupportedAddonValueShape(value: unknown): string {
if (
typeof value !== 'object' ||
value === null ||
typeof (value as { inputValue?: unknown }).inputValue !== 'string'
) {
throw new InvalidRequestError(
'selectedAddons values must use { inputValue }; LIST-option values ({ optionValueId }) are not supported',
);
}
return (value as { inputValue: string }).inputValue;
}

// This is the only place these shapes, length/HTTPS/count limits are enforced — `order-api`'s
// schema uses a plain `z.string()` for these fields with no such caps, and the request body
// arrives as untyped JSON, so every field read here must be shape-checked before use rather
// than trusted from a TypeScript cast.
export function assertValidCartItemInput(item: AddToCartItemInput): void {
const assetUrl = item.details?.productAssetUrl;
if (assetUrl !== undefined) {
if (typeof assetUrl !== 'string') {
throw new InvalidRequestError('productAssetUrl must be a string');
}
if (assetUrl.length > PRODUCT_ASSET_URL_MAX_LENGTH) {
throw new InvalidRequestError(
`productAssetUrl cannot exceed ${PRODUCT_ASSET_URL_MAX_LENGTH} characters`,
);
}
let parsed: URL;
try {
parsed = new URL(assetUrl);
} catch {
throw new InvalidRequestError('productAssetUrl must be an absolute URL');
}
if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

order-api uses data.details?.productAssetUrl || <catalog media>, so any https URL a shopper sends replaces the catalog image on the merchant's order, emails and fulfillment views. If this is meant for design previews, consider restricting it to a host-configured origin allowlist rather than any https URL.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I think an allowlist would make sense here, but worry we might "paint ourselves into a corner" so to speak if the allowlist isn't broad enough for it to work well. What hosts would you propose to explicitly allow?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Agreed, let's not add an allowlist for now. It only makes sense if we can confirm Airo uploads design assets to specific CDNs. If we confirm that later, an optional host-configured origin list (with unset meaning any https URL, as today) would avoid painting ourselves into a corner. The https check is fine for this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Leaving this unresolved so it's easier to find when we return to this question.

}
const addons = item.details?.selectedAddons;
if (addons !== undefined) {
if (!Array.isArray(addons)) throw new InvalidRequestError('selectedAddons must be an array');
if (addons.length > MAX_SELECTED_ADDONS) {
throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`);
}
for (const addon of addons) {
if (
typeof addon !== 'object' ||
addon === null ||
typeof addon.optionId !== 'string' ||
!addon.optionId
) {
throw new InvalidRequestError('Each selectedAddons entry must have a non-empty optionId');
}
if (!Array.isArray(addon.values)) {
throw new InvalidRequestError('Each selectedAddons entry must have a values array');
}
for (const value of addon.values) {
const inputValue = assertSupportedAddonValueShape(value);
if (inputValue.length > SELECTED_ADDON_VALUE_MAX_LENGTH) {
throw new InvalidRequestError(
`selectedAddons value cannot exceed ${SELECTED_ADDON_VALUE_MAX_LENGTH} characters`,
);
}
}
}
}
const metafields = item.metafields;
if (metafields !== undefined) {
if (!Array.isArray(metafields)) throw new InvalidRequestError('metafields must be an array');
if (metafields.length > MAX_METAFIELDS) {
throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`);
}
for (const metafield of metafields) {
if (
typeof metafield !== 'object' ||
metafield === null ||
!metafield.key ||
typeof metafield.key !== 'string'
) {
throw new InvalidRequestError('Each metafield must have a non-empty string key');
}
if (typeof metafield.value !== 'string') {
throw new InvalidRequestError('Each metafield value must be a string');
}
if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) {
throw new InvalidRequestError(
`metafield value cannot exceed ${METAFIELD_VALUE_MAX_LENGTH} characters`,
);
}
}
}
}

// The single place a cart-item request body is turned into a trusted AddToCartItemInput. Reads
// only the known top-level fields off the untyped body — any other property the client sent
// (e.g. a spread product object) is dropped here rather than riding along to order-api, which
// would otherwise reject it as an unknown field and surface as a 502 instead of this 400.
export function parseCartItemInput(body: unknown): AddToCartItemInput {
if (typeof body !== 'object' || body === null) {
throw new InvalidRequestError('Request body must be an object');
}
const candidate = body as Partial<AddToCartItemInput>;
if (!candidate.skuId || typeof candidate.skuId !== 'string') {
throw new InvalidRequestError('skuId must be a non-empty string');
}
if (!candidate.name || typeof candidate.name !== 'string') {
throw new InvalidRequestError('name must be a non-empty string');
}
if (typeof candidate.quantity !== 'number') {
throw new InvalidRequestError('quantity must be a number');
}
// Validate before picking: every field the pick below reads has already been shape-checked
// here, so it can be destructured directly without repeating the same guards.
assertValidCartItemInput(candidate as AddToCartItemInput);
return {
skuId: candidate.skuId,
name: candidate.name,
quantity: candidate.quantity,
...(candidate.details !== undefined
? {
details: {
...(candidate.details.productAssetUrl !== undefined
? { productAssetUrl: candidate.details.productAssetUrl }
: {}),
...(candidate.details.selectedAddons !== undefined
? {
selectedAddons: candidate.details.selectedAddons.map((addon) => ({
optionId: addon.optionId,
values: addon.values.map((value) => ({ inputValue: value.inputValue })),
})),
}
: {}),
},
}
: {}),
...(candidate.metafields !== undefined
? { metafields: candidate.metafields.map(({ key, value }) => ({ key, value })) }
: {}),
};
}

export interface CartSummaryTotals {
Expand Down Expand Up @@ -322,6 +512,8 @@ export function buildEmptyCartOrderInput({
};
}

// Caller must have already validated `item` (e.g. via `parseCartItemInput`) — this function
// does not re-validate.
export function buildAddLineItemBySkuIdInput(
orderId: string,
item: AddToCartItemInput,
Expand All @@ -333,6 +525,16 @@ export function buildAddLineItemBySkuIdInput(
quantity: item.quantity,
fulfillmentMode: 'NONE',
status: 'DRAFT',
...(item.details ? { details: item.details } : {}),
...(item.metafields
? {
metafields: item.metafields.map(({ key, value }) => ({
key,
value,
type: 'JSON' as const,
})),
}
: {}),
};
}

Expand Down
53 changes: 46 additions & 7 deletions packages/commerce-server/src/lib/commerce/upstream-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* upstream errors stay 502; the server log carries their codes and statuses so new rules can
* be derived from real responses rather than guessed.
*/
import { type CommerceError, NotFoundError, type UpstreamError } from './errors';
import { type CommerceError, InvalidRequestError, NotFoundError, type UpstreamError } from './errors';
import { GraphQLErrorWithCodes } from './gql';

export function isCartNotFoundError(error: unknown): boolean {
Expand All @@ -34,20 +34,59 @@ export function isCartNotFoundError(error: unknown): boolean {
});
}

// order-api reports its own input validation (catalog option min/max, the TEXT/NUMBER
// single-value rule, a SKU with no price, etc.) with this code on addLineItemBySkuId and
// addDraftOrder. The browser can't have known the catalog-side rule in advance, so this is a
// 400, not a generic 502 — unlike a true upstream outage or an unexpected shape.
export function isBadUserInputError(error: unknown): boolean {
if (!(error instanceof GraphQLErrorWithCodes)) {
return false;
}
return error.errors.length > 0 && error.errors.every(({ code }) => code === 'BAD_USER_INPUT');
}

interface UpstreamErrorRule {
matches(error: UpstreamError): boolean;
toError(error: UpstreamError): CommerceError;
}

const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [
{
// A completed (paid) draft is reported the same way, so this is "no longer a usable cart".
matches: isCartNotFoundError,
toError: (error) => new NotFoundError('Cart not found', { cause: error }),
},
const BAD_USER_INPUT_RULE: UpstreamErrorRule = {
matches: isBadUserInputError,
toError: (error) =>
new InvalidRequestError('The requested change is not valid for this cart or its items.', {
cause: error,
message: error.message,
}),
};

const CART_NOT_FOUND_RULE: UpstreamErrorRule = {
// A completed (paid) draft is reported the same way, so this is "no longer a usable cart".
matches: isCartNotFoundError,
toError: (error) => new NotFoundError('Cart not found', { cause: error }),
};

const CART_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [CART_NOT_FOUND_RULE];

// Add-item is the only route BAD_USER_INPUT is mapped for today: it's the one order-api path
// this PR actually exercises for that code. Applying it to every classifyCartUpstreamError
// route (GET, discounts, PATCH, DELETE) would be untested scope creep — add it to
// CART_UPSTREAM_ERROR_RULES too only once those routes' BAD_USER_INPUT cases are understood.
const ADD_ITEM_UPSTREAM_ERROR_RULES: readonly UpstreamErrorRule[] = [
CART_NOT_FOUND_RULE,
BAD_USER_INPUT_RULE,
Comment thread
ajaynes-godaddy marked this conversation as resolved.
Resolved
];

/** For routes acting on an existing saved cart (`/cart/:id`); creating a cart has none to miss. */
export function classifyCartUpstreamError(error: UpstreamError): CommerceError {
return CART_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error;
}

/** For `POST /cart/:id/items`: an existing cart can still go missing, and the new item can still fail validation. */
export function classifyAddItemUpstreamError(error: UpstreamError): CommerceError {
return ADD_ITEM_UPSTREAM_ERROR_RULES.find((rule) => rule.matches(error))?.toError(error) ?? error;
}

/** For `POST /cart`: no existing cart to report missing, but addDraftOrder/addLineItemBySkuId can still reject input. */
export function classifyCartCreationUpstreamError(error: UpstreamError): CommerceError {
return BAD_USER_INPUT_RULE.matches(error) ? BAD_USER_INPUT_RULE.toError(error) : error;
}
Loading