@happyvertical/payments 0.105.4 → 0.105.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"stripe.js","names":[],"sources":["../../src/adapters/stripe.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n PaymentConfigurationError,\n PaymentProviderError,\n PaymentVerificationError,\n} from '../errors.js';\nimport {\n applyExpiryToPendingStatus,\n type FetchLike,\n formEncode,\n getFetch,\n normalizeDate,\n normalizeMaxStoredPaymentOptions,\n normalizeMinorUnitAmount,\n normalizeNonEmptyString,\n normalizePositiveMinorUnitAmount,\n normalizePositivePaymentAmount,\n normalizeUrlString,\n pollPaymentStatus,\n readJsonResponse,\n rememberPaymentOption,\n} from '../shared.js';\nimport type {\n AuthorizationResult,\n AuthorizePaymentInput,\n CapturePaymentInput,\n CaptureResult,\n CreatePaymentOptionInput,\n CreateSetupSessionInput,\n GetSetupResultInput,\n PaymentBackend,\n PaymentBackendCapabilities,\n PaymentEvent,\n PaymentOption,\n PaymentStatus,\n PaymentStatusContext,\n PaymentStatusResult,\n PaymentWebhookEvent,\n PayoutResult,\n RefundPaymentInput,\n RefundResult,\n SavedPaymentMethod,\n SendPayoutInput,\n SetupSession,\n VoidPaymentInput,\n VoidResult,\n WatchPaymentInput,\n} from '../types.js';\n\nexport const STRIPE_BACKEND_ID = 'stripe';\nconst STRIPE_CHECKOUT_MIN_EXPIRY_MS = 30 * 60 * 1_000;\nconst STRIPE_CHECKOUT_MAX_EXPIRY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_STRIPE_API_VERSION = '2024-06-20';\nconst DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS = 50_000;\n\nexport interface StripeAdapterOptions {\n secretKey: string;\n fetch?: FetchLike;\n apiBaseUrl?: string;\n apiVersion?: string;\n defaultCurrency?: string;\n supportedCurrencies?: string[];\n successUrl?: string;\n cancelUrl?: string;\n checkoutMode?: string;\n webhookSecret?: string;\n pollIntervalMs?: number;\n maxStoredPaymentOptions?: number;\n maxStoredWebhookEventIds?: number;\n /** Default Stripe Connect account for this adapter's provider requests. */\n stripeAccount?: string;\n}\n\n/** Stripe Connect account scope for a request; omit it for the platform. */\nexport interface StripeAccountScope {\n stripeAccount?: string;\n}\n\nexport interface StripeCreatePaymentOptionInput\n extends CreatePaymentOptionInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this direct charge. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripePaymentStatusContext\n extends PaymentStatusContext,\n StripeAccountScope {}\n\nexport interface StripeRefundPaymentInput\n extends RefundPaymentInput,\n StripeAccountScope {\n /** Refund a Stripe application fee collected with the charge. */\n refundApplicationFee?: boolean;\n /** Reverse a destination transfer when the provider supports one. */\n reverseTransfer?: boolean;\n}\n\nexport interface StripeAuthorizePaymentInput\n extends AuthorizePaymentInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this PaymentIntent. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripeCapturePaymentInput\n extends CapturePaymentInput,\n StripeAccountScope {}\n\nexport interface StripeVoidPaymentInput\n extends VoidPaymentInput,\n StripeAccountScope {}\n\nexport interface StripeCreateSetupSessionInput\n extends CreateSetupSessionInput,\n StripeAccountScope {}\n\nexport interface StripeGetSetupResultInput\n extends GetSetupResultInput,\n StripeAccountScope {}\n\nexport interface StripeWatchPaymentInput\n extends Omit<WatchPaymentInput, 'statusContext'> {\n statusContext?: StripePaymentStatusContext;\n}\n\nexport interface StripeWebhookEvent extends PaymentWebhookEvent {\n id: string;\n type: string;\n status: PaymentStatus;\n quoteId?: string;\n providerPaymentId?: string;\n raw: unknown;\n}\n\nexport class StripeAdapter implements PaymentBackend {\n readonly capabilities: PaymentBackendCapabilities;\n\n private readonly fetch: FetchLike;\n private readonly secretKey: string;\n private readonly apiBaseUrl: string;\n private readonly apiVersion: string;\n private readonly defaultCurrency: string;\n private readonly supportedCurrencies: Set<string>;\n private readonly checkoutMode: string;\n private readonly webhookSecret: string | undefined;\n private readonly stripeAccount: string | undefined;\n private readonly maxStoredPaymentOptions: number;\n private readonly maxStoredWebhookEventIds: number;\n private readonly optionsByQuote = new Map<string, PaymentOption>();\n private readonly seenWebhookEventIds = new Set<string>();\n\n constructor(private readonly options: StripeAdapterOptions) {\n if (typeof options.secretKey !== 'string' || !options.secretKey.trim()) {\n throw new PaymentConfigurationError('StripeAdapter requires secretKey.');\n }\n\n if (options.webhookSecret !== undefined) {\n if (typeof options.webhookSecret !== 'string') {\n throw new PaymentConfigurationError(\n 'StripeAdapter webhookSecret must be a string when configured.',\n );\n }\n\n if (!options.webhookSecret.trim()) {\n throw new PaymentConfigurationError(\n 'StripeAdapter webhookSecret must not be empty when configured.',\n );\n }\n }\n\n if (options.apiBaseUrl !== undefined) {\n if (typeof options.apiBaseUrl !== 'string') {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must be a string when configured.',\n );\n }\n\n if (!options.apiBaseUrl.trim()) {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must not be empty when configured.',\n );\n }\n }\n\n this.fetch = getFetch(options.fetch);\n this.maxStoredPaymentOptions = normalizeMaxStoredPaymentOptions(\n options.maxStoredPaymentOptions,\n 'StripeAdapter maxStoredPaymentOptions',\n );\n this.maxStoredWebhookEventIds = normalizeMaxStoredPaymentOptions(\n options.maxStoredWebhookEventIds ?? DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS,\n 'StripeAdapter maxStoredWebhookEventIds',\n );\n this.secretKey = options.secretKey.trim();\n this.apiBaseUrl = normalizeUrlString(\n options.apiBaseUrl ?? 'https://api.stripe.com/v1',\n 'StripeAdapter apiBaseUrl',\n ).replace(/\\/$/, '');\n this.apiVersion = normalizeNonEmptyString(\n options.apiVersion ?? DEFAULT_STRIPE_API_VERSION,\n 'StripeAdapter apiVersion',\n );\n this.defaultCurrency = normalizeStripeCurrency(\n options.defaultCurrency ?? 'usd',\n );\n this.supportedCurrencies = normalizeSupportedStripeCurrencies(\n options.supportedCurrencies,\n this.defaultCurrency,\n );\n this.checkoutMode = options.checkoutMode ?? 'payment';\n\n if (this.checkoutMode !== 'payment') {\n throw new PaymentConfigurationError(\n 'StripeAdapter only supports payment Checkout mode.',\n );\n }\n\n this.webhookSecret = options.webhookSecret?.trim();\n this.stripeAccount = normalizeOptionalStripeAccount(\n options.stripeAccount,\n 'StripeAdapter stripeAccount',\n );\n this.capabilities = {\n id: STRIPE_BACKEND_ID,\n displayName: 'Stripe Checkout',\n settlementCurrency: this.defaultCurrency.toUpperCase(),\n supportedSettlementCurrencies: [...this.supportedCurrencies].map(\n (currency) => currency.toUpperCase(),\n ),\n chain: 'stripe',\n settlementShape: 'url',\n x402Capable: false,\n confirmationLatency: {\n expectedSeconds: 5,\n maxExpectedSeconds: 600,\n description:\n 'Card payments usually confirm in seconds; bank debits can remain processing while Stripe settles them.',\n },\n supportsRefunds: true,\n supportsPayouts: true,\n supportsWebhooks: true,\n supportsManualCapture: true,\n supportsSavedPaymentMethods: true,\n metadata: {\n provider: 'stripe',\n },\n };\n }\n\n async createPaymentOption(\n input: StripeCreatePaymentOptionInput,\n ): Promise<PaymentOption> {\n const quoteId = normalizeNonEmptyString(input.quoteId, 'Stripe quoteId');\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createPaymentOption requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe Checkout amount',\n );\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe Checkout applicationFeeAmount',\n );\n const expiresAt = normalizeDate(input.expiresAt);\n const stripeExpiresAt = normalizeStripeCheckoutExpiresAt(expiresAt);\n const params: Record<string, unknown> = {\n mode: this.checkoutMode,\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ['client_reference_id', quoteId],\n ['customer_email', input.buyerEmail],\n ['expires_at', Math.floor(stripeExpiresAt.getTime() / 1_000)],\n ]),\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': currency,\n 'line_items[0][price_data][unit_amount]': amount,\n 'line_items[0][price_data][product_data][name]':\n input.description ?? `Quote ${quoteId}`,\n ...(applicationFeeAmount === undefined\n ? {}\n : {\n 'payment_intent_data[application_fee_amount]': applicationFeeAmount,\n }),\n ...flattenStripeMetadata(input.metadata),\n 'metadata[quoteId]': quoteId,\n };\n\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(params),\n },\n );\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const checkoutUrl = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !checkoutUrl) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session response did not include id and url.',\n );\n }\n\n const option: PaymentOption = {\n backendId: this.capabilities.id,\n quoteId,\n payTo: checkoutUrl,\n settlementShape: 'url',\n settlementCurrency: currency.toUpperCase(),\n settlementAmount: amount,\n amount,\n currency: currency.toUpperCase(),\n expiresAt: stripeExpiresAt,\n providerPaymentId: sessionId,\n paymentUri: checkoutUrl,\n metadata: {\n sessionId,\n stripeAccount,\n paymentIntent: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n },\n };\n\n rememberPaymentOption(\n this.optionsByQuote,\n stripePaymentOptionKey(quoteId, stripeAccount),\n option,\n this.maxStoredPaymentOptions,\n );\n\n return option;\n }\n\n watchPayment(input: StripeWatchPaymentInput): AsyncIterable<PaymentEvent> {\n return pollPaymentStatus(\n {\n ...input,\n pollIntervalMs:\n input.pollIntervalMs ?? this.options.pollIntervalMs ?? 5_000,\n },\n () => this.getStatus(input.quoteId, input.payTo, input.statusContext),\n );\n }\n\n async getStatus(\n quoteId: string,\n payTo: string,\n context: StripePaymentStatusContext = {},\n ): Promise<PaymentStatusResult> {\n const normalizedQuoteId = normalizeNonEmptyString(\n quoteId,\n 'Stripe quoteId',\n );\n const normalizedPayTo = normalizeNonEmptyString(payTo, 'Stripe payTo');\n const contextProviderPaymentId =\n context.providerPaymentId === undefined\n ? undefined\n : normalizeNonEmptyString(\n context.providerPaymentId,\n 'Stripe providerPaymentId',\n );\n const contextStripeAccount = normalizeOptionalStripeAccount(\n context.stripeAccount,\n 'Stripe stripeAccount',\n );\n const scopedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(\n normalizedQuoteId,\n contextStripeAccount ?? this.stripeAccount,\n ),\n );\n const sessionId =\n contextProviderPaymentId ??\n extractStripeSessionId(normalizedPayTo) ??\n scopedOption?.providerPaymentId;\n\n if (!sessionId) {\n throw new PaymentConfigurationError(\n 'Stripe getStatus requires a Checkout Session id or URL.',\n );\n }\n\n const storedOption = this.findStoredOptionBySessionId(sessionId);\n const stripeAccount =\n contextStripeAccount ??\n readStripeOptionAccount(storedOption) ??\n this.stripeAccount;\n const cachedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(normalizedQuoteId, stripeAccount),\n );\n\n // A caller-supplied session id can deliberately select a later checkout\n // for the same quote. Cache-derived amount, currency, and expiry describe\n // only the session we created, never an explicitly selected replacement.\n const option =\n cachedOption?.providerPaymentId === sessionId ? cachedOption : undefined;\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}`,\n { stripeAccount },\n );\n const sessionQuoteId = readStripeSessionQuoteId(session);\n\n if (sessionQuoteId !== undefined && sessionQuoteId !== normalizedQuoteId) {\n throw new PaymentVerificationError(\n `Stripe Checkout Session quoteId ${sessionQuoteId} did not match ${normalizedQuoteId}.`,\n );\n }\n\n const paymentStatus = readString(session, 'payment_status');\n const status = mapStripeStatus(\n readString(session, 'status'),\n paymentStatus,\n );\n\n const contextAmount =\n context.amount === undefined\n ? undefined\n : normalizeMinorUnitAmount(context.amount, 'Stripe status');\n const contextCurrency =\n context.currency === undefined\n ? undefined\n : normalizeStripeCurrency(context.currency).toUpperCase();\n const sessionCurrency =\n readString(session, 'currency') === undefined\n ? undefined\n : normalizeStripeCurrency(\n readString(session, 'currency') ?? '',\n ).toUpperCase();\n const sessionAmount = readSafeInteger(session, 'amount_total');\n const expiresAt =\n option?.expiresAt ??\n (context.expiresAt === undefined\n ? undefined\n : normalizeDate(context.expiresAt));\n const effectiveStatus = applyExpiryToPendingStatus(status, expiresAt);\n\n return {\n backendId: this.capabilities.id,\n quoteId: normalizedQuoteId,\n payTo: normalizedPayTo,\n status: effectiveStatus,\n settlementCurrency:\n sessionCurrency ??\n option?.settlementCurrency ??\n contextCurrency ??\n this.defaultCurrency.toUpperCase(),\n settlementAmount:\n sessionAmount ?? option?.settlementAmount ?? contextAmount,\n receivedAmount:\n paymentStatus === 'paid' || paymentStatus === 'no_payment_required'\n ? (sessionAmount ?? option?.settlementAmount ?? contextAmount)\n : undefined,\n amount: option?.amount ?? contextAmount,\n currency: option?.currency ?? contextCurrency,\n providerPaymentId: sessionId,\n transactionId: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n updatedAt: new Date(),\n raw: session,\n };\n }\n\n async sendPayout(input: SendPayoutInput): Promise<PayoutResult> {\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const destination = normalizeNonEmptyString(\n input.destination,\n 'Stripe payout destination',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe payout quoteId');\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe payout amount',\n );\n const transfer = await this.stripeRequest<Record<string, unknown>>(\n '/transfers',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n amount,\n currency,\n destination,\n description: input.memo,\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: 'submitted',\n payoutId: normalizeOptionalProviderString(\n readProviderString(transfer, 'id'),\n ),\n destination,\n amount,\n currency: currency.toUpperCase(),\n raw: transfer,\n };\n }\n\n async refundPayment(input: StripeRefundPaymentInput): Promise<RefundResult> {\n const rawPaymentReference = input.paymentId ?? input.transactionId;\n\n if (!rawPaymentReference) {\n throw new PaymentConfigurationError(\n 'Stripe refunds require paymentId or transactionId.',\n );\n }\n\n const paymentReference = normalizeNonEmptyString(\n rawPaymentReference,\n 'Stripe refund payment reference',\n );\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe refund amount',\n );\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const refundReferenceParam = await this.resolveStripeRefundReferenceParam(\n paymentReference,\n stripeAccount,\n );\n const refundParams: Record<string, unknown> = {\n ...refundReferenceParam,\n amount: amount === undefined ? undefined : amount,\n reason: input.reason,\n refund_application_fee: input.refundApplicationFee,\n reverse_transfer: input.reverseTransfer,\n ...flattenStripeMetadata(input.metadata),\n };\n\n const refund = await this.stripeRequest<Record<string, unknown>>(\n '/refunds',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(refundParams),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeRefundStatus(readString(refund, 'status')),\n refundId: normalizeOptionalProviderString(\n readProviderString(refund, 'id'),\n ),\n transactionId: paymentReference,\n // Read the settled amount and currency back from the refund object\n // (mirrors capturePayment) so a full refund — no `input.amount` supplied,\n // and possibly a currency differing from the adapter default when\n // `input.currency` is omitted — surfaces what Stripe actually refunded\n // instead of the request defaults.\n amount: readSafeInteger(refund, 'amount') ?? amount,\n currency: readStripeResultCurrency(refund) ?? currency.toUpperCase(),\n raw: refund,\n };\n }\n\n async authorizePayment(\n input: StripeAuthorizePaymentInput,\n ): Promise<AuthorizationResult> {\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe authorize amount',\n );\n const paymentMethod = normalizeNonEmptyString(\n input.providerPaymentMethodId,\n 'Stripe authorize providerPaymentMethodId',\n );\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe authorize providerCustomerId',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe authorize quoteId');\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe PaymentIntent applicationFeeAmount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n '/payment_intents',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n amount,\n currency,\n confirm: true,\n 'payment_method_types[]': 'card',\n description: input.description,\n application_fee_amount: applicationFeeAmount,\n ...Object.fromEntries([\n ['payment_method', paymentMethod],\n ['capture_method', 'manual'],\n // Off-session (merchant-initiated) by default — the primary use is\n // charging a saved card while the buyer is absent. Without this,\n // Stripe treats it as on-session and may raise an SCA challenge the\n // absent buyer can't complete, so the hold is never placed.\n ['off_session', input.offSession ?? true],\n ]),\n ...(providerCustomerId === undefined\n ? {}\n : { customer: providerCustomerId }),\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n const providerPaymentId = normalizeOptionalProviderString(\n readProviderString(intent, 'id'),\n );\n\n if (!providerPaymentId) {\n throw new PaymentProviderError(\n 'Stripe PaymentIntent response did not include an id.',\n );\n }\n\n const status = mapStripeAuthorizationStatus(readString(intent, 'status'));\n // Only surface the SCA fields when authentication is actually required — the\n // documented contract — even though Stripe returns client_secret regardless.\n // (Authorization progress is observed via `parseWebhookEvent`, which surfaces\n // the ready-to-capture transition as `processing` — there is no distinct\n // `requires_capture` webhook status; `getStatus` handles Checkout sessions,\n // not PaymentIntents.)\n const actionRequired = status === 'requires_action';\n\n return {\n backendId: this.capabilities.id,\n status,\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount') ?? amount,\n currency: (readString(intent, 'currency') ?? currency).toUpperCase(),\n clientSecret: actionRequired\n ? normalizeOptionalProviderString(\n readProviderString(intent, 'client_secret'),\n )\n : undefined,\n nextAction: actionRequired\n ? (intent.next_action ?? undefined)\n : undefined,\n raw: intent,\n };\n }\n\n async capturePayment(\n input: StripeCapturePaymentInput,\n ): Promise<CaptureResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe capture providerPaymentId',\n );\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositiveMinorUnitAmount(\n input.amount,\n 'Stripe capture amount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/capture`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n ...Object.fromEntries([['amount_to_capture', amount]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeCaptureStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount:\n readSafeInteger(intent, 'amount_received') ??\n readSafeInteger(intent, 'amount') ??\n amount,\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async voidPayment(input: StripeVoidPaymentInput): Promise<VoidResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe void providerPaymentId',\n );\n const reason =\n input.reason === undefined\n ? undefined\n : normalizeNonEmptyString(input.reason, 'Stripe void reason');\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/cancel`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(Object.fromEntries([['cancellation_reason', reason]])),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeVoidStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount'),\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async createSetupSession(\n input: StripeCreateSetupSessionInput,\n ): Promise<SetupSession> {\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createSetupSession requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n // Currency for the setup-mode session (defaults to the backend currency).\n // Redundant now that payment_method_types is always set, but harmless and\n // kept so the session is well-formed if that restriction is ever relaxed.\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe setup customer',\n );\n\n // Either attach to an existing customer, or force Stripe to create one so\n // the saved method comes back with a reusable `cus_` reference. Setup-mode\n // sessions do NOT create a customer on their own — `customer_creation` must\n // be `always`. All snake_case keys go through Object.fromEntries.\n const customerParams: [string, unknown][] = [];\n if (providerCustomerId !== undefined) {\n customerParams.push(['customer', providerCustomerId]);\n } else {\n customerParams.push(['customer_creation', 'always']);\n if (input.customerEmail !== undefined) {\n customerParams.push([\n 'customer_email',\n normalizeNonEmptyString(\n input.customerEmail,\n 'Stripe setup customerEmail',\n ),\n ]);\n }\n }\n\n const params: Record<string, unknown> = {\n mode: 'setup',\n currency,\n // Restrict to cards: SavedPaymentMethod exposes card display fields\n // (brand/last4/expiry), so allowing SEPA/Bacs/etc. would yield saved\n // methods with no usable display detail.\n 'payment_method_types[]': 'card',\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ...customerParams,\n ]),\n ...flattenStripeMetadata(input.metadata),\n };\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(params),\n },\n );\n\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const url = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !url) {\n throw new PaymentProviderError(\n 'Stripe setup Checkout Session response did not include id and url.',\n );\n }\n\n return {\n backendId: this.capabilities.id,\n sessionId,\n url,\n providerCustomerId:\n providerCustomerId ??\n normalizeOptionalProviderString(\n readProviderString(session, 'customer'),\n ),\n raw: session,\n };\n }\n\n async getSetupResult(\n input: StripeGetSetupResultInput,\n ): Promise<SavedPaymentMethod> {\n const sessionId = normalizeNonEmptyString(\n input.sessionId,\n 'Stripe setup sessionId',\n );\n\n const query = new URLSearchParams();\n query.append('expand[]', 'setup_intent.payment_method');\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}?${query.toString()}`,\n { stripeAccount: this.resolveStripeAccount(input.stripeAccount) },\n );\n\n const setupIntent = readObject(session, 'setup_intent');\n const paymentMethod = readObject(setupIntent, 'payment_method');\n const card = readObject(paymentMethod, 'card');\n\n // `customer` is a bare `cus_` string on the request path (only\n // setup_intent.payment_method is expanded), but read tolerantly of an\n // expanded object so a future `expand[]=customer` can't wrongly downgrade a\n // completed setup to a permanent `pending`.\n const providerCustomerId = normalizeOptionalProviderString(\n readProviderString(session, 'customer') ??\n readProviderString(readObject(session, 'customer'), 'id'),\n );\n const providerPaymentMethodId = normalizeOptionalProviderString(\n readProviderString(paymentMethod, 'id'),\n );\n\n let status = mapStripeSetupStatus(\n readString(session, 'status'),\n readString(setupIntent, 'status'),\n );\n // Never report `complete` without the reusable references a caller needs to\n // charge the method later — a `pm_` with no `cus_` can't be charged\n // off-session, so treat that as not-yet-ready rather than a false success.\n if (\n status === 'complete' &&\n (!providerCustomerId || !providerPaymentMethodId)\n ) {\n status = 'pending';\n }\n\n return {\n backendId: this.capabilities.id,\n status,\n providerCustomerId,\n providerPaymentMethodId,\n type: readString(paymentMethod, 'type'),\n brand: readString(card, 'brand'),\n last4: readString(card, 'last4'),\n expMonth: readSafeInteger(card, 'exp_month'),\n expYear: readSafeInteger(card, 'exp_year'),\n raw: session,\n };\n }\n\n parseWebhookEvent(payload: string, signature?: string): StripeWebhookEvent {\n if (!this.webhookSecret) {\n throw new PaymentConfigurationError(\n 'StripeAdapter parseWebhookEvent requires webhookSecret.',\n );\n }\n\n if (!signature) {\n throw new PaymentProviderError('Missing Stripe webhook signature.');\n }\n\n verifyStripeWebhookSignature(payload, signature, this.webhookSecret);\n\n const event = parseStripeWebhookPayload(payload);\n const id = readRequiredWebhookString(\n event,\n 'id',\n 'Stripe webhook event id',\n );\n const type = readRequiredWebhookString(\n event,\n 'type',\n 'Stripe webhook event type',\n );\n\n const duplicate = this.seenWebhookEventIds.has(id);\n\n if (!duplicate) {\n this.seenWebhookEventIds.add(id);\n while (this.seenWebhookEventIds.size > this.maxStoredWebhookEventIds) {\n const oldest = this.seenWebhookEventIds.values().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n this.seenWebhookEventIds.delete(oldest);\n }\n }\n\n const data = (\n event.data as { object?: Record<string, unknown> } | undefined\n )?.object;\n\n return {\n id,\n type,\n status: mapStripeWebhookStatus(type, data),\n quoteId: normalizeOptionalWebhookString(\n // `client_reference_id` is a Checkout Session-only field; honor it only\n // for session events so a non-session object (a PaymentIntent / Charge /\n // Transfer, possibly from a malicious Connect account) can't spoof\n // correlation to another quote's id. Non-session events correlate only\n // via our own `metadata.quoteId`.\n (type.startsWith('checkout.session.')\n ? readString(data, 'client_reference_id')\n : undefined) ??\n readString(\n (data?.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n ),\n providerPaymentId: normalizeOptionalWebhookString(readString(data, 'id')),\n duplicate,\n raw: event,\n };\n }\n\n private async stripeRequest<T>(\n path: string,\n init: RequestInit & {\n idempotencyKey?: string;\n stripeAccount?: string;\n } = {},\n ): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.secretKey}`);\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n headers.set('Accept', 'application/json');\n headers.set('Stripe-Version', this.apiVersion);\n\n if (init.stripeAccount !== undefined) {\n headers.set('Stripe-Account', init.stripeAccount);\n }\n\n if (init.idempotencyKey !== undefined) {\n headers.set(\n 'Idempotency-Key',\n normalizeNonEmptyString(init.idempotencyKey, 'Stripe idempotencyKey'),\n );\n }\n\n const {\n idempotencyKey: _idempotencyKey,\n stripeAccount: _stripeAccount,\n ...requestInit\n } = init;\n const response = await this.fetch(`${this.apiBaseUrl}${path}`, {\n ...requestInit,\n method: init.method ?? 'GET',\n headers,\n });\n\n return readJsonResponse<T>(response, `Stripe ${path}`);\n }\n\n private assertSupportedCurrency(currency: string): void {\n if (!this.supportedCurrencies.has(currency)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency ${currency.toUpperCase()} is not configured as supported.`,\n );\n }\n }\n\n private async resolveStripeRefundReferenceParam(\n paymentReference: string,\n stripeAccount: string | undefined,\n ): Promise<Record<string, string>> {\n if (paymentReference.startsWith('cs_')) {\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(paymentReference)}`,\n { stripeAccount },\n );\n const paymentIntent = normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n );\n\n if (!paymentIntent) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session did not include payment_intent for refund.',\n );\n }\n\n return Object.fromEntries([['payment_intent', paymentIntent]]);\n }\n\n return stripeRefundReferenceParam(paymentReference);\n }\n\n private resolveStripeAccount(\n override: string | undefined,\n ): string | undefined {\n return (\n normalizeOptionalStripeAccount(override, 'Stripe stripeAccount') ??\n this.stripeAccount\n );\n }\n\n private findStoredOptionBySessionId(\n sessionId: string,\n ): PaymentOption | undefined {\n for (const option of this.optionsByQuote.values()) {\n if (option.providerPaymentId === sessionId) return option;\n }\n return undefined;\n }\n}\n\nfunction readStripeOptionAccount(\n option: PaymentOption | undefined,\n): string | undefined {\n const value = option?.metadata?.stripeAccount;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction normalizeOptionalStripeAccount(\n value: string | undefined,\n context: string,\n): string | undefined {\n return value === undefined\n ? undefined\n : normalizeNonEmptyString(value, context);\n}\n\nfunction normalizeApplicationFeeAmount(\n value: number | undefined,\n chargeAmount: number,\n context: string,\n): number | undefined {\n if (value === undefined) return undefined;\n\n const fee = normalizePositiveMinorUnitAmount(value, context);\n if (fee > chargeAmount) {\n throw new PaymentConfigurationError(\n `${context} must not exceed the charge amount.`,\n );\n }\n return fee;\n}\n\nfunction stripePaymentOptionKey(\n quoteId: string,\n stripeAccount: string | undefined,\n): string {\n // Platform entries retain their old quote-only keys. Connected-account ids\n // cannot contain NUL in an HTTP header, so it safely separates account scope\n // from the caller's quote id without collapsing tenant-local quote ids.\n return stripeAccount === undefined ? quoteId : `${stripeAccount}\\0${quoteId}`;\n}\n\nfunction stripeRefundReferenceParam(\n paymentReference: string,\n): Record<string, string> {\n if (paymentReference.startsWith('pi_')) {\n return Object.fromEntries([['payment_intent', paymentReference]]);\n }\n\n if (paymentReference.startsWith('ch_')) {\n return { charge: paymentReference };\n }\n\n throw new PaymentConfigurationError(\n 'Stripe refunds require a Checkout Session (cs_), payment_intent (pi_), or charge (ch_) reference.',\n );\n}\n\nfunction normalizeStripeCurrency(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (!/^[a-z]{3}$/.test(normalized)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizeSupportedStripeCurrencies(\n configuredCurrencies: string[] | undefined,\n defaultCurrency: string,\n): Set<string> {\n const normalized = new Set(\n (configuredCurrencies ?? ['usd', 'eur', 'gbp', 'cad']).map(\n normalizeStripeCurrency,\n ),\n );\n normalized.add(defaultCurrency);\n\n return normalized;\n}\n\nfunction normalizeStripeCheckoutExpiresAt(\n expiresAt: Date,\n now = Date.now(),\n): Date {\n if (expiresAt.getTime() <= now) {\n throw new PaymentProviderError('Stripe Checkout expiry is in the past.');\n }\n\n const min = now + STRIPE_CHECKOUT_MIN_EXPIRY_MS;\n const max = now + STRIPE_CHECKOUT_MAX_EXPIRY_MS;\n\n if (expiresAt.getTime() < min || expiresAt.getTime() > max) {\n throw new PaymentConfigurationError(\n 'Stripe Checkout expiry must be at least 30 minutes and no more than 24 hours from now.',\n );\n }\n\n return expiresAt;\n}\n\nexport function verifyStripeWebhookSignature(\n payload: string,\n signatureHeader: string,\n secret: string,\n toleranceSeconds = 300,\n): void {\n if (typeof payload !== 'string') {\n throw new PaymentProviderError('Stripe webhook payload must be a string.');\n }\n\n const normalizedSignatureHeader = normalizeNonEmptyString(\n signatureHeader,\n 'Stripe signature header',\n );\n const normalizedSecret = normalizeNonEmptyString(\n secret,\n 'Stripe webhook secret',\n );\n\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {\n throw new PaymentConfigurationError(\n `Stripe webhook toleranceSeconds must be a non-negative finite number, received ${String(toleranceSeconds)}.`,\n );\n }\n\n const timestampCandidates: string[] = [];\n const signatures: string[] = [];\n\n for (const part of normalizedSignatureHeader.split(',')) {\n const [rawKey, ...rawValue] = part.split('=');\n const key = rawKey?.trim();\n const value = rawValue.join('=').trim();\n\n if (!key || !value) {\n continue;\n }\n\n if (key === 't') {\n timestampCandidates.push(value);\n }\n\n if (key === 'v1') {\n signatures.push(value);\n }\n }\n\n if (timestampCandidates.length !== 1 || signatures.length === 0) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestamp = timestampCandidates[0] ?? '';\n\n if (!/^\\d+$/.test(timestamp)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestampSeconds = Number(timestamp);\n\n if (!Number.isSafeInteger(timestampSeconds)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const nowSeconds = Date.now() / 1_000;\n const ageSeconds = nowSeconds - timestampSeconds;\n\n if (ageSeconds < -5) {\n throw new PaymentProviderError(\n 'Stripe webhook signature timestamp is in the future.',\n );\n }\n\n if (ageSeconds > toleranceSeconds) {\n throw new PaymentProviderError('Stripe webhook signature is too old.');\n }\n\n const expected = createHmac('sha256', normalizedSecret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n const expectedBuffer = Buffer.from(expected, 'hex');\n\n for (const signature of signatures) {\n if (!/^[0-9a-f]+$/i.test(signature)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const actualBuffer = Buffer.from(signature, 'hex');\n\n if (\n expectedBuffer.length === actualBuffer.length &&\n timingSafeEqual(expectedBuffer, actualBuffer)\n ) {\n return;\n }\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook signature.');\n}\n\nfunction parseStripeWebhookPayload(payload: string): Record<string, unknown> {\n try {\n const event = JSON.parse(payload);\n\n if (!event || typeof event !== 'object' || Array.isArray(event)) {\n throw new PaymentProviderError('Invalid Stripe webhook JSON payload.');\n }\n\n return event as Record<string, unknown>;\n } catch (error) {\n if (error instanceof PaymentProviderError) {\n throw error;\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook JSON payload.', {\n cause: error,\n });\n }\n}\n\nfunction normalizeOptionalWebhookString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction normalizeOptionalProviderString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction readProviderString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'string' ? item : undefined;\n}\n\nfunction readRequiredWebhookString(\n value: Record<string, unknown>,\n key: string,\n context: string,\n): string {\n const item = value[key];\n\n if (typeof item !== 'string') {\n throw new PaymentProviderError(`${context} must be a string.`);\n }\n\n return normalizeNonEmptyString(item, context);\n}\n\nfunction readStripeSessionQuoteId(\n session: Record<string, unknown>,\n): string | undefined {\n return normalizeOptionalWebhookString(\n readString(session, 'client_reference_id') ??\n readString(\n (session.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n );\n}\n\nfunction mapStripeStatus(\n checkoutStatus: string | undefined,\n paymentStatus: string | undefined,\n): PaymentStatus {\n if (paymentStatus === 'paid' || paymentStatus === 'no_payment_required') {\n return 'confirmed';\n }\n\n if (checkoutStatus === 'expired') {\n return 'expired';\n }\n\n if (paymentStatus === 'unpaid' || checkoutStatus === 'open') {\n return 'pending';\n }\n\n if (checkoutStatus === 'complete') {\n return 'processing';\n }\n\n return 'pending';\n}\n\nfunction mapStripeWebhookStatus(\n type: string | undefined,\n object: Record<string, unknown> | undefined,\n): PaymentStatus {\n if (type === 'checkout.session.completed') {\n return mapStripeStatus(\n readString(object, 'status'),\n readString(object, 'payment_status'),\n );\n }\n\n if (type === 'checkout.session.async_payment_succeeded') {\n return 'confirmed';\n }\n\n if (type === 'checkout.session.async_payment_failed') {\n return 'failed';\n }\n\n if (type === 'checkout.session.expired') {\n return 'expired';\n }\n\n // Manual-capture PaymentIntent lifecycle (authorize → capture / void). Only\n // treat these as terminal for intents WE created and can correlate — i.e.\n // ones carrying our `quoteId` in metadata. Checkout Sessions create their own\n // PaymentIntents (which fire these same events with no quoteId on the intent);\n // those are handled via the `checkout.session.*` events above, so here they\n // stay non-terminal (`processing`) rather than emitting a spurious,\n // uncorrelatable terminal event. Handled before the generic `failed` catch\n // below so an un-owned `payment_intent.payment_failed` isn't reclassified.\n if (\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.canceled' ||\n type === 'payment_intent.payment_failed'\n ) {\n const metadata = (object?.metadata as Record<string, unknown>) ?? {};\n // Match parseWebhookEvent's normalization so an empty/blank quoteId is\n // treated as un-owned by both — gate and reporter must agree on ownership.\n const owned =\n normalizeOptionalWebhookString(readString(metadata, 'quoteId')) !==\n undefined;\n if (owned) {\n if (type === 'payment_intent.succeeded') {\n return 'confirmed';\n }\n // A manual-capture hold Stripe released automatically (it lapsed) is\n // `expired`, distinct from a deliberate void or hard decline (`failed`);\n // the shared PaymentStatus union has no `canceled`.\n if (\n type === 'payment_intent.canceled' &&\n readString(object, 'cancellation_reason') === 'automatic'\n ) {\n return 'expired';\n }\n return 'failed';\n }\n return 'processing';\n }\n\n // Terminal failure/refund only for payment-in objects (Checkout Session,\n // PaymentIntent, Charge). Money-out / unrelated events (transfer.failed,\n // payout.failed, refund.failed, application_fee.refunded, …) also match a\n // naive substring scan — and a failed Transfer even carries our quoteId\n // (sendPayout stamps it), which would miscorrelate a payout failure as a\n // payment failure — so they must not surface as a terminal payment status.\n const isPaymentInEvent =\n type?.startsWith('checkout.session.') === true ||\n type?.startsWith('payment_intent.') === true ||\n type?.startsWith('charge.') === true;\n\n if (isPaymentInEvent && type?.includes('refunded')) {\n return 'refunded';\n }\n\n if (isPaymentInEvent && type?.includes('failed')) {\n return 'failed';\n }\n\n return 'processing';\n}\n\nfunction mapStripeRefundStatus(\n status: string | undefined,\n): RefundResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n case 'failed':\n case 'canceled':\n return 'failed';\n case 'requires_action':\n return 'requires_action';\n default:\n return 'submitted';\n }\n}\n\nfunction mapStripeAuthorizationStatus(\n status: string | undefined,\n): AuthorizationResult['status'] {\n switch (status) {\n case 'requires_capture':\n return 'requires_capture';\n case 'succeeded':\n return 'succeeded';\n case 'requires_action':\n return 'requires_action';\n case 'processing':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeCaptureStatus(\n status: string | undefined,\n): CaptureResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n // Capturing an authorized intent shouldn't re-enter authentication; treat\n // any in-flight/action state as still processing rather than a failure.\n case 'processing':\n case 'requires_action':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeVoidStatus(status: string | undefined): VoidResult['status'] {\n return status === 'canceled' ? 'canceled' : 'failed';\n}\n\nfunction readStripeResultCurrency(\n value: Record<string, unknown>,\n): string | undefined {\n const currency = readString(value, 'currency');\n\n return currency === undefined ? undefined : currency.toUpperCase();\n}\n\nfunction mapStripeSetupStatus(\n sessionStatus: string | undefined,\n setupIntentStatus: string | undefined,\n): SavedPaymentMethod['status'] {\n if (sessionStatus === 'expired') {\n return 'expired';\n }\n\n if (sessionStatus === 'complete') {\n // The method is reusable only once the SetupIntent itself has succeeded —\n // the Session can be `complete` while the intent is still `processing`\n // (async setup methods via dynamic payment methods).\n if (setupIntentStatus === 'succeeded') {\n return 'complete';\n }\n // A finished session whose SetupIntent didn't succeed is a terminal\n // failure (card declined → `requires_payment_method`, or `canceled`), so\n // callers can stop polling instead of waiting on a `pending` that will\n // never resolve. Still-in-flight states (`processing`, `requires_action`)\n // remain `pending`.\n if (\n setupIntentStatus === 'canceled' ||\n setupIntentStatus === 'requires_payment_method'\n ) {\n return 'failed';\n }\n }\n\n return 'pending';\n}\n\nfunction readObject(\n value: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n const item = value?.[key];\n\n return item && typeof item === 'object' && !Array.isArray(item)\n ? (item as Record<string, unknown>)\n : undefined;\n}\n\nfunction extractStripeSessionId(payTo: string): string | undefined {\n if (/^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(payTo)) {\n return payTo;\n }\n\n try {\n const url = new URL(payTo);\n const match = url.pathname.match(/\\/pay\\/([^/?#]+)/);\n\n const sessionId = match?.[1];\n\n return sessionId && /^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(sessionId)\n ? sessionId\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction flattenStripeMetadata(\n metadata:\n | Record<string, string | number | boolean | null | undefined>\n | undefined,\n): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(metadata ?? {})) {\n if (value !== undefined && value !== null) {\n result[`metadata[${key}]`] = value;\n }\n }\n\n return result;\n}\n\nfunction readString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n if (typeof item === 'string') {\n return item;\n }\n\n if (typeof item === 'number') {\n return String(item);\n }\n\n return undefined;\n}\n\nfunction readSafeInteger(\n value: Record<string, unknown> | undefined,\n key: string,\n): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'number' && Number.isSafeInteger(item) && item >= 0\n ? item\n : undefined;\n}\n"],"mappings":";;;;AAiDA,IAAa,oBAAoB;AACjC,IAAM,gCAAgC,OAAU;AAChD,IAAM,gCAAgC,OAAU,KAAK;AACrD,IAAM,6BAA6B;AACnC,IAAM,uCAAuC;AAkF7C,IAA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ACF;AAEA,SAAS,sBACP,UAG2C;CAC3C,MAAM,SAAoD,CAAC;CAE3D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,YAAY,CAAC,CAAC,GACtD,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,YAAY,IAAI,MAAM;CAIjC,OAAO;AACT;AAEA,SAAS,WACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,IAAI,OAAO,SAAS,UAClB,OAAO;CAGT,IAAI,OAAO,SAAS,UAClB,OAAO,OAAO,IAAI;AAItB;AAEA,SAAS,gBACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,OAAO,OAAO,SAAS,YAAY,OAAO,cAAc,IAAI,KAAK,QAAQ,IACrE,OACA,KAAA;AACN"}
1
+ {"version":3,"file":"stripe.js","names":[],"sources":["../../src/adapters/stripe.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n PaymentConfigurationError,\n PaymentNotOwnedError,\n PaymentProviderError,\n PaymentVerificationError,\n} from '../errors.js';\nimport {\n applyExpiryToPendingStatus,\n type FetchLike,\n formEncode,\n getFetch,\n normalizeDate,\n normalizeMaxStoredPaymentOptions,\n normalizeMinorUnitAmount,\n normalizeNonEmptyString,\n normalizePositiveMinorUnitAmount,\n normalizePositivePaymentAmount,\n normalizeUrlString,\n pollPaymentStatus,\n readJsonResponse,\n rememberPaymentOption,\n} from '../shared.js';\nimport type {\n AuthorizationResult,\n AuthorizePaymentInput,\n CapturePaymentInput,\n CaptureResult,\n CreatePaymentOptionInput,\n CreateSetupSessionInput,\n GetSetupResultInput,\n PaymentBackend,\n PaymentBackendCapabilities,\n PaymentEvent,\n PaymentOption,\n PaymentStatus,\n PaymentStatusContext,\n PaymentStatusResult,\n PaymentWebhookEvent,\n PayoutResult,\n RefundPaymentInput,\n RefundResult,\n SavedPaymentMethod,\n SendPayoutInput,\n SetupSession,\n VoidPaymentInput,\n VoidResult,\n WatchPaymentInput,\n} from '../types.js';\n\nexport const STRIPE_BACKEND_ID = 'stripe';\nconst STRIPE_CHECKOUT_MIN_EXPIRY_MS = 30 * 60 * 1_000;\nconst STRIPE_CHECKOUT_MAX_EXPIRY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_STRIPE_API_VERSION = '2024-06-20';\nconst DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS = 50_000;\n\nexport interface StripeAdapterOptions {\n secretKey: string;\n fetch?: FetchLike;\n apiBaseUrl?: string;\n apiVersion?: string;\n defaultCurrency?: string;\n supportedCurrencies?: string[];\n successUrl?: string;\n cancelUrl?: string;\n checkoutMode?: string;\n webhookSecret?: string;\n /**\n * Signing secret of the Stripe Connect webhook endpoint. Stripe signs\n * connected-account events with a different secret from the platform\n * endpoint; see {@link StripeAdapter.parseConnectWebhookEvent}.\n */\n connectWebhookSecret?: string;\n pollIntervalMs?: number;\n maxStoredPaymentOptions?: number;\n maxStoredWebhookEventIds?: number;\n /** Default Stripe Connect account for this adapter's provider requests. */\n stripeAccount?: string;\n}\n\n/** Stripe Connect account scope for a request; omit it for the platform. */\nexport interface StripeAccountScope {\n stripeAccount?: string;\n}\n\nexport interface StripeCreatePaymentOptionInput\n extends CreatePaymentOptionInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this direct charge. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripePaymentStatusContext\n extends PaymentStatusContext,\n StripeAccountScope {}\n\nexport interface StripeRefundPaymentInput\n extends RefundPaymentInput,\n StripeAccountScope {\n /** Refund a Stripe application fee collected with the charge. */\n refundApplicationFee?: boolean;\n /** Reverse a destination transfer when the provider supports one. */\n reverseTransfer?: boolean;\n}\n\nexport interface StripeAuthorizePaymentInput\n extends AuthorizePaymentInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this PaymentIntent. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripeCapturePaymentInput\n extends CapturePaymentInput,\n StripeAccountScope {}\n\nexport interface StripeVoidPaymentInput\n extends VoidPaymentInput,\n StripeAccountScope {}\n\nexport interface StripeCreateSetupSessionInput\n extends CreateSetupSessionInput,\n StripeAccountScope {}\n\nexport interface StripeGetSetupResultInput\n extends GetSetupResultInput,\n StripeAccountScope {}\n\nexport interface StripeWatchPaymentInput\n extends Omit<WatchPaymentInput, 'statusContext'> {\n statusContext?: StripePaymentStatusContext;\n}\n\nexport interface StripeWebhookEvent extends PaymentWebhookEvent {\n id: string;\n type: string;\n status: PaymentStatus;\n quoteId?: string;\n providerPaymentId?: string;\n /**\n * Connected account (`acct_...`) the event originated from. Set only on\n * events verified through {@link StripeAdapter.parseConnectWebhookEvent};\n * platform-endpoint events never carry it.\n */\n account?: string;\n /** Typed Connect payload for `account.updated` and `application_fee.*`. */\n connect?: StripeConnectEventDetail;\n raw: unknown;\n}\n\n/** A Connect endpoint event: always scoped to a connected account. */\nexport interface StripeConnectWebhookEvent extends StripeWebhookEvent {\n account: string;\n}\n\nexport type StripeConnectEventDetail =\n | {\n type: 'account.updated';\n account: StripeConnectAccountStatus;\n }\n | {\n type: 'application_fee.created' | 'application_fee.refunded';\n applicationFee: StripeApplicationFee;\n };\n\n/** Connected account onboarding and capability state. */\nexport interface StripeConnectAccountStatus {\n accountId: string;\n /** Stripe account type (`standard`, `express`, `custom`) when reported. */\n type?: string;\n /** Stripe `charges_enabled`. */\n chargesEnabled: boolean;\n /** Stripe `details_submitted`. */\n detailsSubmitted: boolean;\n /** Stripe `payouts_enabled`. */\n payoutsEnabled: boolean;\n /** Per-capability state, e.g. `{ card_payments: 'active' }`. */\n capabilities: Record<string, string>;\n requirements: {\n currentlyDue: string[];\n eventuallyDue: string[];\n pastDue: string[];\n disabledReason?: string;\n };\n country?: string;\n defaultCurrency?: string;\n raw: unknown;\n}\n\nexport interface StripeApplicationFee {\n id: string;\n /** Connected account the fee was collected from. */\n account?: string;\n /** Fee amount in integer minor units. */\n amount?: number;\n /** Refunded portion in integer minor units. */\n amountRefunded?: number;\n currency?: string;\n refunded: boolean;\n charge?: string;\n livemode?: boolean;\n raw: unknown;\n}\n\nexport interface StripeCreateStandardAccountInput {\n /** Two-letter ISO country code of the account holder. */\n country?: string;\n /** Prefills the account holder's email in Stripe onboarding. */\n email?: string;\n businessType?: 'individual' | 'company' | 'non_profit' | 'government_entity';\n metadata?: Record<string, string | number | boolean | null | undefined>;\n idempotencyKey?: string;\n}\n\nexport interface StripeOnboardingLink {\n /** Single-use Stripe-hosted onboarding URL; treat it as a bearer secret. */\n url: string;\n expiresAt?: Date;\n raw: unknown;\n}\n\nexport interface StripeCreateOnboardingLinkOptions {\n /** Which requirements to collect up front; Stripe defaults to `currently_due`. */\n collect?: 'currently_due' | 'eventually_due';\n idempotencyKey?: string;\n}\n\n/**\n * Host mapping from a connected account to its owner. Return `undefined` or\n * `null` for an account the host does not recognize; the event is then\n * rejected with {@link PaymentNotOwnedError}.\n */\nexport type StripeConnectAccountResolver<TOwner> = (\n account: string,\n event: StripeWebhookEvent,\n) => TOwner | null | undefined | Promise<TOwner | null | undefined>;\n\nexport interface StripeResolveConnectWebhookOptions<TOwner> {\n resolveAccount: StripeConnectAccountResolver<TOwner>;\n /**\n * Endpoint the delivery arrived on. `connect` (default) verifies with\n * `connectWebhookSecret` and routes by the event's `account`. `platform`\n * verifies with `webhookSecret` and routes `application_fee.*` events by the\n * fee's connected account; other platform events are rejected.\n */\n endpoint?: 'connect' | 'platform';\n}\n\nexport interface StripeResolvedConnectWebhookEvent<TOwner> {\n event: StripeWebhookEvent;\n /** Connected account the event was routed by. */\n account: string;\n owner: TOwner;\n}\n\nexport class StripeAdapter implements PaymentBackend {\n readonly capabilities: PaymentBackendCapabilities;\n\n private readonly fetch: FetchLike;\n private readonly secretKey: string;\n private readonly apiBaseUrl: string;\n private readonly apiVersion: string;\n private readonly defaultCurrency: string;\n private readonly supportedCurrencies: Set<string>;\n private readonly checkoutMode: string;\n private readonly webhookSecret: string | undefined;\n private readonly connectWebhookSecret: string | undefined;\n private readonly stripeAccount: string | undefined;\n private readonly maxStoredPaymentOptions: number;\n private readonly maxStoredWebhookEventIds: number;\n private readonly optionsByQuote = new Map<string, PaymentOption>();\n private readonly seenWebhookEventIds = new Set<string>();\n\n constructor(private readonly options: StripeAdapterOptions) {\n if (typeof options.secretKey !== 'string' || !options.secretKey.trim()) {\n throw new PaymentConfigurationError('StripeAdapter requires secretKey.');\n }\n\n assertOptionalSecret(options.webhookSecret, 'webhookSecret');\n assertOptionalSecret(options.connectWebhookSecret, 'connectWebhookSecret');\n\n if (options.apiBaseUrl !== undefined) {\n if (typeof options.apiBaseUrl !== 'string') {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must be a string when configured.',\n );\n }\n\n if (!options.apiBaseUrl.trim()) {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must not be empty when configured.',\n );\n }\n }\n\n this.fetch = getFetch(options.fetch);\n this.maxStoredPaymentOptions = normalizeMaxStoredPaymentOptions(\n options.maxStoredPaymentOptions,\n 'StripeAdapter maxStoredPaymentOptions',\n );\n this.maxStoredWebhookEventIds = normalizeMaxStoredPaymentOptions(\n options.maxStoredWebhookEventIds ?? DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS,\n 'StripeAdapter maxStoredWebhookEventIds',\n );\n this.secretKey = options.secretKey.trim();\n this.apiBaseUrl = normalizeUrlString(\n options.apiBaseUrl ?? 'https://api.stripe.com/v1',\n 'StripeAdapter apiBaseUrl',\n ).replace(/\\/$/, '');\n this.apiVersion = normalizeNonEmptyString(\n options.apiVersion ?? DEFAULT_STRIPE_API_VERSION,\n 'StripeAdapter apiVersion',\n );\n this.defaultCurrency = normalizeStripeCurrency(\n options.defaultCurrency ?? 'usd',\n );\n this.supportedCurrencies = normalizeSupportedStripeCurrencies(\n options.supportedCurrencies,\n this.defaultCurrency,\n );\n this.checkoutMode = options.checkoutMode ?? 'payment';\n\n if (this.checkoutMode !== 'payment') {\n throw new PaymentConfigurationError(\n 'StripeAdapter only supports payment Checkout mode.',\n );\n }\n\n this.webhookSecret = options.webhookSecret?.trim();\n this.connectWebhookSecret = options.connectWebhookSecret?.trim();\n this.stripeAccount = normalizeOptionalStripeAccount(\n options.stripeAccount,\n 'StripeAdapter stripeAccount',\n );\n this.capabilities = {\n id: STRIPE_BACKEND_ID,\n displayName: 'Stripe Checkout',\n settlementCurrency: this.defaultCurrency.toUpperCase(),\n supportedSettlementCurrencies: [...this.supportedCurrencies].map(\n (currency) => currency.toUpperCase(),\n ),\n chain: 'stripe',\n settlementShape: 'url',\n x402Capable: false,\n confirmationLatency: {\n expectedSeconds: 5,\n maxExpectedSeconds: 600,\n description:\n 'Card payments usually confirm in seconds; bank debits can remain processing while Stripe settles them.',\n },\n supportsRefunds: true,\n supportsPayouts: true,\n supportsWebhooks: true,\n supportsManualCapture: true,\n supportsSavedPaymentMethods: true,\n metadata: {\n provider: 'stripe',\n },\n };\n }\n\n async createPaymentOption(\n input: StripeCreatePaymentOptionInput,\n ): Promise<PaymentOption> {\n const quoteId = normalizeNonEmptyString(input.quoteId, 'Stripe quoteId');\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createPaymentOption requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe Checkout amount',\n );\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe Checkout applicationFeeAmount',\n );\n const expiresAt = normalizeDate(input.expiresAt);\n const stripeExpiresAt = normalizeStripeCheckoutExpiresAt(expiresAt);\n const params: Record<string, unknown> = {\n mode: this.checkoutMode,\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ['client_reference_id', quoteId],\n ['customer_email', input.buyerEmail],\n ['expires_at', Math.floor(stripeExpiresAt.getTime() / 1_000)],\n ]),\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': currency,\n 'line_items[0][price_data][unit_amount]': amount,\n 'line_items[0][price_data][product_data][name]':\n input.description ?? `Quote ${quoteId}`,\n ...(applicationFeeAmount === undefined\n ? {}\n : {\n 'payment_intent_data[application_fee_amount]': applicationFeeAmount,\n }),\n ...flattenStripeMetadata(input.metadata),\n 'metadata[quoteId]': quoteId,\n };\n\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(params),\n },\n );\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const checkoutUrl = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !checkoutUrl) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session response did not include id and url.',\n );\n }\n\n const option: PaymentOption = {\n backendId: this.capabilities.id,\n quoteId,\n payTo: checkoutUrl,\n settlementShape: 'url',\n settlementCurrency: currency.toUpperCase(),\n settlementAmount: amount,\n amount,\n currency: currency.toUpperCase(),\n expiresAt: stripeExpiresAt,\n providerPaymentId: sessionId,\n paymentUri: checkoutUrl,\n metadata: {\n sessionId,\n stripeAccount,\n paymentIntent: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n },\n };\n\n rememberPaymentOption(\n this.optionsByQuote,\n stripePaymentOptionKey(quoteId, stripeAccount),\n option,\n this.maxStoredPaymentOptions,\n );\n\n return option;\n }\n\n watchPayment(input: StripeWatchPaymentInput): AsyncIterable<PaymentEvent> {\n return pollPaymentStatus(\n {\n ...input,\n pollIntervalMs:\n input.pollIntervalMs ?? this.options.pollIntervalMs ?? 5_000,\n },\n () => this.getStatus(input.quoteId, input.payTo, input.statusContext),\n );\n }\n\n async getStatus(\n quoteId: string,\n payTo: string,\n context: StripePaymentStatusContext = {},\n ): Promise<PaymentStatusResult> {\n const normalizedQuoteId = normalizeNonEmptyString(\n quoteId,\n 'Stripe quoteId',\n );\n const normalizedPayTo = normalizeNonEmptyString(payTo, 'Stripe payTo');\n const contextProviderPaymentId =\n context.providerPaymentId === undefined\n ? undefined\n : normalizeNonEmptyString(\n context.providerPaymentId,\n 'Stripe providerPaymentId',\n );\n const contextStripeAccount = normalizeOptionalStripeAccount(\n context.stripeAccount,\n 'Stripe stripeAccount',\n );\n const scopedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(\n normalizedQuoteId,\n contextStripeAccount ?? this.stripeAccount,\n ),\n );\n const sessionId =\n contextProviderPaymentId ??\n extractStripeSessionId(normalizedPayTo) ??\n scopedOption?.providerPaymentId;\n\n if (!sessionId) {\n throw new PaymentConfigurationError(\n 'Stripe getStatus requires a Checkout Session id or URL.',\n );\n }\n\n const storedOption = this.findStoredOptionBySessionId(sessionId);\n const stripeAccount =\n contextStripeAccount ??\n readStripeOptionAccount(storedOption) ??\n this.stripeAccount;\n const cachedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(normalizedQuoteId, stripeAccount),\n );\n\n // A caller-supplied session id can deliberately select a later checkout\n // for the same quote. Cache-derived amount, currency, and expiry describe\n // only the session we created, never an explicitly selected replacement.\n const option =\n cachedOption?.providerPaymentId === sessionId ? cachedOption : undefined;\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}`,\n { stripeAccount },\n );\n const sessionQuoteId = readStripeSessionQuoteId(session);\n\n if (sessionQuoteId !== undefined && sessionQuoteId !== normalizedQuoteId) {\n throw new PaymentVerificationError(\n `Stripe Checkout Session quoteId ${sessionQuoteId} did not match ${normalizedQuoteId}.`,\n );\n }\n\n const paymentStatus = readString(session, 'payment_status');\n const status = mapStripeStatus(\n readString(session, 'status'),\n paymentStatus,\n );\n\n const contextAmount =\n context.amount === undefined\n ? undefined\n : normalizeMinorUnitAmount(context.amount, 'Stripe status');\n const contextCurrency =\n context.currency === undefined\n ? undefined\n : normalizeStripeCurrency(context.currency).toUpperCase();\n const sessionCurrency =\n readString(session, 'currency') === undefined\n ? undefined\n : normalizeStripeCurrency(\n readString(session, 'currency') ?? '',\n ).toUpperCase();\n const sessionAmount = readSafeInteger(session, 'amount_total');\n const expiresAt =\n option?.expiresAt ??\n (context.expiresAt === undefined\n ? undefined\n : normalizeDate(context.expiresAt));\n const effectiveStatus = applyExpiryToPendingStatus(status, expiresAt);\n\n return {\n backendId: this.capabilities.id,\n quoteId: normalizedQuoteId,\n payTo: normalizedPayTo,\n status: effectiveStatus,\n settlementCurrency:\n sessionCurrency ??\n option?.settlementCurrency ??\n contextCurrency ??\n this.defaultCurrency.toUpperCase(),\n settlementAmount:\n sessionAmount ?? option?.settlementAmount ?? contextAmount,\n receivedAmount:\n paymentStatus === 'paid' || paymentStatus === 'no_payment_required'\n ? (sessionAmount ?? option?.settlementAmount ?? contextAmount)\n : undefined,\n amount: option?.amount ?? contextAmount,\n currency: option?.currency ?? contextCurrency,\n providerPaymentId: sessionId,\n transactionId: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n updatedAt: new Date(),\n raw: session,\n };\n }\n\n async sendPayout(input: SendPayoutInput): Promise<PayoutResult> {\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const destination = normalizeNonEmptyString(\n input.destination,\n 'Stripe payout destination',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe payout quoteId');\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe payout amount',\n );\n const transfer = await this.stripeRequest<Record<string, unknown>>(\n '/transfers',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n amount,\n currency,\n destination,\n description: input.memo,\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: 'submitted',\n payoutId: normalizeOptionalProviderString(\n readProviderString(transfer, 'id'),\n ),\n destination,\n amount,\n currency: currency.toUpperCase(),\n raw: transfer,\n };\n }\n\n async refundPayment(input: StripeRefundPaymentInput): Promise<RefundResult> {\n const rawPaymentReference = input.paymentId ?? input.transactionId;\n\n if (!rawPaymentReference) {\n throw new PaymentConfigurationError(\n 'Stripe refunds require paymentId or transactionId.',\n );\n }\n\n const paymentReference = normalizeNonEmptyString(\n rawPaymentReference,\n 'Stripe refund payment reference',\n );\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe refund amount',\n );\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const refundReferenceParam = await this.resolveStripeRefundReferenceParam(\n paymentReference,\n stripeAccount,\n );\n const refundParams: Record<string, unknown> = {\n ...refundReferenceParam,\n amount: amount === undefined ? undefined : amount,\n reason: input.reason,\n refund_application_fee: input.refundApplicationFee,\n reverse_transfer: input.reverseTransfer,\n ...flattenStripeMetadata(input.metadata),\n };\n\n const refund = await this.stripeRequest<Record<string, unknown>>(\n '/refunds',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(refundParams),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeRefundStatus(readString(refund, 'status')),\n refundId: normalizeOptionalProviderString(\n readProviderString(refund, 'id'),\n ),\n transactionId: paymentReference,\n // Read the settled amount and currency back from the refund object\n // (mirrors capturePayment) so a full refund — no `input.amount` supplied,\n // and possibly a currency differing from the adapter default when\n // `input.currency` is omitted — surfaces what Stripe actually refunded\n // instead of the request defaults.\n amount: readSafeInteger(refund, 'amount') ?? amount,\n currency: readStripeResultCurrency(refund) ?? currency.toUpperCase(),\n raw: refund,\n };\n }\n\n async authorizePayment(\n input: StripeAuthorizePaymentInput,\n ): Promise<AuthorizationResult> {\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe authorize amount',\n );\n const paymentMethod = normalizeNonEmptyString(\n input.providerPaymentMethodId,\n 'Stripe authorize providerPaymentMethodId',\n );\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe authorize providerCustomerId',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe authorize quoteId');\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe PaymentIntent applicationFeeAmount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n '/payment_intents',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n amount,\n currency,\n confirm: true,\n 'payment_method_types[]': 'card',\n description: input.description,\n application_fee_amount: applicationFeeAmount,\n ...Object.fromEntries([\n ['payment_method', paymentMethod],\n ['capture_method', 'manual'],\n // Off-session (merchant-initiated) by default — the primary use is\n // charging a saved card while the buyer is absent. Without this,\n // Stripe treats it as on-session and may raise an SCA challenge the\n // absent buyer can't complete, so the hold is never placed.\n ['off_session', input.offSession ?? true],\n ]),\n ...(providerCustomerId === undefined\n ? {}\n : { customer: providerCustomerId }),\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n const providerPaymentId = normalizeOptionalProviderString(\n readProviderString(intent, 'id'),\n );\n\n if (!providerPaymentId) {\n throw new PaymentProviderError(\n 'Stripe PaymentIntent response did not include an id.',\n );\n }\n\n const status = mapStripeAuthorizationStatus(readString(intent, 'status'));\n // Only surface the SCA fields when authentication is actually required — the\n // documented contract — even though Stripe returns client_secret regardless.\n // (Authorization progress is observed via `parseWebhookEvent`, which surfaces\n // the ready-to-capture transition as `processing` — there is no distinct\n // `requires_capture` webhook status; `getStatus` handles Checkout sessions,\n // not PaymentIntents.)\n const actionRequired = status === 'requires_action';\n\n return {\n backendId: this.capabilities.id,\n status,\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount') ?? amount,\n currency: (readString(intent, 'currency') ?? currency).toUpperCase(),\n clientSecret: actionRequired\n ? normalizeOptionalProviderString(\n readProviderString(intent, 'client_secret'),\n )\n : undefined,\n nextAction: actionRequired\n ? (intent.next_action ?? undefined)\n : undefined,\n raw: intent,\n };\n }\n\n async capturePayment(\n input: StripeCapturePaymentInput,\n ): Promise<CaptureResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe capture providerPaymentId',\n );\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositiveMinorUnitAmount(\n input.amount,\n 'Stripe capture amount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/capture`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n ...Object.fromEntries([['amount_to_capture', amount]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeCaptureStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount:\n readSafeInteger(intent, 'amount_received') ??\n readSafeInteger(intent, 'amount') ??\n amount,\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async voidPayment(input: StripeVoidPaymentInput): Promise<VoidResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe void providerPaymentId',\n );\n const reason =\n input.reason === undefined\n ? undefined\n : normalizeNonEmptyString(input.reason, 'Stripe void reason');\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/cancel`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(Object.fromEntries([['cancellation_reason', reason]])),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeVoidStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount'),\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async createSetupSession(\n input: StripeCreateSetupSessionInput,\n ): Promise<SetupSession> {\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createSetupSession requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n // Currency for the setup-mode session (defaults to the backend currency).\n // Redundant now that payment_method_types is always set, but harmless and\n // kept so the session is well-formed if that restriction is ever relaxed.\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe setup customer',\n );\n\n // Either attach to an existing customer, or force Stripe to create one so\n // the saved method comes back with a reusable `cus_` reference. Setup-mode\n // sessions do NOT create a customer on their own — `customer_creation` must\n // be `always`. All snake_case keys go through Object.fromEntries.\n const customerParams: [string, unknown][] = [];\n if (providerCustomerId !== undefined) {\n customerParams.push(['customer', providerCustomerId]);\n } else {\n customerParams.push(['customer_creation', 'always']);\n if (input.customerEmail !== undefined) {\n customerParams.push([\n 'customer_email',\n normalizeNonEmptyString(\n input.customerEmail,\n 'Stripe setup customerEmail',\n ),\n ]);\n }\n }\n\n const params: Record<string, unknown> = {\n mode: 'setup',\n currency,\n // Restrict to cards: SavedPaymentMethod exposes card display fields\n // (brand/last4/expiry), so allowing SEPA/Bacs/etc. would yield saved\n // methods with no usable display detail.\n 'payment_method_types[]': 'card',\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ...customerParams,\n ]),\n ...flattenStripeMetadata(input.metadata),\n };\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(params),\n },\n );\n\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const url = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !url) {\n throw new PaymentProviderError(\n 'Stripe setup Checkout Session response did not include id and url.',\n );\n }\n\n return {\n backendId: this.capabilities.id,\n sessionId,\n url,\n providerCustomerId:\n providerCustomerId ??\n normalizeOptionalProviderString(\n readProviderString(session, 'customer'),\n ),\n raw: session,\n };\n }\n\n async getSetupResult(\n input: StripeGetSetupResultInput,\n ): Promise<SavedPaymentMethod> {\n const sessionId = normalizeNonEmptyString(\n input.sessionId,\n 'Stripe setup sessionId',\n );\n\n const query = new URLSearchParams();\n query.append('expand[]', 'setup_intent.payment_method');\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}?${query.toString()}`,\n { stripeAccount: this.resolveStripeAccount(input.stripeAccount) },\n );\n\n const setupIntent = readObject(session, 'setup_intent');\n const paymentMethod = readObject(setupIntent, 'payment_method');\n const card = readObject(paymentMethod, 'card');\n\n // `customer` is a bare `cus_` string on the request path (only\n // setup_intent.payment_method is expanded), but read tolerantly of an\n // expanded object so a future `expand[]=customer` can't wrongly downgrade a\n // completed setup to a permanent `pending`.\n const providerCustomerId = normalizeOptionalProviderString(\n readProviderString(session, 'customer') ??\n readProviderString(readObject(session, 'customer'), 'id'),\n );\n const providerPaymentMethodId = normalizeOptionalProviderString(\n readProviderString(paymentMethod, 'id'),\n );\n\n let status = mapStripeSetupStatus(\n readString(session, 'status'),\n readString(setupIntent, 'status'),\n );\n // Never report `complete` without the reusable references a caller needs to\n // charge the method later — a `pm_` with no `cus_` can't be charged\n // off-session, so treat that as not-yet-ready rather than a false success.\n if (\n status === 'complete' &&\n (!providerCustomerId || !providerPaymentMethodId)\n ) {\n status = 'pending';\n }\n\n return {\n backendId: this.capabilities.id,\n status,\n providerCustomerId,\n providerPaymentMethodId,\n type: readString(paymentMethod, 'type'),\n brand: readString(card, 'brand'),\n last4: readString(card, 'last4'),\n expMonth: readSafeInteger(card, 'exp_month'),\n expYear: readSafeInteger(card, 'exp_year'),\n raw: session,\n };\n }\n\n /**\n * Verify and parse a delivery to the platform webhook endpoint. Events that\n * carry a connected `account` are rejected: they belong to the Connect\n * endpoint and must never be processed as platform-account events.\n */\n parseWebhookEvent(payload: string, signature?: string): StripeWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'platform');\n this.recordWebhookEvent(event);\n return event;\n }\n\n /**\n * Verify a Stripe Connect endpoint delivery with `connectWebhookSecret`,\n * then parse it. The signature is checked before the payload is parsed, and\n * an event without a connected `account` is rejected. When this adapter is\n * scoped to a `stripeAccount`, events for any other account are rejected.\n * The payload, including `quoteId`, is controlled by the connected account:\n * bind `quoteId` to `account` before acting on it.\n */\n parseConnectWebhookEvent(\n payload: string,\n signature?: string,\n ): StripeConnectWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'connect');\n this.recordWebhookEvent(event);\n return event as StripeConnectWebhookEvent;\n }\n\n /**\n * Verify a webhook delivery, then map its connected account to an owner\n * (for example a tenant) with the host's resolver. An account the resolver\n * does not recognize is rejected with {@link PaymentNotOwnedError}; there is\n * no fallback to the platform account. The event is recorded for duplicate\n * detection only after it resolves, so a retried delivery that failed to\n * resolve is not reported as a duplicate.\n *\n * Security: a connected account controls the objects it creates, so a\n * Connect event's `quoteId` (and every other payload field) is chosen by\n * that account. Resolving the account proves only who sent the event. The\n * host must check that `event.quoteId` belongs to the resolved owner (for\n * example inside `resolveAccount`, which receives the event, or before\n * settling) and must never settle another owner's quote from it.\n */\n async resolveConnectWebhookEvent<TOwner>(\n payload: string,\n signature: string | undefined,\n options: StripeResolveConnectWebhookOptions<TOwner>,\n ): Promise<StripeResolvedConnectWebhookEvent<TOwner>> {\n if (typeof options?.resolveAccount !== 'function') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent requires a resolveAccount function.',\n );\n }\n\n const endpoint = options.endpoint ?? 'connect';\n\n if (endpoint !== 'connect' && endpoint !== 'platform') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent endpoint must be connect or platform.',\n );\n }\n\n const event = this.verifyWebhookEvent(payload, signature, endpoint);\n const account =\n endpoint === 'connect'\n ? event.account\n : event.connect?.type === 'application_fee.created' ||\n event.connect?.type === 'application_fee.refunded'\n ? event.connect.applicationFee.account\n : undefined;\n\n if (account === undefined) {\n throw new PaymentNotOwnedError(\n `Stripe webhook event ${event.id} (${event.type}) has no connected account to route by.`,\n );\n }\n\n this.assertAdapterAccount(account);\n const owner = await options.resolveAccount(account, event);\n\n if (owner === undefined || owner === null) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} is not mapped to an owner.`,\n );\n }\n\n this.recordWebhookEvent(event);\n return { event, account, owner };\n }\n\n /**\n * Create a Stripe Connect **Standard** account. The account holder owns the\n * Stripe relationship and dashboard; the platform only connects to it.\n * Always issued on the platform account, never on a connected account.\n */\n async createStandardAccount(\n input: StripeCreateStandardAccountInput = {},\n ): Promise<StripeConnectAccountStatus> {\n const country =\n input.country === undefined\n ? undefined\n : normalizeStripeCountry(input.country);\n const email =\n input.email === undefined\n ? undefined\n : normalizeNonEmptyString(input.email, 'Stripe account email');\n const account = await this.stripeRequest<Record<string, unknown>>(\n '/accounts',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n type: 'standard',\n country,\n email,\n ...Object.fromEntries([['business_type', input.businessType]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return mapStripeConnectAccount(account, 'Stripe account response');\n }\n\n /**\n * Create a single-use Account Link that sends the account holder through\n * Stripe-hosted onboarding. `refreshUrl` is visited when the link expires or\n * is reused, and should mint a new link; `returnUrl` does not mean\n * onboarding finished, so read {@link getAccountCapabilities} afterwards.\n */\n async createOnboardingLink(\n accountId: string,\n returnUrl: string,\n refreshUrl: string,\n options: StripeCreateOnboardingLinkOptions = {},\n ): Promise<StripeOnboardingLink> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const link = await this.stripeRequest<Record<string, unknown>>(\n '/account_links',\n {\n method: 'POST',\n idempotencyKey: options.idempotencyKey,\n body: formEncode({\n account,\n type: 'account_onboarding',\n collect: options.collect,\n ...Object.fromEntries([\n ['return_url', normalizeUrlString(returnUrl, 'Stripe returnUrl')],\n [\n 'refresh_url',\n normalizeUrlString(refreshUrl, 'Stripe refreshUrl'),\n ],\n ]),\n }),\n },\n );\n const url = normalizeOptionalProviderString(\n readProviderString(link, 'url'),\n );\n\n if (!url) {\n throw new PaymentProviderError(\n 'Stripe Account Link response did not include a url.',\n );\n }\n\n const expiresAtSeconds = readSafeInteger(link, 'expires_at');\n\n return {\n url,\n expiresAt:\n expiresAtSeconds === undefined\n ? undefined\n : new Date(expiresAtSeconds * 1_000),\n raw: link,\n };\n }\n\n /**\n * Read a connected account's onboarding and capability state\n * (`charges_enabled`, `details_submitted`, `payouts_enabled`, per-capability\n * status, and outstanding requirements).\n */\n async getAccountCapabilities(\n accountId: string,\n ): Promise<StripeConnectAccountStatus> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const response = await this.stripeRequest<Record<string, unknown>>(\n `/accounts/${encodeURIComponent(account)}`,\n );\n const status = mapStripeConnectAccount(response, 'Stripe account response');\n\n if (status.accountId !== account) {\n throw new PaymentVerificationError(\n `Stripe account response ${status.accountId} did not match ${account}.`,\n );\n }\n\n return status;\n }\n\n private verifyWebhookEvent(\n payload: string,\n signature: string | undefined,\n endpoint: 'connect' | 'platform',\n ): StripeWebhookEvent {\n const secret =\n endpoint === 'connect' ? this.connectWebhookSecret : this.webhookSecret;\n\n if (!secret) {\n throw new PaymentConfigurationError(\n endpoint === 'connect'\n ? 'StripeAdapter parseConnectWebhookEvent requires connectWebhookSecret.'\n : 'StripeAdapter parseWebhookEvent requires webhookSecret.',\n );\n }\n\n if (!signature) {\n throw new PaymentProviderError('Missing Stripe webhook signature.');\n }\n\n // Authenticate the raw bytes before anything reads the payload.\n verifyStripeWebhookSignature(payload, signature, secret);\n\n const event = parseStripeWebhookPayload(payload);\n const id = readRequiredWebhookString(\n event,\n 'id',\n 'Stripe webhook event id',\n );\n const type = readRequiredWebhookString(\n event,\n 'type',\n 'Stripe webhook event type',\n );\n const rawAccount = event.account;\n let account: string | undefined;\n\n if (endpoint === 'connect') {\n account = typeof rawAccount === 'string' ? rawAccount.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentVerificationError(\n 'Stripe Connect webhook event did not include a valid connected account.',\n );\n }\n\n this.assertAdapterAccount(account);\n } else if (rawAccount !== undefined && rawAccount !== null) {\n throw new PaymentVerificationError(\n 'Stripe connected-account event received on the platform webhook endpoint; verify it with parseConnectWebhookEvent.',\n );\n }\n\n const data = (\n event.data as { object?: Record<string, unknown> } | undefined\n )?.object;\n const connect = mapStripeConnectEventDetail(type, data);\n\n if (\n account !== undefined &&\n connect?.type === 'account.updated' &&\n connect.account.accountId !== account\n ) {\n throw new PaymentVerificationError(\n 'Stripe account.updated webhook object did not match the event account.',\n );\n }\n\n return {\n id,\n type,\n status: mapStripeWebhookStatus(type, data),\n quoteId: normalizeOptionalWebhookString(\n // `client_reference_id` is a Checkout Session-only field; honor it only\n // for session events so a non-session object (a PaymentIntent / Charge /\n // Transfer, possibly from a malicious Connect account) can't spoof\n // correlation to another quote's id. Non-session events correlate only\n // via our own `metadata.quoteId`.\n (type.startsWith('checkout.session.')\n ? readString(data, 'client_reference_id')\n : undefined) ??\n readString(\n (data?.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n ),\n providerPaymentId: normalizeOptionalWebhookString(readString(data, 'id')),\n duplicate: this.seenWebhookEventIds.has(id),\n ...(account === undefined ? {} : { account }),\n ...(connect === undefined ? {} : { connect }),\n raw: event,\n };\n }\n\n private recordWebhookEvent(event: StripeWebhookEvent): void {\n if (this.seenWebhookEventIds.has(event.id)) {\n event.duplicate = true;\n return;\n }\n\n event.duplicate = false;\n this.seenWebhookEventIds.add(event.id);\n while (this.seenWebhookEventIds.size > this.maxStoredWebhookEventIds) {\n const oldest = this.seenWebhookEventIds.values().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n this.seenWebhookEventIds.delete(oldest);\n }\n }\n\n private assertAdapterAccount(account: string): void {\n if (this.stripeAccount !== undefined && account !== this.stripeAccount) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} does not match this adapter's account scope.`,\n );\n }\n }\n\n private async stripeRequest<T>(\n path: string,\n init: RequestInit & {\n idempotencyKey?: string;\n stripeAccount?: string;\n } = {},\n ): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.secretKey}`);\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n headers.set('Accept', 'application/json');\n headers.set('Stripe-Version', this.apiVersion);\n\n if (init.stripeAccount !== undefined) {\n headers.set('Stripe-Account', init.stripeAccount);\n }\n\n if (init.idempotencyKey !== undefined) {\n headers.set(\n 'Idempotency-Key',\n normalizeNonEmptyString(init.idempotencyKey, 'Stripe idempotencyKey'),\n );\n }\n\n const {\n idempotencyKey: _idempotencyKey,\n stripeAccount: _stripeAccount,\n ...requestInit\n } = init;\n const response = await this.fetch(`${this.apiBaseUrl}${path}`, {\n ...requestInit,\n method: init.method ?? 'GET',\n headers,\n });\n\n return readJsonResponse<T>(response, `Stripe ${path}`);\n }\n\n private assertSupportedCurrency(currency: string): void {\n if (!this.supportedCurrencies.has(currency)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency ${currency.toUpperCase()} is not configured as supported.`,\n );\n }\n }\n\n private async resolveStripeRefundReferenceParam(\n paymentReference: string,\n stripeAccount: string | undefined,\n ): Promise<Record<string, string>> {\n if (paymentReference.startsWith('cs_')) {\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(paymentReference)}`,\n { stripeAccount },\n );\n const paymentIntent = normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n );\n\n if (!paymentIntent) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session did not include payment_intent for refund.',\n );\n }\n\n return Object.fromEntries([['payment_intent', paymentIntent]]);\n }\n\n return stripeRefundReferenceParam(paymentReference);\n }\n\n private resolveStripeAccount(\n override: string | undefined,\n ): string | undefined {\n return (\n normalizeOptionalStripeAccount(override, 'Stripe stripeAccount') ??\n this.stripeAccount\n );\n }\n\n private findStoredOptionBySessionId(\n sessionId: string,\n ): PaymentOption | undefined {\n for (const option of this.optionsByQuote.values()) {\n if (option.providerPaymentId === sessionId) return option;\n }\n return undefined;\n }\n}\n\nfunction assertOptionalSecret(value: unknown, name: string): void {\n if (value === undefined) return;\n\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must be a string when configured.`,\n );\n }\n\n if (!value.trim()) {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must not be empty when configured.`,\n );\n }\n}\n\nconst STRIPE_CONNECTED_ACCOUNT_ID = /^acct_[A-Za-z0-9]+$/;\n\nfunction normalizeStripeConnectedAccountId(value: unknown): string {\n const account = typeof value === 'string' ? value.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentConfigurationError(\n 'Stripe connected account id must look like acct_...',\n );\n }\n\n return account;\n}\n\nfunction normalizeStripeCountry(value: string): string {\n const country = typeof value === 'string' ? value.trim().toUpperCase() : '';\n\n if (!/^[A-Z]{2}$/.test(country)) {\n throw new PaymentConfigurationError(\n 'Stripe account country must be a two-letter ISO country code.',\n );\n }\n\n return country;\n}\n\nfunction readStringArray(\n value: Record<string, unknown> | undefined,\n key: string,\n): string[] {\n const item = value?.[key];\n\n return Array.isArray(item)\n ? item.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\nfunction mapStripeConnectAccount(\n account: Record<string, unknown> | undefined,\n context: string,\n): StripeConnectAccountStatus {\n const accountId = readProviderString(account, 'id')?.trim();\n\n if (!account || !accountId || !STRIPE_CONNECTED_ACCOUNT_ID.test(accountId)) {\n throw new PaymentProviderError(`${context} did not include an account id.`);\n }\n\n const capabilities: Record<string, string> = {};\n\n for (const [name, state] of Object.entries(\n readObject(account, 'capabilities') ?? {},\n )) {\n if (typeof state === 'string') {\n capabilities[name] = state;\n }\n }\n\n const requirements = readObject(account, 'requirements');\n const disabledReason = normalizeOptionalProviderString(\n readProviderString(requirements, 'disabled_reason'),\n );\n const defaultCurrency = readProviderString(account, 'default_currency');\n\n return {\n accountId,\n type: normalizeOptionalProviderString(readProviderString(account, 'type')),\n chargesEnabled: account.charges_enabled === true,\n detailsSubmitted: account.details_submitted === true,\n payoutsEnabled: account.payouts_enabled === true,\n capabilities,\n requirements: {\n currentlyDue: readStringArray(requirements, 'currently_due'),\n eventuallyDue: readStringArray(requirements, 'eventually_due'),\n pastDue: readStringArray(requirements, 'past_due'),\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n country: normalizeOptionalProviderString(\n readProviderString(account, 'country'),\n ),\n defaultCurrency: defaultCurrency?.toUpperCase(),\n raw: account,\n };\n}\n\nfunction mapStripeApplicationFee(\n fee: Record<string, unknown> | undefined,\n): StripeApplicationFee {\n const id = normalizeOptionalProviderString(readProviderString(fee, 'id'));\n\n if (!fee || !id) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object did not include an id.',\n );\n }\n\n const account = normalizeOptionalProviderString(\n readProviderString(fee, 'account'),\n );\n\n if (account !== undefined && !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object has an invalid account id.',\n );\n }\n const livemode = fee.livemode;\n\n return {\n id,\n account,\n amount: readSafeInteger(fee, 'amount'),\n amountRefunded: readSafeInteger(fee, 'amount_refunded'),\n currency: readStripeResultCurrency(fee),\n refunded: fee.refunded === true,\n charge: normalizeOptionalProviderString(\n readProviderString(fee, 'charge') ??\n readProviderString(readObject(fee, 'charge'), 'id'),\n ),\n livemode: typeof livemode === 'boolean' ? livemode : undefined,\n raw: fee,\n };\n}\n\nfunction mapStripeConnectEventDetail(\n type: string,\n object: Record<string, unknown> | undefined,\n): StripeConnectEventDetail | undefined {\n if (type === 'account.updated') {\n return {\n type,\n account: mapStripeConnectAccount(\n object,\n 'Stripe account.updated webhook object',\n ),\n };\n }\n\n if (\n type === 'application_fee.created' ||\n type === 'application_fee.refunded'\n ) {\n return { type, applicationFee: mapStripeApplicationFee(object) };\n }\n\n return undefined;\n}\n\nfunction readStripeOptionAccount(\n option: PaymentOption | undefined,\n): string | undefined {\n const value = option?.metadata?.stripeAccount;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction normalizeOptionalStripeAccount(\n value: string | undefined,\n context: string,\n): string | undefined {\n return value === undefined\n ? undefined\n : normalizeNonEmptyString(value, context);\n}\n\nfunction normalizeApplicationFeeAmount(\n value: number | undefined,\n chargeAmount: number,\n context: string,\n): number | undefined {\n if (value === undefined) return undefined;\n\n const fee = normalizePositiveMinorUnitAmount(value, context);\n if (fee > chargeAmount) {\n throw new PaymentConfigurationError(\n `${context} must not exceed the charge amount.`,\n );\n }\n return fee;\n}\n\nfunction stripePaymentOptionKey(\n quoteId: string,\n stripeAccount: string | undefined,\n): string {\n // Platform entries retain their old quote-only keys. Connected-account ids\n // cannot contain NUL in an HTTP header, so it safely separates account scope\n // from the caller's quote id without collapsing tenant-local quote ids.\n return stripeAccount === undefined ? quoteId : `${stripeAccount}\\0${quoteId}`;\n}\n\nfunction stripeRefundReferenceParam(\n paymentReference: string,\n): Record<string, string> {\n if (paymentReference.startsWith('pi_')) {\n return Object.fromEntries([['payment_intent', paymentReference]]);\n }\n\n if (paymentReference.startsWith('ch_')) {\n return { charge: paymentReference };\n }\n\n throw new PaymentConfigurationError(\n 'Stripe refunds require a Checkout Session (cs_), payment_intent (pi_), or charge (ch_) reference.',\n );\n}\n\nfunction normalizeStripeCurrency(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (!/^[a-z]{3}$/.test(normalized)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizeSupportedStripeCurrencies(\n configuredCurrencies: string[] | undefined,\n defaultCurrency: string,\n): Set<string> {\n const normalized = new Set(\n (configuredCurrencies ?? ['usd', 'eur', 'gbp', 'cad']).map(\n normalizeStripeCurrency,\n ),\n );\n normalized.add(defaultCurrency);\n\n return normalized;\n}\n\nfunction normalizeStripeCheckoutExpiresAt(\n expiresAt: Date,\n now = Date.now(),\n): Date {\n if (expiresAt.getTime() <= now) {\n throw new PaymentProviderError('Stripe Checkout expiry is in the past.');\n }\n\n const min = now + STRIPE_CHECKOUT_MIN_EXPIRY_MS;\n const max = now + STRIPE_CHECKOUT_MAX_EXPIRY_MS;\n\n if (expiresAt.getTime() < min || expiresAt.getTime() > max) {\n throw new PaymentConfigurationError(\n 'Stripe Checkout expiry must be at least 30 minutes and no more than 24 hours from now.',\n );\n }\n\n return expiresAt;\n}\n\nexport function verifyStripeWebhookSignature(\n payload: string,\n signatureHeader: string,\n secret: string,\n toleranceSeconds = 300,\n): void {\n if (typeof payload !== 'string') {\n throw new PaymentProviderError('Stripe webhook payload must be a string.');\n }\n\n const normalizedSignatureHeader = normalizeNonEmptyString(\n signatureHeader,\n 'Stripe signature header',\n );\n const normalizedSecret = normalizeNonEmptyString(\n secret,\n 'Stripe webhook secret',\n );\n\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {\n throw new PaymentConfigurationError(\n `Stripe webhook toleranceSeconds must be a non-negative finite number, received ${String(toleranceSeconds)}.`,\n );\n }\n\n const timestampCandidates: string[] = [];\n const signatures: string[] = [];\n\n for (const part of normalizedSignatureHeader.split(',')) {\n const [rawKey, ...rawValue] = part.split('=');\n const key = rawKey?.trim();\n const value = rawValue.join('=').trim();\n\n if (!key || !value) {\n continue;\n }\n\n if (key === 't') {\n timestampCandidates.push(value);\n }\n\n if (key === 'v1') {\n signatures.push(value);\n }\n }\n\n if (timestampCandidates.length !== 1 || signatures.length === 0) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestamp = timestampCandidates[0] ?? '';\n\n if (!/^\\d+$/.test(timestamp)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestampSeconds = Number(timestamp);\n\n if (!Number.isSafeInteger(timestampSeconds)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const nowSeconds = Date.now() / 1_000;\n const ageSeconds = nowSeconds - timestampSeconds;\n\n if (ageSeconds < -5) {\n throw new PaymentProviderError(\n 'Stripe webhook signature timestamp is in the future.',\n );\n }\n\n if (ageSeconds > toleranceSeconds) {\n throw new PaymentProviderError('Stripe webhook signature is too old.');\n }\n\n const expected = createHmac('sha256', normalizedSecret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n const expectedBuffer = Buffer.from(expected, 'hex');\n\n for (const signature of signatures) {\n if (!/^[0-9a-f]+$/i.test(signature)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const actualBuffer = Buffer.from(signature, 'hex');\n\n if (\n expectedBuffer.length === actualBuffer.length &&\n timingSafeEqual(expectedBuffer, actualBuffer)\n ) {\n return;\n }\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook signature.');\n}\n\nfunction parseStripeWebhookPayload(payload: string): Record<string, unknown> {\n try {\n const event = JSON.parse(payload);\n\n if (!event || typeof event !== 'object' || Array.isArray(event)) {\n throw new PaymentProviderError('Invalid Stripe webhook JSON payload.');\n }\n\n return event as Record<string, unknown>;\n } catch (error) {\n if (error instanceof PaymentProviderError) {\n throw error;\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook JSON payload.', {\n cause: error,\n });\n }\n}\n\nfunction normalizeOptionalWebhookString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction normalizeOptionalProviderString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction readProviderString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'string' ? item : undefined;\n}\n\nfunction readRequiredWebhookString(\n value: Record<string, unknown>,\n key: string,\n context: string,\n): string {\n const item = value[key];\n\n if (typeof item !== 'string') {\n throw new PaymentProviderError(`${context} must be a string.`);\n }\n\n return normalizeNonEmptyString(item, context);\n}\n\nfunction readStripeSessionQuoteId(\n session: Record<string, unknown>,\n): string | undefined {\n return normalizeOptionalWebhookString(\n readString(session, 'client_reference_id') ??\n readString(\n (session.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n );\n}\n\nfunction mapStripeStatus(\n checkoutStatus: string | undefined,\n paymentStatus: string | undefined,\n): PaymentStatus {\n if (paymentStatus === 'paid' || paymentStatus === 'no_payment_required') {\n return 'confirmed';\n }\n\n if (checkoutStatus === 'expired') {\n return 'expired';\n }\n\n if (paymentStatus === 'unpaid' || checkoutStatus === 'open') {\n return 'pending';\n }\n\n if (checkoutStatus === 'complete') {\n return 'processing';\n }\n\n return 'pending';\n}\n\nfunction mapStripeWebhookStatus(\n type: string | undefined,\n object: Record<string, unknown> | undefined,\n): PaymentStatus {\n if (type === 'checkout.session.completed') {\n return mapStripeStatus(\n readString(object, 'status'),\n readString(object, 'payment_status'),\n );\n }\n\n if (type === 'checkout.session.async_payment_succeeded') {\n return 'confirmed';\n }\n\n if (type === 'checkout.session.async_payment_failed') {\n return 'failed';\n }\n\n if (type === 'checkout.session.expired') {\n return 'expired';\n }\n\n // Manual-capture PaymentIntent lifecycle (authorize → capture / void). Only\n // treat these as terminal for intents WE created and can correlate — i.e.\n // ones carrying our `quoteId` in metadata. Checkout Sessions create their own\n // PaymentIntents (which fire these same events with no quoteId on the intent);\n // those are handled via the `checkout.session.*` events above, so here they\n // stay non-terminal (`processing`) rather than emitting a spurious,\n // uncorrelatable terminal event. Handled before the generic `failed` catch\n // below so an un-owned `payment_intent.payment_failed` isn't reclassified.\n if (\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.canceled' ||\n type === 'payment_intent.payment_failed'\n ) {\n const metadata = (object?.metadata as Record<string, unknown>) ?? {};\n // Match parseWebhookEvent's normalization so an empty/blank quoteId is\n // treated as un-owned by both — gate and reporter must agree on ownership.\n const owned =\n normalizeOptionalWebhookString(readString(metadata, 'quoteId')) !==\n undefined;\n if (owned) {\n if (type === 'payment_intent.succeeded') {\n return 'confirmed';\n }\n // A manual-capture hold Stripe released automatically (it lapsed) is\n // `expired`, distinct from a deliberate void or hard decline (`failed`);\n // the shared PaymentStatus union has no `canceled`.\n if (\n type === 'payment_intent.canceled' &&\n readString(object, 'cancellation_reason') === 'automatic'\n ) {\n return 'expired';\n }\n return 'failed';\n }\n return 'processing';\n }\n\n // Terminal failure/refund only for payment-in objects (Checkout Session,\n // PaymentIntent, Charge). Money-out / unrelated events (transfer.failed,\n // payout.failed, refund.failed, application_fee.refunded, …) also match a\n // naive substring scan — and a failed Transfer even carries our quoteId\n // (sendPayout stamps it), which would miscorrelate a payout failure as a\n // payment failure — so they must not surface as a terminal payment status.\n const isPaymentInEvent =\n type?.startsWith('checkout.session.') === true ||\n type?.startsWith('payment_intent.') === true ||\n type?.startsWith('charge.') === true;\n\n if (isPaymentInEvent && type?.includes('refunded')) {\n return 'refunded';\n }\n\n if (isPaymentInEvent && type?.includes('failed')) {\n return 'failed';\n }\n\n return 'processing';\n}\n\nfunction mapStripeRefundStatus(\n status: string | undefined,\n): RefundResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n case 'failed':\n case 'canceled':\n return 'failed';\n case 'requires_action':\n return 'requires_action';\n default:\n return 'submitted';\n }\n}\n\nfunction mapStripeAuthorizationStatus(\n status: string | undefined,\n): AuthorizationResult['status'] {\n switch (status) {\n case 'requires_capture':\n return 'requires_capture';\n case 'succeeded':\n return 'succeeded';\n case 'requires_action':\n return 'requires_action';\n case 'processing':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeCaptureStatus(\n status: string | undefined,\n): CaptureResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n // Capturing an authorized intent shouldn't re-enter authentication; treat\n // any in-flight/action state as still processing rather than a failure.\n case 'processing':\n case 'requires_action':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeVoidStatus(status: string | undefined): VoidResult['status'] {\n return status === 'canceled' ? 'canceled' : 'failed';\n}\n\nfunction readStripeResultCurrency(\n value: Record<string, unknown>,\n): string | undefined {\n const currency = readString(value, 'currency');\n\n return currency === undefined ? undefined : currency.toUpperCase();\n}\n\nfunction mapStripeSetupStatus(\n sessionStatus: string | undefined,\n setupIntentStatus: string | undefined,\n): SavedPaymentMethod['status'] {\n if (sessionStatus === 'expired') {\n return 'expired';\n }\n\n if (sessionStatus === 'complete') {\n // The method is reusable only once the SetupIntent itself has succeeded —\n // the Session can be `complete` while the intent is still `processing`\n // (async setup methods via dynamic payment methods).\n if (setupIntentStatus === 'succeeded') {\n return 'complete';\n }\n // A finished session whose SetupIntent didn't succeed is a terminal\n // failure (card declined → `requires_payment_method`, or `canceled`), so\n // callers can stop polling instead of waiting on a `pending` that will\n // never resolve. Still-in-flight states (`processing`, `requires_action`)\n // remain `pending`.\n if (\n setupIntentStatus === 'canceled' ||\n setupIntentStatus === 'requires_payment_method'\n ) {\n return 'failed';\n }\n }\n\n return 'pending';\n}\n\nfunction readObject(\n value: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n const item = value?.[key];\n\n return item && typeof item === 'object' && !Array.isArray(item)\n ? (item as Record<string, unknown>)\n : undefined;\n}\n\nfunction extractStripeSessionId(payTo: string): string | undefined {\n if (/^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(payTo)) {\n return payTo;\n }\n\n try {\n const url = new URL(payTo);\n const match = url.pathname.match(/\\/pay\\/([^/?#]+)/);\n\n const sessionId = match?.[1];\n\n return sessionId && /^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(sessionId)\n ? sessionId\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction flattenStripeMetadata(\n metadata:\n | Record<string, string | number | boolean | null | undefined>\n | undefined,\n): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(metadata ?? {})) {\n if (value !== undefined && value !== null) {\n result[`metadata[${key}]`] = value;\n }\n }\n\n return result;\n}\n\nfunction readString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n if (typeof item === 'string') {\n return item;\n }\n\n if (typeof item === 'number') {\n return String(item);\n }\n\n return undefined;\n}\n\nfunction readSafeInteger(\n value: Record<string, unknown> | undefined,\n key: string,\n): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'number' && Number.isSafeInteger(item) && item >= 0\n ? item\n : undefined;\n}\n"],"mappings":";;;;AAkDA,IAAa,oBAAoB;AACjC,IAAM,gCAAgC,OAAU;AAChD,IAAM,gCAAgC,OAAU,KAAK;AACrD,IAAM,6BAA6B;AACnC,IAAM,uCAAuC;AAyM7C,IAAa,gBAAb,MAAqD;CAkBtB;CAjB7B;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,iCAAkC,IAAI,IAA2B;CACjE,sCAAuC,IAAI,IAAY;CAEvD,YAAY,SAAgD;EAA/B,KAAA,UAAA;EAC3B,IAAI,OAAO,QAAQ,cAAc,YAAY,CAAC,QAAQ,UAAU,KAAK,GACnE,MAAM,IAAI,0BAA0B,mCAAmC;EAGzE,qBAAqB,QAAQ,eAAe,eAAe;EAC3D,qBAAqB,QAAQ,sBAAsB,sBAAsB;EAEzE,IAAI,QAAQ,eAAe,KAAA,GAAW;GACpC,IAAI,OAAO,QAAQ,eAAe,UAChC,MAAM,IAAI,0BACR,4DACF;GAGF,IAAI,CAAC,QAAQ,WAAW,KAAK,GAC3B,MAAM,IAAI,0BACR,6DACF;EAEJ;EAEA,KAAK,QAAQ,SAAS,QAAQ,KAAK;EACnC,KAAK,0BAA0B,iCAC7B,QAAQ,yBACR,uCACF;EACA,KAAK,2BAA2B,iCAC9B,QAAQ,4BAA4B,sCACpC,wCACF;EACA,KAAK,YAAY,QAAQ,UAAU,KAAK;EACxC,KAAK,aAAa,mBAChB,QAAQ,cAAc,6BACtB,0BACF,CAAC,CAAC,QAAQ,OAAO,EAAE;EACnB,KAAK,aAAa,wBAChB,QAAQ,cAAc,4BACtB,0BACF;EACA,KAAK,kBAAkB,wBACrB,QAAQ,mBAAmB,KAC7B;EACA,KAAK,sBAAsB,mCACzB,QAAQ,qBACR,KAAK,eACP;EACA,KAAK,eAAe,QAAQ,gBAAgB;EAE5C,IA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ACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,OAAO,OAAO,SAAS,YAAY,OAAO,cAAc,IAAI,KAAK,QAAQ,IACrE,OACA,KAAA;AACN"}
@@ -1,4 +1,4 @@
1
- import { n as PaymentError } from "./errors-feZrwnTy.js";
1
+ import { n as PaymentError } from "./errors-zSmk_AYY.js";
2
2
  //#region src/checkout-gateway.ts
3
3
  /**
4
4
  * A provider-neutral port for **hosted crypto checkouts priced in fiat**.
@@ -39,4 +39,4 @@ var CryptoCheckoutNotOwnedError = class extends PaymentError {
39
39
  //#endregion
40
40
  export { CryptoCheckoutNotOwnedError as t };
41
41
 
42
- //# sourceMappingURL=checkout-gateway-DG-LY0oG.js.map
42
+ //# sourceMappingURL=checkout-gateway-Bb8UEwK8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"checkout-gateway-DG-LY0oG.js","names":[],"sources":["../../src/checkout-gateway.ts"],"sourcesContent":["/**\n * A provider-neutral port for **hosted crypto checkouts priced in fiat**.\n *\n * Billing code (for example smrt-commerce) talks only to this interface. The\n * BTCPay implementation (`createBtcpayCheckoutGateway` in\n * `@happyvertical/payments/btcpay`) is one adapter; a dedicated crypto-payments\n * service client can implement the same port later without changing callers.\n *\n * Rules every implementation keeps:\n *\n * - **Settlement belongs to the gateway.** `status: 'settled'` means the\n * gateway's own confirmation policy is met. Callers never count\n * confirmations.\n * - **Fiat is exact.** `amount` and `amountPaid` are integer minor units of\n * `currency`; `amountPaid` is rounded down.\n * - **Webhooks carry ids only.** `verifyWebhook` authenticates a delivery and\n * names the checkout; callers act on `getCheckout()`, never on the body.\n * - **Creation is idempotent by `orderId`.** A live checkout for the order is\n * returned instead of creating another; an expired or invalid one is not\n * revived.\n */\n\nimport { PaymentError } from './errors.js';\n\n/**\n * `getCheckout` was asked for a checkout this gateway did not create (for\n * example a webhook for an invoice made by hand at the provider). Callers\n * acknowledge and ignore it, like an event with `checkoutId: null`. Its code\n * is `PAYMENT_NOT_OWNED` — routine, and distinct from the\n * `PAYMENT_VERIFICATION_FAILED` of a forged or foreign-store delivery.\n */\nexport class CryptoCheckoutNotOwnedError extends PaymentError {\n readonly checkoutId: string;\n\n constructor(checkoutId: string) {\n super(\n `Checkout ${checkoutId} was not created by this gateway.`,\n 'PAYMENT_NOT_OWNED',\n );\n this.name = 'CryptoCheckoutNotOwnedError';\n this.checkoutId = checkoutId;\n }\n}\n\n/** Where a checkout is in its lifecycle. */\nexport type CryptoCheckoutStatus =\n /** Awaiting payment; the rate is locked until `expiresAt`. */\n | 'open'\n /** Enough has been paid but is not yet settled (for example 0-conf). */\n | 'confirming'\n /** Settled under the gateway's confirmation policy. */\n | 'settled'\n /** The rate lock ran out without a full, settled payment. */\n | 'expired'\n /** The gateway invalidated it (for example a payment was double-spent or reorganized away). */\n | 'invalid';\n\n/** A qualifier that needs a decision beyond the status. */\nexport type CryptoCheckoutException =\n | 'none'\n /** Less than the price was received. */\n | 'underpaid'\n /** More than the price was received. */\n | 'overpaid'\n /** Payment arrived after the rate lock expired. */\n | 'paid_late'\n /** An operator marked it settled by hand at the gateway. */\n | 'manually_marked';\n\nexport interface CryptoCheckoutPayment {\n id: string;\n /** The asset paid, for example `BTC`. */\n asset: string;\n /** `onchain`, `lightning`, or a gateway-specific rail name. */\n rail: string;\n /** Decimal amount of `asset`. */\n amount: string;\n /** Decimal network or processing fee in `asset`, when reported. */\n fee?: string;\n status: 'confirming' | 'settled' | 'invalid';\n /** Chain transaction id, for on-chain payments. */\n transactionId?: string;\n receivedAt?: Date;\n}\n\nexport interface CryptoCheckout {\n /** The gateway implementation id (`btcpay`, …). */\n gateway: string;\n id: string;\n orderId?: string;\n status: CryptoCheckoutStatus;\n exception: CryptoCheckoutException;\n /** Locked fiat price, integer minor units of `currency`. */\n amount: number;\n currency: string;\n /** Fiat value received at the locked rate, minor units, rounded down. */\n amountPaid: number;\n /** The asset the price was quoted in (`BTC`), when known. */\n settlementAsset?: string;\n /** Decimal amount of `settlementAsset` the price required. */\n nativeAmountDue?: string;\n /** Decimal amount of `settlementAsset` received across payments. */\n nativeAmountPaid?: string;\n /** Decimal price of one `settlementAsset` in `currency`, as locked. */\n rate?: string;\n /** Where the rate came from, when the gateway or its operator says. */\n rateSource?: string;\n checkoutUrl?: string;\n createdAt?: Date;\n expiresAt?: Date;\n metadata: Record<string, string>;\n payments: CryptoCheckoutPayment[];\n /** The gateway's own representation, for audit only. */\n raw: unknown;\n}\n\nexport interface CreateCryptoCheckoutInput {\n /** Caller-owned order id; creation is idempotent by it. */\n orderId: string;\n /** Price in integer minor units of `currency`. */\n amount: number;\n currency: string;\n description?: string;\n buyerEmail?: string;\n /** String metadata stored on the checkout and returned verbatim (only these keys). */\n metadata?: Record<string, string>;\n /** Where the payer is sent after paying. */\n redirectUrl?: string;\n}\n\n/** An authenticated webhook delivery. Re-read the checkout to act on it. */\nexport interface CryptoCheckoutEvent {\n /** Stable across redeliveries of the same event. */\n eventId: string;\n /** The checkout the event is about; `null` for events about no checkout (acknowledge and ignore). */\n checkoutId: string | null;\n /** The gateway's event type, for logging. */\n type: string;\n redelivery: boolean;\n}\n\nexport interface CryptoCheckoutGateway {\n readonly id: string;\n /** Return the live checkout for `orderId`, or create one. */\n createCheckout(input: CreateCryptoCheckoutInput): Promise<CryptoCheckout>;\n /** Throws `CryptoCheckoutNotOwnedError` for a checkout it did not create. */\n getCheckout(checkoutId: string): Promise<CryptoCheckout>;\n listCheckouts(input: { orderId: string }): Promise<CryptoCheckout[]>;\n /**\n * Authenticate and parse a webhook delivery. Throws\n * `PaymentVerificationError` for a bad signature or a delivery that does\n * not belong to this gateway.\n */\n verifyWebhook(\n rawBody: string,\n headers: Headers | Record<string, string | undefined>,\n ): CryptoCheckoutEvent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,8BAAb,cAAiD,aAAa;CAC5D;CAEA,YAAY,YAAoB;EAC9B,MACE,YAAY,WAAW,oCACvB,mBACF;EACA,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF"}
1
+ {"version":3,"file":"checkout-gateway-Bb8UEwK8.js","names":[],"sources":["../../src/checkout-gateway.ts"],"sourcesContent":["/**\n * A provider-neutral port for **hosted crypto checkouts priced in fiat**.\n *\n * Billing code (for example smrt-commerce) talks only to this interface. The\n * BTCPay implementation (`createBtcpayCheckoutGateway` in\n * `@happyvertical/payments/btcpay`) is one adapter; a dedicated crypto-payments\n * service client can implement the same port later without changing callers.\n *\n * Rules every implementation keeps:\n *\n * - **Settlement belongs to the gateway.** `status: 'settled'` means the\n * gateway's own confirmation policy is met. Callers never count\n * confirmations.\n * - **Fiat is exact.** `amount` and `amountPaid` are integer minor units of\n * `currency`; `amountPaid` is rounded down.\n * - **Webhooks carry ids only.** `verifyWebhook` authenticates a delivery and\n * names the checkout; callers act on `getCheckout()`, never on the body.\n * - **Creation is idempotent by `orderId`.** A live checkout for the order is\n * returned instead of creating another; an expired or invalid one is not\n * revived.\n */\n\nimport { PaymentError } from './errors.js';\n\n/**\n * `getCheckout` was asked for a checkout this gateway did not create (for\n * example a webhook for an invoice made by hand at the provider). Callers\n * acknowledge and ignore it, like an event with `checkoutId: null`. Its code\n * is `PAYMENT_NOT_OWNED` — routine, and distinct from the\n * `PAYMENT_VERIFICATION_FAILED` of a forged or foreign-store delivery.\n */\nexport class CryptoCheckoutNotOwnedError extends PaymentError {\n readonly checkoutId: string;\n\n constructor(checkoutId: string) {\n super(\n `Checkout ${checkoutId} was not created by this gateway.`,\n 'PAYMENT_NOT_OWNED',\n );\n this.name = 'CryptoCheckoutNotOwnedError';\n this.checkoutId = checkoutId;\n }\n}\n\n/** Where a checkout is in its lifecycle. */\nexport type CryptoCheckoutStatus =\n /** Awaiting payment; the rate is locked until `expiresAt`. */\n | 'open'\n /** Enough has been paid but is not yet settled (for example 0-conf). */\n | 'confirming'\n /** Settled under the gateway's confirmation policy. */\n | 'settled'\n /** The rate lock ran out without a full, settled payment. */\n | 'expired'\n /** The gateway invalidated it (for example a payment was double-spent or reorganized away). */\n | 'invalid';\n\n/** A qualifier that needs a decision beyond the status. */\nexport type CryptoCheckoutException =\n | 'none'\n /** Less than the price was received. */\n | 'underpaid'\n /** More than the price was received. */\n | 'overpaid'\n /** Payment arrived after the rate lock expired. */\n | 'paid_late'\n /** An operator marked it settled by hand at the gateway. */\n | 'manually_marked';\n\nexport interface CryptoCheckoutPayment {\n id: string;\n /** The asset paid, for example `BTC`. */\n asset: string;\n /** `onchain`, `lightning`, or a gateway-specific rail name. */\n rail: string;\n /** Decimal amount of `asset`. */\n amount: string;\n /** Decimal network or processing fee in `asset`, when reported. */\n fee?: string;\n status: 'confirming' | 'settled' | 'invalid';\n /** Chain transaction id, for on-chain payments. */\n transactionId?: string;\n receivedAt?: Date;\n}\n\nexport interface CryptoCheckout {\n /** The gateway implementation id (`btcpay`, …). */\n gateway: string;\n id: string;\n orderId?: string;\n status: CryptoCheckoutStatus;\n exception: CryptoCheckoutException;\n /** Locked fiat price, integer minor units of `currency`. */\n amount: number;\n currency: string;\n /** Fiat value received at the locked rate, minor units, rounded down. */\n amountPaid: number;\n /** The asset the price was quoted in (`BTC`), when known. */\n settlementAsset?: string;\n /** Decimal amount of `settlementAsset` the price required. */\n nativeAmountDue?: string;\n /** Decimal amount of `settlementAsset` received across payments. */\n nativeAmountPaid?: string;\n /** Decimal price of one `settlementAsset` in `currency`, as locked. */\n rate?: string;\n /** Where the rate came from, when the gateway or its operator says. */\n rateSource?: string;\n checkoutUrl?: string;\n createdAt?: Date;\n expiresAt?: Date;\n metadata: Record<string, string>;\n payments: CryptoCheckoutPayment[];\n /** The gateway's own representation, for audit only. */\n raw: unknown;\n}\n\nexport interface CreateCryptoCheckoutInput {\n /** Caller-owned order id; creation is idempotent by it. */\n orderId: string;\n /** Price in integer minor units of `currency`. */\n amount: number;\n currency: string;\n description?: string;\n buyerEmail?: string;\n /** String metadata stored on the checkout and returned verbatim (only these keys). */\n metadata?: Record<string, string>;\n /** Where the payer is sent after paying. */\n redirectUrl?: string;\n}\n\n/** An authenticated webhook delivery. Re-read the checkout to act on it. */\nexport interface CryptoCheckoutEvent {\n /** Stable across redeliveries of the same event. */\n eventId: string;\n /** The checkout the event is about; `null` for events about no checkout (acknowledge and ignore). */\n checkoutId: string | null;\n /** The gateway's event type, for logging. */\n type: string;\n redelivery: boolean;\n}\n\nexport interface CryptoCheckoutGateway {\n readonly id: string;\n /** Return the live checkout for `orderId`, or create one. */\n createCheckout(input: CreateCryptoCheckoutInput): Promise<CryptoCheckout>;\n /** Throws `CryptoCheckoutNotOwnedError` for a checkout it did not create. */\n getCheckout(checkoutId: string): Promise<CryptoCheckout>;\n listCheckouts(input: { orderId: string }): Promise<CryptoCheckout[]>;\n /**\n * Authenticate and parse a webhook delivery. Throws\n * `PaymentVerificationError` for a bad signature or a delivery that does\n * not belong to this gateway.\n */\n verifyWebhook(\n rawBody: string,\n headers: Headers | Record<string, string | undefined>,\n ): CryptoCheckoutEvent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,8BAAb,cAAiD,aAAa;CAC5D;CAEA,YAAY,YAAoB;EAC9B,MACE,YAAY,WAAW,oCACvB,mBACF;EACA,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF"}
@@ -33,7 +33,18 @@ var PaymentVerificationError = class extends PaymentError {
33
33
  this.name = "PaymentVerificationError";
34
34
  }
35
35
  };
36
+ /**
37
+ * The payment, event, or provider account does not belong to any party the
38
+ * caller recognizes (for example a Stripe Connect webhook for an account the
39
+ * host has not mapped to a tenant).
40
+ */
41
+ var PaymentNotOwnedError = class extends PaymentError {
42
+ constructor(message, options = {}) {
43
+ super(message, "PAYMENT_NOT_OWNED", options);
44
+ this.name = "PaymentNotOwnedError";
45
+ }
46
+ };
36
47
  //#endregion
37
- export { PaymentVerificationError as a, PaymentUnsupportedError as i, PaymentError as n, PaymentProviderError as r, PaymentConfigurationError as t };
48
+ export { PaymentUnsupportedError as a, PaymentProviderError as i, PaymentError as n, PaymentVerificationError as o, PaymentNotOwnedError as r, PaymentConfigurationError as t };
38
49
 
39
- //# sourceMappingURL=errors-feZrwnTy.js.map
50
+ //# sourceMappingURL=errors-zSmk_AYY.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-feZrwnTy.js","names":[],"sources":["../../src/errors.ts"],"sourcesContent":["export type PaymentErrorCode =\n | 'PAYMENT_CONFIGURATION_ERROR'\n | 'PAYMENT_PROVIDER_ERROR'\n | 'PAYMENT_UNSUPPORTED'\n | 'PAYMENT_VERIFICATION_FAILED'\n | 'PAYMENT_NOT_OWNED'\n | 'PAYMENT_TIMEOUT'\n | 'PAYMENT_INVALID_INPUT';\n\nexport class PaymentError extends Error {\n readonly code: PaymentErrorCode;\n readonly retryable: boolean;\n\n constructor(\n message: string,\n code: PaymentErrorCode = 'PAYMENT_PROVIDER_ERROR',\n options: { cause?: unknown; retryable?: boolean } = {},\n ) {\n super(\n message,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'PaymentError';\n this.code = code;\n this.retryable = options.retryable ?? false;\n }\n}\n\nexport class PaymentConfigurationError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_CONFIGURATION_ERROR', options);\n this.name = 'PaymentConfigurationError';\n }\n}\n\nexport class PaymentProviderError extends PaymentError {\n constructor(\n message: string,\n options: { cause?: unknown; retryable?: boolean } = {},\n ) {\n super(message, 'PAYMENT_PROVIDER_ERROR', options);\n this.name = 'PaymentProviderError';\n }\n}\n\nexport class PaymentUnsupportedError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_UNSUPPORTED', options);\n this.name = 'PaymentUnsupportedError';\n }\n}\n\nexport class PaymentVerificationError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_VERIFICATION_FAILED', options);\n this.name = 'PaymentVerificationError';\n }\n}\n"],"mappings":";AASA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YACE,SACA,OAAyB,0BACzB,UAAoD,CAAC,GACrD;EACA,MACE,SACA,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CACnE;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,QAAQ,aAAa;CACxC;AACF;AAEA,IAAa,4BAAb,cAA+C,aAAa;CAC1D,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,+BAA+B,OAAO;EACrD,KAAK,OAAO;CACd;AACF;AAEA,IAAa,uBAAb,cAA0C,aAAa;CACrD,YACE,SACA,UAAoD,CAAC,GACrD;EACA,MAAM,SAAS,0BAA0B,OAAO;EAChD,KAAK,OAAO;CACd;AACF;AAEA,IAAa,0BAAb,cAA6C,aAAa;CACxD,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,uBAAuB,OAAO;EAC7C,KAAK,OAAO;CACd;AACF;AAEA,IAAa,2BAAb,cAA8C,aAAa;CACzD,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,+BAA+B,OAAO;EACrD,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"errors-zSmk_AYY.js","names":[],"sources":["../../src/errors.ts"],"sourcesContent":["export type PaymentErrorCode =\n | 'PAYMENT_CONFIGURATION_ERROR'\n | 'PAYMENT_PROVIDER_ERROR'\n | 'PAYMENT_UNSUPPORTED'\n | 'PAYMENT_VERIFICATION_FAILED'\n | 'PAYMENT_NOT_OWNED'\n | 'PAYMENT_TIMEOUT'\n | 'PAYMENT_INVALID_INPUT';\n\nexport class PaymentError extends Error {\n readonly code: PaymentErrorCode;\n readonly retryable: boolean;\n\n constructor(\n message: string,\n code: PaymentErrorCode = 'PAYMENT_PROVIDER_ERROR',\n options: { cause?: unknown; retryable?: boolean } = {},\n ) {\n super(\n message,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'PaymentError';\n this.code = code;\n this.retryable = options.retryable ?? false;\n }\n}\n\nexport class PaymentConfigurationError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_CONFIGURATION_ERROR', options);\n this.name = 'PaymentConfigurationError';\n }\n}\n\nexport class PaymentProviderError extends PaymentError {\n constructor(\n message: string,\n options: { cause?: unknown; retryable?: boolean } = {},\n ) {\n super(message, 'PAYMENT_PROVIDER_ERROR', options);\n this.name = 'PaymentProviderError';\n }\n}\n\nexport class PaymentUnsupportedError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_UNSUPPORTED', options);\n this.name = 'PaymentUnsupportedError';\n }\n}\n\nexport class PaymentVerificationError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_VERIFICATION_FAILED', options);\n this.name = 'PaymentVerificationError';\n }\n}\n\n/**\n * The payment, event, or provider account does not belong to any party the\n * caller recognizes (for example a Stripe Connect webhook for an account the\n * host has not mapped to a tenant).\n */\nexport class PaymentNotOwnedError extends PaymentError {\n constructor(message: string, options: { cause?: unknown } = {}) {\n super(message, 'PAYMENT_NOT_OWNED', options);\n this.name = 'PaymentNotOwnedError';\n }\n}\n"],"mappings":";AASA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YACE,SACA,OAAyB,0BACzB,UAAoD,CAAC,GACrD;EACA,MACE,SACA,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CACnE;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,QAAQ,aAAa;CACxC;AACF;AAEA,IAAa,4BAAb,cAA+C,aAAa;CAC1D,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,+BAA+B,OAAO;EACrD,KAAK,OAAO;CACd;AACF;AAEA,IAAa,uBAAb,cAA0C,aAAa;CACrD,YACE,SACA,UAAoD,CAAC,GACrD;EACA,MAAM,SAAS,0BAA0B,OAAO;EAChD,KAAK,OAAO;CACd;AACF;AAEA,IAAa,0BAAb,cAA6C,aAAa;CACxD,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,uBAAuB,OAAO;EAC7C,KAAK,OAAO;CACd;AACF;AAEA,IAAa,2BAAb,cAA8C,aAAa;CACzD,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,+BAA+B,OAAO;EACrD,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,uBAAb,cAA0C,aAAa;CACrD,YAAY,SAAiB,UAA+B,CAAC,GAAG;EAC9D,MAAM,SAAS,qBAAqB,OAAO;EAC3C,KAAK,OAAO;CACd;AACF"}
@@ -1,4 +1,4 @@
1
- import { r as PaymentProviderError, t as PaymentConfigurationError } from "./errors-feZrwnTy.js";
1
+ import { i as PaymentProviderError, t as PaymentConfigurationError } from "./errors-zSmk_AYY.js";
2
2
  //#region src/shared.ts
3
3
  var TERMINAL_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
4
4
  "confirmed",
@@ -257,4 +257,4 @@ function formEncode(params) {
257
257
  //#endregion
258
258
  export { normalizeUrlString as _, formEncode as a, rememberPaymentOption as b, normalizeAmount as c, normalizeFutureDate as d, normalizeMaxStoredPaymentOptions as f, normalizePositivePaymentAmount as g, normalizePositiveMinorUnitAmount as h, decimalToMinorUnitAmount as i, normalizeCurrency as l, normalizeNonEmptyString as m, currencyMinorUnitDecimals as n, getFetch as o, normalizeMinorUnitAmount as p, decimalToAtomicUnits as r, minorUnitsToDecimal as s, applyExpiryToPendingStatus as t, normalizeDate as u, pollPaymentStatus as v, readJsonResponse as y };
259
259
 
260
- //# sourceMappingURL=shared-DVl6UzD9.js.map
260
+ //# sourceMappingURL=shared-oBgOhLsa.js.map