@adyen/adyen-web 6.47.0-alpha.41c41fe → 6.47.0

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.
Files changed (76) hide show
  1. package/dist/cjs/adyen.css +10 -10
  2. package/dist/cjs/adyen.css.map +1 -1
  3. package/dist/cjs/index.cjs +2 -2
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/index.d.cts +57 -12
  6. package/dist/es/adyen.css +10 -10
  7. package/dist/es/adyen.css.map +1 -1
  8. package/dist/es/components/Dropin/components/PaymentMethod/DisableOneClickConfirmation.js +1 -1
  9. package/dist/es/components/Dropin/components/PaymentMethod/DisableOneClickConfirmation.js.map +1 -1
  10. package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
  11. package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
  12. package/dist/es/components/Giftcard/Giftcard.js +1 -1
  13. package/dist/es/components/Giftcard/Giftcard.js.map +1 -1
  14. package/dist/es/components/Giftcard/components/GiftcardComponent.js +1 -1
  15. package/dist/es/components/Giftcard/components/GiftcardComponent.js.map +1 -1
  16. package/dist/es/components/Giftcard/types.js +2 -0
  17. package/dist/es/components/Giftcard/types.js.map +1 -0
  18. package/dist/es/components/Giftcard/utils.js +2 -0
  19. package/dist/es/components/Giftcard/utils.js.map +1 -0
  20. package/dist/es/components/internal/Address/components/CountryField.js +1 -1
  21. package/dist/es/components/internal/Address/components/CountryField.js.map +1 -1
  22. package/dist/es/components/internal/Address/components/StateField.js +1 -1
  23. package/dist/es/components/internal/Address/components/StateField.js.map +1 -1
  24. package/dist/es/components/internal/ClickToPay/components/CtPOneTimePassword/CtPOneTimePasswordInput/CtPResendOtpLink.js +1 -1
  25. package/dist/es/components/internal/ClickToPay/components/CtPOneTimePassword/CtPOneTimePasswordInput/CtPResendOtpLink.js.map +1 -1
  26. package/dist/es/components/internal/ClickToPay/components/CtPSection/CtPLogoutLink.js +1 -1
  27. package/dist/es/components/internal/ClickToPay/components/CtPSection/CtPLogoutLink.js.map +1 -1
  28. package/dist/es/components/internal/SecuredFields/lib/securedField/utils/processAriaConfig.js +1 -1
  29. package/dist/es/components/internal/SecuredFields/lib/securedField/utils/processAriaConfig.js.map +1 -1
  30. package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
  31. package/dist/es/core/Services/http.js.map +1 -1
  32. package/dist/es/core/config.js +1 -1
  33. package/dist/es/core/config.js.map +1 -1
  34. package/dist/es/index.d.ts +57 -12
  35. package/dist/es/language/Language.js +1 -1
  36. package/dist/es/language/Language.js.map +1 -1
  37. package/dist/es/language/utils.js +1 -1
  38. package/dist/es/language/utils.js.map +1 -1
  39. package/dist/es/utils/amount-util.js +1 -1
  40. package/dist/es/utils/amount-util.js.map +1 -1
  41. package/dist/es-legacy/adyen.css +10 -10
  42. package/dist/es-legacy/adyen.css.map +1 -1
  43. package/dist/es-legacy/components/Dropin/components/PaymentMethod/DisableOneClickConfirmation.js +1 -1
  44. package/dist/es-legacy/components/Dropin/components/PaymentMethod/DisableOneClickConfirmation.js.map +1 -1
  45. package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
  46. package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
  47. package/dist/es-legacy/components/Giftcard/Giftcard.js +1 -1
  48. package/dist/es-legacy/components/Giftcard/Giftcard.js.map +1 -1
  49. package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js +1 -1
  50. package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js.map +1 -1
  51. package/dist/es-legacy/components/Giftcard/types.js +2 -0
  52. package/dist/es-legacy/components/Giftcard/types.js.map +1 -0
  53. package/dist/es-legacy/components/Giftcard/utils.js +2 -0
  54. package/dist/es-legacy/components/Giftcard/utils.js.map +1 -0
  55. package/dist/es-legacy/components/internal/Address/components/CountryField.js +1 -1
  56. package/dist/es-legacy/components/internal/Address/components/CountryField.js.map +1 -1
  57. package/dist/es-legacy/components/internal/Address/components/StateField.js +1 -1
  58. package/dist/es-legacy/components/internal/Address/components/StateField.js.map +1 -1
  59. package/dist/es-legacy/components/internal/ClickToPay/components/CtPOneTimePassword/CtPOneTimePasswordInput/CtPResendOtpLink.js +1 -1
  60. package/dist/es-legacy/components/internal/ClickToPay/components/CtPOneTimePassword/CtPOneTimePasswordInput/CtPResendOtpLink.js.map +1 -1
  61. package/dist/es-legacy/components/internal/ClickToPay/components/CtPSection/CtPLogoutLink.js +1 -1
  62. package/dist/es-legacy/components/internal/ClickToPay/components/CtPSection/CtPLogoutLink.js.map +1 -1
  63. package/dist/es-legacy/components/internal/SecuredFields/lib/securedField/utils/processAriaConfig.js +1 -1
  64. package/dist/es-legacy/components/internal/SecuredFields/lib/securedField/utils/processAriaConfig.js.map +1 -1
  65. package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
  66. package/dist/es-legacy/core/Services/http.js.map +1 -1
  67. package/dist/es-legacy/core/config.js +1 -1
  68. package/dist/es-legacy/core/config.js.map +1 -1
  69. package/dist/es-legacy/language/Language.js +1 -1
  70. package/dist/es-legacy/language/Language.js.map +1 -1
  71. package/dist/es-legacy/language/utils.js +1 -1
  72. package/dist/es-legacy/language/utils.js.map +1 -1
  73. package/dist/es-legacy/utils/amount-util.js +1 -1
  74. package/dist/es-legacy/utils/amount-util.js.map +1 -1
  75. package/package.json +25 -25
  76. package/styles/adyen.css +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"UIElement.js","sources":["../../../../../src/components/internal/UIElement/UIElement.tsx"],"sourcesContent":["import { createRef, h, RefObject, TargetedKeyboardEvent } from 'preact';\nimport { Resources } from '../../../core/Context/Resources';\nimport AdyenCheckoutError, { NETWORK_ERROR } from '../../../core/Errors/AdyenCheckoutError';\nimport getOrderStatus from '../../../core/Services/order-status';\nimport { hasOwnProperty } from '../../../utils/hasOwnProperty';\nimport BaseElement from '../BaseElement/BaseElement';\nimport PayButton from '../PayButton';\nimport { assertIsDropin, cleanupFinalResult, getRegulatoryDefaults, sanitizeResponse, verifyPaymentDidNotFail } from './utils';\n\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { AnalyticsErrorEvent, ErrorEventType } from '../../../core/Analytics/events/AnalyticsErrorEvent';\nimport { AnalyticsInfoEvent, InfoEventType } from '../../../core/Analytics/events/AnalyticsInfoEvent';\nimport { AnalyticsLogEvent, LogEventType } from '../../../core/Analytics/events/AnalyticsLogEvent';\nimport type { CheckoutSessionDetailsResponse, CheckoutSessionPaymentResponse } from '../../../core/CheckoutSession/types';\nimport type { NewableComponent } from '../../../core/core.registry';\nimport CancelError from '../../../core/Errors/CancelError';\nimport type { AdditionalDetailsData, CoreConfiguration, ICore, ReviewDetails } from '../../../core/types';\nimport type {\n ActionHandledReturnObject,\n CheckoutAdvancedFlowResponse,\n Order,\n PaymentAction,\n PaymentAmount,\n PaymentData,\n PaymentMethodsResponse,\n PaymentResponseData,\n RawPaymentMethod\n} from '../../../types/global-types';\nimport type { ComponentMethodsRef, UIElementProps, UIElementStatus } from './types';\nimport type { IAnalytics } from '../../../core/Analytics/Analytics';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport { SRPanel } from '../../../core/Errors/SRPanel';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { AmountProvider, AmountProviderRef } from '../../../core/Context/AmountProvider';\nimport { PayButtonProps } from '../PayButton/PayButton';\nimport { TxVariants } from '../../tx-variants';\nimport Donation from '../../Donation/Donation';\nimport './UIElement.scss';\nimport Language from '../../../language';\n\nexport abstract class UIElement<P extends UIElementProps = UIElementProps> extends BaseElement<P> {\n /**\n * componentRef is a ref to the primary component inside the subclass that extends UIElement e.g. CardInput.tsx (which sits inside Card.tsx)\n */\n protected componentRef: ComponentMethodsRef | undefined;\n\n protected resources: Resources;\n protected i18n: Language;\n\n /**\n * elementRef is a ref to the subclass that extends UIElement e.g. Card.tsx or Dropin.tsx\n */\n public elementRef: UIElement;\n\n public static readonly type: string | undefined = undefined;\n\n /**\n * Reference to the methods exposed by the AmountProvider context\n */\n protected amountProviderRef: RefObject<AmountProviderRef> = createRef();\n\n /**\n * Defines all txVariants that the Component supports (in case it support multiple ones besides the 'type' one)\n */\n public static readonly txVariants: string[] = [];\n\n constructor(checkout: ICore, props?: P) {\n super(checkout, props);\n\n this.core.register(this.constructor as NewableComponent);\n\n this.submit = this.submit.bind(this);\n this.setState = this.setState.bind(this);\n this.onComplete = this.onComplete.bind(this);\n this.handleAction = this.handleAction.bind(this);\n this.handleOrder = this.handleOrder.bind(this);\n this.handleAdditionalDetails = this.handleAdditionalDetails.bind(this);\n this.handleResponse = this.handleResponse.bind(this);\n this.setElementStatus = this.setElementStatus.bind(this);\n this.submitAnalytics = this.submitAnalytics.bind(this);\n this.makePaymentsCall = this.makePaymentsCall.bind(this);\n this.makeAdditionalDetailsCall = this.makeAdditionalDetailsCall.bind(this);\n this.submitUsingSessionsFlow = this.submitUsingSessionsFlow.bind(this);\n this.updateAmount = this.updateAmount.bind(this);\n this.setupSessionsDonation = this.setupSessionsDonation.bind(this);\n\n this.elementRef = (props && props.elementRef) || this;\n this.resources = this.props.modules?.resources ?? this.core.modules.resources;\n this.i18n = this.props.i18n ?? this.core.modules.i18n;\n\n this.storeElementRefOnCore(this.props);\n\n this.onEnterKeyPressed = this.onEnterKeyPressed.bind(this);\n this.onActionHandled = this.onActionHandled.bind(this);\n\n this.createBeforeRenderHook(props);\n this.reportIntegrationFlavor();\n }\n\n /**\n * Creates a hook tied to render() method. This hook is called every time render() is invoked.\n * Currently useful for Analytics\n *\n * @param configSetByMerchant\n * @private\n */\n private createBeforeRenderHook(configSetByMerchant?: P): void {\n const originalRender = this.render;\n\n this.render = (...args: unknown[]) => {\n this.beforeRender(configSetByMerchant);\n return originalRender.apply(this, args);\n };\n }\n\n protected beforeRender(configSetByMerchant?: P): void {\n // We don't send 'rendered' events when rendering actions\n if (configSetByMerchant?.originalAction) {\n return;\n }\n\n const event = new AnalyticsInfoEvent({\n type: InfoEventType.rendered,\n component: this.type,\n configData: { ...configSetByMerchant, showPayButton: this.props.showPayButton },\n ...(configSetByMerchant?.oneClick && { isStoredPaymentMethod: true })\n });\n\n this.analytics.sendAnalytics(event);\n }\n\n protected reportIntegrationFlavor(): void {\n void this.analytics.sendFlavor('components');\n }\n\n get analytics(): IAnalytics {\n return this.core.modules.analytics;\n }\n\n get srPanel(): SRPanel {\n return this.core.modules.srPanel;\n }\n\n protected getPaymentMethodConfigFromResponse(componentProps?: P) {\n if (componentProps?.storedPaymentMethodId) return this.getStoredPaymentMethodDetails(componentProps.storedPaymentMethodId);\n return this.getPaymentMethodFromPaymentMethodsResponse(componentProps?.type, componentProps?.paymentMethodId);\n }\n\n protected override buildElementProps(componentProps?: P) {\n const globalCoreProps = this.core.getCorePropsForComponent();\n\n const paymentMethodFromResponse = this.getPaymentMethodConfigFromResponse(componentProps);\n\n const finalProps = {\n showPayButton: true,\n ...globalCoreProps,\n ...paymentMethodFromResponse,\n ...componentProps\n };\n\n const isDropinInstance = assertIsDropin(this);\n\n this.props = this.formatProps({\n ...this.constructor['defaultProps'], // component defaults\n ...getRegulatoryDefaults(this.core.options.countryCode, isDropinInstance), // regulatory defaults\n ...finalProps // the rest (inc. merchant defined config)\n });\n }\n\n protected getStoredPaymentMethodDetails(storedPaymentMethodId: string) {\n return this.core.paymentMethodsResponse.findStoredPaymentMethod(storedPaymentMethodId);\n }\n\n /**\n * Get the payment method from the paymentMethodsResponse\n *\n * @param type - The type of the payment method to get. (This prop is passed by Drop-in OR Standalone components containing the property 'type' as part of their configuration)\n * @param paymentMethodId - Unique internal payment method ID\n */\n protected getPaymentMethodFromPaymentMethodsResponse(type?: string, paymentMethodId?: string): RawPaymentMethod {\n if (paymentMethodId) return this.core.paymentMethodsResponse.findById(paymentMethodId);\n return this.core.paymentMethodsResponse?.find(type || this.constructor['type']);\n }\n\n protected storeElementRefOnCore(props?: P) {\n if (!props?.isDropin) {\n this.core.storeElementReference(this);\n }\n }\n\n public isAvailable(): Promise<void> {\n return Promise.resolve();\n }\n\n public setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n this.onChange();\n }\n\n public showValidation(): this {\n this.componentRef?.showValidation?.();\n return this;\n }\n\n /**\n * Updates the amount in the props and propagates it to the AmountProvider.\n * This allows children components to access the updated amount via context.\n *\n * @param amount - Primary payment amount object\n * @param secondaryAmount - Optional secondary amount for display purposes (e.g., converted currency)\n * @internal\n */\n public updateAmount(amount: PaymentAmount, secondaryAmount?: PaymentAmount): void {\n this.props = {\n ...this.props,\n ...(amount && { amount }),\n ...(secondaryAmount && { secondaryAmount })\n };\n this.amountProviderRef.current?.update(amount, secondaryAmount);\n }\n\n /**\n * Set status using elementRef, which:\n * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component\n * - If Component, it will set its own status\n */\n public setElementStatus(status: UIElementStatus): this {\n this.elementRef?.setStatus?.(status);\n return this;\n }\n\n /**\n * componentRef is a ref to the primary component inside that subclass e.g. CardInput.tsx\n */\n public setStatus(status: UIElementStatus): this {\n this.componentRef?.setStatus?.(status);\n return this;\n }\n\n protected onChange(): void {\n this.props.onChange?.(\n {\n data: this.data,\n isValid: this.isValid,\n errors: this.state.errors,\n valid: this.state.valid\n },\n this.elementRef\n );\n }\n\n protected override submitAnalytics(event: AbstractAnalyticsEvent) {\n this.analytics.sendAnalytics(event);\n }\n\n public submit(): void {\n if (!this.isValid) {\n this.showValidation();\n return;\n }\n\n if (this.props.onReview) {\n const order = this.state.order ?? this.props.order;\n const onReview = (reviewDetails: ReviewDetails = {}) => {\n this.submitAnalytics(new AnalyticsLogEvent({ component: this.type, type: LogEventType.review, message: 'Review flow triggered' }));\n this.props.onReview?.(this.data, this.elementRef, reviewDetails);\n };\n if (order) {\n void getOrderStatus({ clientKey: this.props.clientKey, loadingContext: this.props.loadingContext }, order)\n .then(orderStatus => onReview({ orderStatus }))\n .catch(() => onReview());\n return;\n }\n onReview();\n return;\n }\n\n this.executePaymentsCall();\n }\n\n public executePaymentsCall(): void {\n this.makePaymentsCall()\n ?.then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch((e: PaymentResponseData | Error) => {\n if (e instanceof CancelError) {\n this.setElementStatus('ready');\n return;\n }\n this.handleFailedResult(e as PaymentResponseData);\n });\n }\n\n protected makePaymentsCall(): Promise<CheckoutAdvancedFlowResponse | CheckoutSessionPaymentResponse> | undefined {\n this.setElementStatus('loading');\n\n if (this.props.onSubmit) {\n return this.submitUsingAdvancedFlow();\n }\n\n if (this.core.session) {\n const beforeSubmitEvent: Promise<PaymentData> = this.props.beforeSubmit\n ? new Promise((resolve, reject) => {\n void this.props.beforeSubmit?.(this.data, this.elementRef, {\n resolve,\n reject: () => reject(new CancelError('beforeSubmitRejected'))\n });\n })\n : Promise.resolve(this.data);\n\n return beforeSubmitEvent.then(this.submitUsingSessionsFlow);\n }\n\n const error = new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Cannot perform /payments call. Callback \"onSubmit\" is missing or Checkout session is not available'\n );\n\n this.handleError(error);\n }\n\n private async submitUsingAdvancedFlow(): Promise<CheckoutAdvancedFlowResponse> {\n const event = new AnalyticsLogEvent({\n component: this.type,\n type: LogEventType.submit,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onSubmit?.(\n {\n data: this.data,\n isValid: this.isValid\n },\n this.elementRef,\n { resolve, reject }\n );\n });\n }\n\n private async submitUsingSessionsFlow(data: PaymentData): Promise<CheckoutSessionPaymentResponse> {\n const event = new AnalyticsLogEvent({\n component: this.type,\n type: LogEventType.submit,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n try {\n if (!this.core.session) throw new AdyenCheckoutError('ERROR', 'Cannot perform /payments call. Checkout session is not available');\n return await this.core.session.submitPayment(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) {\n this.handleError(error);\n } else {\n this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /payments call', { cause: error }));\n }\n\n return Promise.reject(error);\n }\n }\n\n protected onComplete(state: AdditionalDetailsData): void {\n this.handleAdditionalDetails(state);\n }\n\n protected handleError = (error: AdyenCheckoutError): void => {\n /**\n * Set status using elementRef, which:\n * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component\n * - If Component, it will set its own status\n */\n this.setElementStatus('ready');\n\n if (error.name === NETWORK_ERROR && error.options.code) {\n const event = new AnalyticsErrorEvent({\n component: this.type,\n errorType: ErrorEventType.apiError,\n code: error.options.code\n });\n\n this.submitAnalytics(event);\n }\n\n if (this.props.onError) {\n this.props.onError(error, this.elementRef);\n }\n };\n\n protected handleAdditionalDetails(state: AdditionalDetailsData): void {\n this.makeAdditionalDetailsCall(state)\n ?.then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch(this.handleFailedResult);\n }\n\n private makeAdditionalDetailsCall(\n state: AdditionalDetailsData\n ): Promise<CheckoutSessionDetailsResponse | CheckoutAdvancedFlowResponse> | undefined {\n if (this.props.onAdditionalDetails) {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onAdditionalDetails?.(state, this.elementRef, { resolve, reject });\n });\n }\n\n if (this.core.session) {\n return this.submitAdditionalDetailsUsingSessionsFlow(state.data);\n }\n\n const error = new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Cannot perform /payments/details call. Callback \"onAdditionalDetails\" is missing or Checkout session is not available'\n );\n\n this.handleError(error);\n }\n\n private async submitAdditionalDetailsUsingSessionsFlow(data: AdditionalDetailsData['data']): Promise<CheckoutSessionDetailsResponse> {\n try {\n if (!this.core.session) throw new AdyenCheckoutError('ERROR', 'Error when making /details call');\n return await this.core.session.submitDetails(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) this.handleError(error);\n else this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /details call', { cause: error }));\n\n return Promise.reject(error);\n }\n }\n\n public handleAction(action: PaymentAction, props = {}): UIElement | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props\n });\n\n if (paymentAction) {\n this.unmount();\n return paymentAction.mount(this.mountedNode);\n }\n\n return null;\n }\n\n protected onActionHandled(actionHandledObj: ActionHandledReturnObject) {\n this.props?.onActionHandled?.({ originalAction: this.props.originalAction, ...actionHandledObj });\n }\n\n protected handleOrder = (response: PaymentResponseData & { order: Order }): void => {\n const { order } = response;\n\n const updateCorePromise = this.core.session\n ? this.core.update({\n order\n })\n : this.handleAdvanceFlowPaymentMethodsUpdate(order);\n\n void updateCorePromise.then(() => {\n this.props.onOrderUpdated?.({ order });\n });\n };\n\n protected setupSessionsDonation() {\n const { amount, donation } = this.props;\n\n // If merchant hasn't explicitly disabled autoMount by setting it to false\n if (donation?.autoMount !== false) {\n const rootNode = assertIsDropin(this.elementRef) ? this.elementRef._node : this._node;\n if (!rootNode) return;\n\n const DonationComponentRef = this.core.getComponent(TxVariants.donation) as typeof Donation;\n new DonationComponentRef(this.core, { rootNode, commercialTxAmount: amount?.value }); // NOSONAR: Instantiation triggers internal async initialization (fire-and-forget pattern)\n }\n }\n\n /**\n * Handles when the payment fails. The payment fails when:\n * - adv flow: the merchant rejects the payment due to a critical error\n * - adv flow: the merchant resolves the payment with a failed resultCode\n * - sessions: a network error occurs when making the payment\n * - sessions: the payment fails with a failed resultCode\n *\n * @param result\n */\n protected handleFailedResult = (result?: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('error');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentFailed?.(result, this.elementRef);\n };\n\n protected handleSuccessResult = (result: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('success');\n }\n\n cleanupFinalResult(result);\n\n /** If we are using sessions and the response mandates it - create a Donation instance */\n if (this.core.session && result.askDonation === true) {\n this.setupSessionsDonation();\n }\n\n this.props.onPaymentCompleted?.(result, this.elementRef);\n };\n\n /**\n * Handles a /payments or /payments/details response.\n * The component will handle automatically actions, orders, and final results.\n *\n * Expected to be called after sanitizeResponse has been run on the raw payment response\n *\n * @param response -\n */\n protected handleResponse(response: PaymentResponseData): void {\n if (response.action) {\n if (this.core.options?.onAction) {\n this.core.options.onAction(this.core.createFromAction(response.action, { ...this.elementRef.props }));\n } else {\n this.elementRef.handleAction(response.action);\n }\n return;\n }\n\n const { order } = response;\n if (order && (order.remainingAmount?.value ?? 0) > 0) {\n // we don't want to call elementRef here, use the component handler\n // we do this way so the logic on handlingOrder is associated with payment method\n this.handleOrder({ ...response, order });\n return;\n }\n\n this.handleSuccessResult(response);\n }\n\n protected handleKeyDown(e: TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n e.preventDefault(); // Prevent <form> submission if Component is placed inside a form\n\n const activeElement = document?.activeElement;\n if (activeElement) this.onEnterKeyPressed(activeElement, this);\n }\n }\n\n /**\n * Handle Enter key pressed from a UIElement (called via handleKeyDown)\n * @param obj\n */\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n if (this.props.onEnterKeyPressed) {\n this.props.onEnterKeyPressed(activeElement, component);\n } else {\n (activeElement as HTMLElement).blur();\n this.submit();\n }\n }\n\n /**\n * Call update on parent instance\n * This function exist to make safe access to the protected _parentInstance\n * @param options - CoreOptions\n */\n public updateParent(options: CoreConfiguration = {}): Promise<ICore> {\n return this.elementRef.core.update(options);\n }\n\n public setComponentRef = (ref: ComponentMethodsRef) => {\n this.componentRef = ref;\n };\n\n /**\n * Get the current validation status of the element\n */\n public get isValid(): boolean {\n return false;\n }\n\n /**\n * Get the element icon URL for the current environment\n */\n public get icon(): string {\n const type = this.props.paymentMethodType || this.type;\n return this.props.icon ?? this.resources.getImage()(type);\n }\n\n /**\n * Get the element's displayable name\n */\n public get displayName(): string {\n const paymentMethodFromResponse = this.core.paymentMethodsResponse?.paymentMethods?.find(pm => pm.type === this.type);\n return this.props.name || paymentMethodFromResponse?.name || this.type;\n }\n\n /**\n * Get the element accessible name, used in the aria-label of the button that controls selected payment method\n */\n public get accessibleName(): string {\n return this.displayName;\n }\n\n /**\n * Used to display the second line of a payment method item\n */\n get additionalInfo(): string | null {\n return null;\n }\n\n /**\n * Return the type of an element\n */\n public get type(): string {\n return this.props.type || this.constructor['type'];\n }\n\n /**\n * Get the payButton component for the current element\n */\n protected payButton = (props: PayButtonProps) => {\n return (\n <PayButton\n {...props}\n showPayButton={this.props.showPayButton}\n disclaimerMessage={this.props.disclaimerMessage}\n onClick={this.submit}\n showReview={!!this.props.onReview}\n />\n );\n };\n\n /**\n * Used in the Partial Orders flow.\n * When the Order is updated, the merchant can request new payment methods based on the new remaining amount\n *\n * @private\n */\n protected async handleAdvanceFlowPaymentMethodsUpdate(order: Order | null, amount?: PaymentAmount) {\n return new Promise<void | PaymentMethodsResponse>((resolve, reject) => {\n if (!this.props.onPaymentMethodsRequest) {\n return resolve();\n }\n\n this.props.onPaymentMethodsRequest(\n {\n ...(order && {\n order: {\n orderData: order.orderData,\n pspReference: order.pspReference\n }\n }),\n locale: this.core.options.locale\n },\n { resolve, reject }\n );\n })\n .catch(error => {\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Something failed during payment methods update or onPaymentMethodsRequest was not implemented',\n {\n cause: error\n }\n )\n );\n })\n .then(paymentMethodsResponse => {\n // in the case of the session flow we get order, amount, countryCode and shopperLocale from initialize()\n // apply the same logic here for order and amount\n // in the future it might be worth moving this logic to be performed by the core on update()\n // it would make this more consistent\n return this.core.update({\n ...(paymentMethodsResponse && { paymentMethodsResponse }),\n order: order ?? undefined,\n amount: order ? order.remainingAmount : amount\n });\n });\n }\n\n protected abstract componentToRender(): h.JSX.Element | null;\n\n render() {\n return (\n <CoreProvider i18n={this.i18n} loadingContext={this.props.loadingContext ?? ''} resources={this.resources} analytics={this.analytics}>\n <SRPanelProvider srPanel={this.srPanel}>\n <AmountProvider amount={this.props.amount} secondaryAmount={this.props.secondaryAmount} providerRef={this.amountProviderRef}>\n {this.componentToRender()}\n </AmountProvider>\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default UIElement;\n"],"names":["UIElement","BaseElement","createBeforeRenderHook","configSetByMerchant","originalRender","this","render","args","beforeRender","apply","originalAction","event","AnalyticsInfoEvent","type","InfoEventType","rendered","component","configData","showPayButton","props","oneClick","isStoredPaymentMethod","analytics","sendAnalytics","reportIntegrationFlavor","sendFlavor","core","modules","srPanel","getPaymentMethodConfigFromResponse","componentProps","storedPaymentMethodId","getStoredPaymentMethodDetails","getPaymentMethodFromPaymentMethodsResponse","paymentMethodId","buildElementProps","finalProps","getCorePropsForComponent","isDropinInstance","assertIsDropin","formatProps","constructor","getRegulatoryDefaults","options","countryCode","paymentMethodsResponse","findStoredPaymentMethod","findById","find","storeElementRefOnCore","isDropin","storeElementReference","isAvailable","Promise","resolve","setState","newState","state","onChange","showValidation","componentRef","updateAmount","amount","secondaryAmount","amountProviderRef","current","update","setElementStatus","status","elementRef","setStatus","data","isValid","errors","valid","submitAnalytics","submit","onReview","order","reviewDetails","AnalyticsLogEvent","LogEventType","review","message","getOrderStatus","clientKey","loadingContext","then","orderStatus","catch","executePaymentsCall","makePaymentsCall","sanitizeResponse","verifyPaymentDidNotFail","handleResponse","e","CancelError","handleFailedResult","onSubmit","submitUsingAdvancedFlow","session","beforeSubmit","reject","submitUsingSessionsFlow","error","AdyenCheckoutError","handleError","submitPayment","cause","onComplete","handleAdditionalDetails","makeAdditionalDetailsCall","onAdditionalDetails","submitAdditionalDetailsUsingSessionsFlow","submitDetails","handleAction","action","hasOwnProperty","Error","paymentAction","createFromAction","unmount","mount","mountedNode","onActionHandled","actionHandledObj","setupSessionsDonation","donation","autoMount","rootNode","_node","getComponent","TxVariants","commercialTxAmount","value","response","onAction","remainingAmount","handleOrder","handleSuccessResult","handleKeyDown","key","code","preventDefault","activeElement","document","onEnterKeyPressed","blur","updateParent","icon","paymentMethodType","resources","getImage","displayName","paymentMethodFromResponse","paymentMethods","pm","name","accessibleName","additionalInfo","handleAdvanceFlowPaymentMethodsUpdate","onPaymentMethodsRequest","orderData","pspReference","locale","undefined","h","CoreProvider","i18n","SRPanelProvider","AmountProvider","providerRef","componentToRender","checkout","super","_define_property","createRef","NETWORK_ERROR","AnalyticsErrorEvent","errorType","ErrorEventType","apiError","onError","onOrderUpdated","result","displayFinalAnimation","cleanupFinalResult","onPaymentFailed","askDonation","onPaymentCompleted","setComponentRef","ref","payButton","PayButton","disclaimerMessage","onClick","showReview","register","bind","txVariants"],"mappings":"8uCAwCO,MAAeA,UAA6DC,EAkEvEC,sBAAAA,CAAuBC,GAC3B,MAAMC,EAAiBC,KAAKC,OAE5BD,KAAKC,OAAS,IAAIC,KACdF,KAAKG,aAAaL,GACXC,EAAeK,MAAMJ,KAAME,GAE1C,CAEUC,YAAAA,CAAaL,GAEnB,GAAIA,GAAqBO,eACrB,OAGJ,MAAMC,EAAQ,IAAIC,EAAmB,CACjCC,KAAMC,EAAcC,SACpBC,UAAWX,KAAKQ,KAChBI,WAAY,IAAKd,EAAqBe,cAAeb,KAAKc,MAAMD,kBAC5Df,GAAqBiB,UAAY,CAAEC,uBAAuB,KAGlEhB,KAAKiB,UAAUC,cAAcZ,EACjC,CAEUa,uBAAAA,GACDnB,KAAKiB,UAAUG,WAAW,aACnC,CAEA,aAAIH,GACA,OAAOjB,KAAKqB,KAAKC,QAAQL,SAC7B,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B/K,EAwBKuM,aAAuB"}
1
+ {"version":3,"file":"UIElement.js","sources":["../../../../../src/components/internal/UIElement/UIElement.tsx"],"sourcesContent":["import { createRef, h, RefObject, TargetedKeyboardEvent } from 'preact';\nimport { Resources } from '../../../core/Context/Resources';\nimport AdyenCheckoutError, { NETWORK_ERROR } from '../../../core/Errors/AdyenCheckoutError';\nimport getOrderStatus from '../../../core/Services/order-status';\nimport { hasOwnProperty } from '../../../utils/hasOwnProperty';\nimport BaseElement from '../BaseElement/BaseElement';\nimport PayButton from '../PayButton';\nimport { assertIsDropin, cleanupFinalResult, getRegulatoryDefaults, sanitizeResponse, verifyPaymentDidNotFail } from './utils';\n\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { AnalyticsErrorEvent, ErrorEventType } from '../../../core/Analytics/events/AnalyticsErrorEvent';\nimport { AnalyticsInfoEvent, InfoEventType } from '../../../core/Analytics/events/AnalyticsInfoEvent';\nimport { AnalyticsLogEvent, LogEventType } from '../../../core/Analytics/events/AnalyticsLogEvent';\nimport type { CheckoutSessionDetailsResponse, CheckoutSessionPaymentResponse } from '../../../core/CheckoutSession/types';\nimport type { NewableComponent } from '../../../core/core.registry';\nimport CancelError from '../../../core/Errors/CancelError';\nimport type { AdditionalDetailsData, CoreConfiguration, ICore, ReviewDetails } from '../../../core/types';\nimport type {\n ActionHandledReturnObject,\n CheckoutAdvancedFlowResponse,\n Order,\n PaymentAction,\n PaymentAmount,\n PaymentData,\n PaymentMethodsResponse,\n PaymentResponseData,\n RawPaymentMethod\n} from '../../../types/global-types';\nimport type { ComponentMethodsRef, UIElementProps, UIElementStatus } from './types';\nimport type { IAnalytics } from '../../../core/Analytics/Analytics';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport { SRPanel } from '../../../core/Errors/SRPanel';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { AmountProvider, AmountProviderRef } from '../../../core/Context/AmountProvider';\nimport { PayButtonProps } from '../PayButton/PayButton';\nimport { TxVariants } from '../../tx-variants';\nimport Donation from '../../Donation/Donation';\nimport './UIElement.scss';\nimport Language from '../../../language';\n\nexport abstract class UIElement<P extends UIElementProps = UIElementProps> extends BaseElement<P> {\n /**\n * componentRef is a ref to the primary component inside the subclass that extends UIElement e.g. CardInput.tsx (which sits inside Card.tsx)\n */\n protected componentRef: ComponentMethodsRef | undefined;\n\n protected resources: Resources;\n protected i18n: Language;\n\n /**\n * elementRef is a ref to the subclass that extends UIElement e.g. Card.tsx or Dropin.tsx\n */\n public elementRef: UIElement;\n\n public static readonly type: string | undefined = undefined;\n\n /**\n * Reference to the methods exposed by the AmountProvider context\n */\n protected amountProviderRef: RefObject<AmountProviderRef> = createRef();\n\n /**\n * Defines all txVariants that the Component supports (in case it support multiple ones besides the 'type' one)\n */\n public static readonly txVariants: string[] = [];\n\n constructor(checkout: ICore, props?: P) {\n super(checkout, props);\n\n this.core.register(this.constructor as NewableComponent);\n\n this.submit = this.submit.bind(this);\n this.setState = this.setState.bind(this);\n this.onComplete = this.onComplete.bind(this);\n this.handleAction = this.handleAction.bind(this);\n this.handleOrder = this.handleOrder.bind(this);\n this.handleAdditionalDetails = this.handleAdditionalDetails.bind(this);\n this.handleResponse = this.handleResponse.bind(this);\n this.setElementStatus = this.setElementStatus.bind(this);\n this.submitAnalytics = this.submitAnalytics.bind(this);\n this.makePaymentsCall = this.makePaymentsCall.bind(this);\n this.makeAdditionalDetailsCall = this.makeAdditionalDetailsCall.bind(this);\n this.submitUsingSessionsFlow = this.submitUsingSessionsFlow.bind(this);\n this.updateAmount = this.updateAmount.bind(this);\n this.setupSessionsDonation = this.setupSessionsDonation.bind(this);\n\n this.elementRef = (props && props.elementRef) || this;\n this.resources = this.props.modules?.resources ?? this.core.modules.resources;\n this.i18n = this.props.i18n ?? this.core.modules.i18n;\n\n this.storeElementRefOnCore(this.props);\n\n this.onEnterKeyPressed = this.onEnterKeyPressed.bind(this);\n this.onActionHandled = this.onActionHandled.bind(this);\n\n this.createBeforeRenderHook(props);\n this.reportIntegrationFlavor();\n }\n\n /**\n * Creates a hook tied to render() method. This hook is called every time render() is invoked.\n * Currently useful for Analytics\n *\n * @param configSetByMerchant\n * @private\n */\n private createBeforeRenderHook(configSetByMerchant?: P): void {\n const originalRender = this.render;\n\n this.render = (...args: unknown[]) => {\n this.beforeRender(configSetByMerchant);\n return originalRender.apply(this, args);\n };\n }\n\n protected beforeRender(configSetByMerchant?: P): void {\n // We don't send 'rendered' events when rendering actions\n if (configSetByMerchant?.originalAction) {\n return;\n }\n\n const event = new AnalyticsInfoEvent({\n type: InfoEventType.rendered,\n component: this.type,\n configData: { ...configSetByMerchant, showPayButton: this.props.showPayButton },\n ...(configSetByMerchant?.oneClick && { isStoredPaymentMethod: true })\n });\n\n this.analytics.sendAnalytics(event);\n }\n\n protected reportIntegrationFlavor(): void {\n void this.analytics.sendFlavor('components');\n }\n\n get analytics(): IAnalytics {\n return this.core.modules.analytics;\n }\n\n get srPanel(): SRPanel {\n return this.core.modules.srPanel;\n }\n\n protected getPaymentMethodConfigFromResponse(componentProps?: P) {\n if (componentProps?.storedPaymentMethodId) return this.getStoredPaymentMethodDetails(componentProps.storedPaymentMethodId);\n return this.getPaymentMethodFromPaymentMethodsResponse(componentProps?.type, componentProps?.paymentMethodId);\n }\n\n protected override buildElementProps(componentProps?: P) {\n const globalCoreProps = this.core.getCorePropsForComponent();\n\n const paymentMethodFromResponse = this.getPaymentMethodConfigFromResponse(componentProps);\n\n const finalProps = {\n showPayButton: true,\n ...globalCoreProps,\n ...paymentMethodFromResponse,\n ...componentProps\n };\n\n const isDropinInstance = assertIsDropin(this);\n\n this.props = this.formatProps({\n ...this.constructor['defaultProps'], // component defaults\n ...getRegulatoryDefaults(this.core.options.countryCode, isDropinInstance), // regulatory defaults\n ...finalProps // the rest (inc. merchant defined config)\n });\n }\n\n protected getStoredPaymentMethodDetails(storedPaymentMethodId: string) {\n return this.core.paymentMethodsResponse.findStoredPaymentMethod(storedPaymentMethodId);\n }\n\n /**\n * Get the payment method from the paymentMethodsResponse\n *\n * @param type - The type of the payment method to get. (This prop is passed by Drop-in OR Standalone components containing the property 'type' as part of their configuration)\n * @param paymentMethodId - Unique internal payment method ID\n */\n protected getPaymentMethodFromPaymentMethodsResponse(type?: string, paymentMethodId?: string): RawPaymentMethod {\n if (paymentMethodId) return this.core.paymentMethodsResponse.findById(paymentMethodId);\n return this.core.paymentMethodsResponse?.find(type || this.constructor['type']);\n }\n\n protected storeElementRefOnCore(props?: P) {\n if (!props?.isDropin) {\n this.core.storeElementReference(this);\n }\n }\n\n public isAvailable(): Promise<void> {\n return Promise.resolve();\n }\n\n public setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n this.onChange();\n }\n\n public showValidation(): this {\n this.componentRef?.showValidation?.();\n return this;\n }\n\n /**\n * Updates the amount in the props and propagates it to the AmountProvider.\n * This allows children components to access the updated amount via context.\n *\n * @param amount - Primary payment amount object\n * @param secondaryAmount - Optional secondary amount for display purposes (e.g., converted currency)\n * @internal\n */\n public updateAmount(amount: PaymentAmount, secondaryAmount?: PaymentAmount): void {\n this.props = {\n ...this.props,\n ...(amount && { amount }),\n ...(secondaryAmount && { secondaryAmount })\n };\n this.amountProviderRef.current?.update(amount, secondaryAmount);\n }\n\n /**\n * Set status using elementRef, which:\n *\n * - If Drop-in, will set status for Dropin component, and then it will propagate the\n * new status for the active payment method componen. This is triggered via componentDidUpdate\n * on DropinComponent.tsx and it will not push the state if it hasn't changed.\n *\n * - If Component, it will set its own status\n */\n public setElementStatus(status: UIElementStatus): this {\n this.elementRef?.setStatus?.(status);\n return this;\n }\n\n /**\n * componentRef is a ref to the primary component inside that subclass e.g. CardInput.tsx\n *\n * This bypasses elementRef, so inside Drop-in it only changes the view of this component, never Drop-in's own status.\n * handleError resets the status with setElementStatus('ready'), and Drop-in drops that as \"no change\" if it never left 'ready'.\n * So a status that setElementStatus will reset must also be set with setElementStatus.\n */\n public setStatus(status: UIElementStatus): this {\n this.componentRef?.setStatus?.(status);\n return this;\n }\n\n protected onChange(): void {\n this.props.onChange?.(\n {\n data: this.data,\n isValid: this.isValid,\n errors: this.state.errors,\n valid: this.state.valid\n },\n this.elementRef\n );\n }\n\n protected override submitAnalytics(event: AbstractAnalyticsEvent) {\n this.analytics.sendAnalytics(event);\n }\n\n public submit(): void {\n if (!this.isValid) {\n this.showValidation();\n return;\n }\n\n if (this.props.onReview) {\n const order = this.state.order ?? this.props.order;\n const onReview = (reviewDetails: ReviewDetails = {}) => {\n this.submitAnalytics(new AnalyticsLogEvent({ component: this.type, type: LogEventType.review, message: 'Review flow triggered' }));\n this.props.onReview?.(this.data, this.elementRef, reviewDetails);\n };\n if (order) {\n void getOrderStatus({ clientKey: this.props.clientKey, loadingContext: this.props.loadingContext }, order)\n .then(orderStatus => onReview({ orderStatus }))\n .catch(() => onReview());\n return;\n }\n onReview();\n return;\n }\n\n this.executePaymentsCall();\n }\n\n public executePaymentsCall(): void {\n this.makePaymentsCall()\n ?.then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch((e: PaymentResponseData | Error) => {\n if (e instanceof CancelError) {\n this.setElementStatus('ready');\n return;\n }\n this.handleFailedResult(e as PaymentResponseData);\n });\n }\n\n protected makePaymentsCall(): Promise<CheckoutAdvancedFlowResponse | CheckoutSessionPaymentResponse> | undefined {\n this.setElementStatus('loading');\n\n if (this.props.onSubmit) {\n return this.submitUsingAdvancedFlow();\n }\n\n if (this.core.session) {\n const beforeSubmitEvent: Promise<PaymentData> = this.props.beforeSubmit\n ? new Promise((resolve, reject) => {\n void this.props.beforeSubmit?.(this.data, this.elementRef, {\n resolve,\n reject: () => reject(new CancelError('beforeSubmitRejected'))\n });\n })\n : Promise.resolve(this.data);\n\n return beforeSubmitEvent.then(this.submitUsingSessionsFlow);\n }\n\n const error = new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Cannot perform /payments call. Callback \"onSubmit\" is missing or Checkout session is not available'\n );\n\n this.handleError(error);\n }\n\n private async submitUsingAdvancedFlow(): Promise<CheckoutAdvancedFlowResponse> {\n const event = new AnalyticsLogEvent({\n component: this.type,\n type: LogEventType.submit,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onSubmit?.(\n {\n data: this.data,\n isValid: this.isValid\n },\n this.elementRef,\n { resolve, reject }\n );\n });\n }\n\n private async submitUsingSessionsFlow(data: PaymentData): Promise<CheckoutSessionPaymentResponse> {\n const event = new AnalyticsLogEvent({\n component: this.type,\n type: LogEventType.submit,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n try {\n if (!this.core.session) throw new AdyenCheckoutError('ERROR', 'Cannot perform /payments call. Checkout session is not available');\n return await this.core.session.submitPayment(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) {\n this.handleError(error);\n } else {\n this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /payments call', { cause: error }));\n }\n\n return Promise.reject(error);\n }\n }\n\n protected onComplete(state: AdditionalDetailsData): void {\n this.handleAdditionalDetails(state);\n }\n\n protected handleError = (error: AdyenCheckoutError): void => {\n /**\n * Set status using elementRef, which:\n * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component\n * - If Component, it will set its own status\n *\n * This only resets a status that was set with setElementStatus. A status set with setStatus is not reset inside Drop-in.\n */\n this.setElementStatus('ready');\n\n if (error.name === NETWORK_ERROR && error.options.code) {\n const event = new AnalyticsErrorEvent({\n component: this.type,\n errorType: ErrorEventType.apiError,\n code: error.options.code\n });\n\n this.submitAnalytics(event);\n }\n\n if (this.props.onError) {\n this.props.onError(error, this.elementRef);\n }\n };\n\n protected handleAdditionalDetails(state: AdditionalDetailsData): void {\n this.makeAdditionalDetailsCall(state)\n ?.then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch(this.handleFailedResult);\n }\n\n private makeAdditionalDetailsCall(\n state: AdditionalDetailsData\n ): Promise<CheckoutSessionDetailsResponse | CheckoutAdvancedFlowResponse> | undefined {\n if (this.props.onAdditionalDetails) {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onAdditionalDetails?.(state, this.elementRef, { resolve, reject });\n });\n }\n\n if (this.core.session) {\n return this.submitAdditionalDetailsUsingSessionsFlow(state.data);\n }\n\n const error = new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Cannot perform /payments/details call. Callback \"onAdditionalDetails\" is missing or Checkout session is not available'\n );\n\n this.handleError(error);\n }\n\n private async submitAdditionalDetailsUsingSessionsFlow(data: AdditionalDetailsData['data']): Promise<CheckoutSessionDetailsResponse> {\n try {\n if (!this.core.session) throw new AdyenCheckoutError('ERROR', 'Error when making /details call');\n return await this.core.session.submitDetails(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) this.handleError(error);\n else this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /details call', { cause: error }));\n\n return Promise.reject(error);\n }\n }\n\n public handleAction(action: PaymentAction, props = {}): UIElement | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props\n });\n\n if (paymentAction) {\n this.unmount();\n return paymentAction.mount(this.mountedNode);\n }\n\n return null;\n }\n\n protected onActionHandled(actionHandledObj: ActionHandledReturnObject) {\n this.props?.onActionHandled?.({ originalAction: this.props.originalAction, ...actionHandledObj });\n }\n\n protected handleOrder = (response: PaymentResponseData & { order: Order }): void => {\n const { order } = response;\n\n const updateCorePromise = this.core.session\n ? this.core.update({\n order\n })\n : this.handleAdvanceFlowPaymentMethodsUpdate(order);\n\n void updateCorePromise.then(() => {\n this.props.onOrderUpdated?.({ order });\n });\n };\n\n protected setupSessionsDonation() {\n const { amount, donation } = this.props;\n\n // If merchant hasn't explicitly disabled autoMount by setting it to false\n if (donation?.autoMount !== false) {\n const rootNode = assertIsDropin(this.elementRef) ? this.elementRef._node : this._node;\n if (!rootNode) return;\n\n const DonationComponentRef = this.core.getComponent(TxVariants.donation) as typeof Donation;\n new DonationComponentRef(this.core, { rootNode, commercialTxAmount: amount?.value }); // NOSONAR: Instantiation triggers internal async initialization (fire-and-forget pattern)\n }\n }\n\n /**\n * Handles when the payment fails. The payment fails when:\n * - adv flow: the merchant rejects the payment due to a critical error\n * - adv flow: the merchant resolves the payment with a failed resultCode\n * - sessions: a network error occurs when making the payment\n * - sessions: the payment fails with a failed resultCode\n *\n * @param result\n */\n protected handleFailedResult = (result?: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('error');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentFailed?.(result, this.elementRef);\n };\n\n protected handleSuccessResult = (result: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('success');\n }\n\n cleanupFinalResult(result);\n\n /** If we are using sessions and the response mandates it - create a Donation instance */\n if (this.core.session && result.askDonation === true) {\n this.setupSessionsDonation();\n }\n\n this.props.onPaymentCompleted?.(result, this.elementRef);\n };\n\n /**\n * Handles a /payments or /payments/details response.\n * The component will handle automatically actions, orders, and final results.\n *\n * Expected to be called after sanitizeResponse has been run on the raw payment response\n *\n * @param response -\n */\n protected handleResponse(response: PaymentResponseData): void {\n if (response.action) {\n if (this.core.options?.onAction) {\n this.core.options.onAction(this.core.createFromAction(response.action, { ...this.elementRef.props }));\n } else {\n this.elementRef.handleAction(response.action);\n }\n return;\n }\n\n const { order } = response;\n if (order && (order.remainingAmount?.value ?? 0) > 0) {\n // we don't want to call elementRef here, use the component handler\n // we do this way so the logic on handlingOrder is associated with payment method\n this.handleOrder({ ...response, order });\n return;\n }\n\n this.handleSuccessResult(response);\n }\n\n protected handleKeyDown(e: TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n e.preventDefault(); // Prevent <form> submission if Component is placed inside a form\n\n const activeElement = document?.activeElement;\n if (activeElement) this.onEnterKeyPressed(activeElement, this);\n }\n }\n\n /**\n * Handle Enter key pressed from a UIElement (called via handleKeyDown)\n * @param obj\n */\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n if (this.props.onEnterKeyPressed) {\n this.props.onEnterKeyPressed(activeElement, component);\n } else {\n (activeElement as HTMLElement).blur();\n this.submit();\n }\n }\n\n /**\n * Call update on parent instance\n * This function exist to make safe access to the protected _parentInstance\n * @param options - CoreOptions\n */\n public updateParent(options: CoreConfiguration = {}): Promise<ICore> {\n return this.elementRef.core.update(options);\n }\n\n public setComponentRef = (ref: ComponentMethodsRef) => {\n this.componentRef = ref;\n };\n\n /**\n * Get the current validation status of the element\n */\n public get isValid(): boolean {\n return false;\n }\n\n /**\n * Get the element icon URL for the current environment\n */\n public get icon(): string {\n const type = this.props.paymentMethodType || this.type;\n return this.props.icon ?? this.resources.getImage()(type);\n }\n\n /**\n * Get the element's displayable name\n */\n public get displayName(): string {\n const paymentMethodFromResponse = this.core.paymentMethodsResponse?.paymentMethods?.find(pm => pm.type === this.type);\n return this.props.name || paymentMethodFromResponse?.name || this.type;\n }\n\n /**\n * Get the element accessible name, used in the aria-label of the button that controls selected payment method\n */\n public get accessibleName(): string {\n return this.displayName;\n }\n\n /**\n * Used to display the second line of a payment method item\n */\n get additionalInfo(): string | null {\n return null;\n }\n\n /**\n * Return the type of an element\n */\n public get type(): string {\n return this.props.type || this.constructor['type'];\n }\n\n /**\n * Get the payButton component for the current element\n */\n protected payButton = (props: PayButtonProps) => {\n return (\n <PayButton\n {...props}\n showPayButton={this.props.showPayButton}\n disclaimerMessage={this.props.disclaimerMessage}\n onClick={this.submit}\n showReview={!!this.props.onReview}\n />\n );\n };\n\n /**\n * Used in the Partial Orders flow.\n * When the Order is updated, the merchant can request new payment methods based on the new remaining amount\n *\n * @private\n */\n protected async handleAdvanceFlowPaymentMethodsUpdate(order: Order | null, amount?: PaymentAmount) {\n return new Promise<void | PaymentMethodsResponse>((resolve, reject) => {\n if (!this.props.onPaymentMethodsRequest) {\n return resolve();\n }\n\n this.props.onPaymentMethodsRequest(\n {\n ...(order && {\n order: {\n orderData: order.orderData,\n pspReference: order.pspReference\n }\n }),\n locale: this.core.options.locale\n },\n { resolve, reject }\n );\n })\n .catch(error => {\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Something failed during payment methods update or onPaymentMethodsRequest was not implemented',\n {\n cause: error\n }\n )\n );\n })\n .then(paymentMethodsResponse => {\n // in the case of the session flow we get order, amount, countryCode and shopperLocale from initialize()\n // apply the same logic here for order and amount\n // in the future it might be worth moving this logic to be performed by the core on update()\n // it would make this more consistent\n return this.core.update({\n ...(paymentMethodsResponse && { paymentMethodsResponse }),\n order: order ?? undefined,\n amount: order ? order.remainingAmount : amount\n });\n });\n }\n\n protected abstract componentToRender(): h.JSX.Element | null;\n\n render() {\n return (\n <CoreProvider i18n={this.i18n} loadingContext={this.props.loadingContext ?? ''} resources={this.resources} analytics={this.analytics}>\n <SRPanelProvider srPanel={this.srPanel}>\n <AmountProvider amount={this.props.amount} secondaryAmount={this.props.secondaryAmount} providerRef={this.amountProviderRef}>\n {this.componentToRender()}\n </AmountProvider>\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default UIElement;\n"],"names":["UIElement","BaseElement","createBeforeRenderHook","configSetByMerchant","originalRender","this","render","args","beforeRender","apply","originalAction","event","AnalyticsInfoEvent","type","InfoEventType","rendered","component","configData","showPayButton","props","oneClick","isStoredPaymentMethod","analytics","sendAnalytics","reportIntegrationFlavor","sendFlavor","core","modules","srPanel","getPaymentMethodConfigFromResponse","componentProps","storedPaymentMethodId","getStoredPaymentMethodDetails","getPaymentMethodFromPaymentMethodsResponse","paymentMethodId","buildElementProps","finalProps","getCorePropsForComponent","isDropinInstance","assertIsDropin","formatProps","constructor","getRegulatoryDefaults","options","countryCode","paymentMethodsResponse","findStoredPaymentMethod","findById","find","storeElementRefOnCore","isDropin","storeElementReference","isAvailable","Promise","resolve","setState","newState","state","onChange","showValidation","componentRef","updateAmount","amount","secondaryAmount","amountProviderRef","current","update","setElementStatus","status","elementRef","setStatus","data","isValid","errors","valid","submitAnalytics","submit","onReview","order","reviewDetails","AnalyticsLogEvent","LogEventType","review","message","getOrderStatus","clientKey","loadingContext","then","orderStatus","catch","executePaymentsCall","makePaymentsCall","sanitizeResponse","verifyPaymentDidNotFail","handleResponse","e","CancelError","handleFailedResult","onSubmit","submitUsingAdvancedFlow","session","beforeSubmit","reject","submitUsingSessionsFlow","error","AdyenCheckoutError","handleError","submitPayment","cause","onComplete","handleAdditionalDetails","makeAdditionalDetailsCall","onAdditionalDetails","submitAdditionalDetailsUsingSessionsFlow","submitDetails","handleAction","action","hasOwnProperty","Error","paymentAction","createFromAction","unmount","mount","mountedNode","onActionHandled","actionHandledObj","setupSessionsDonation","donation","autoMount","rootNode","_node","getComponent","TxVariants","commercialTxAmount","value","response","onAction","remainingAmount","handleOrder","handleSuccessResult","handleKeyDown","key","code","preventDefault","activeElement","document","onEnterKeyPressed","blur","updateParent","icon","paymentMethodType","resources","getImage","displayName","paymentMethodFromResponse","paymentMethods","pm","name","accessibleName","additionalInfo","handleAdvanceFlowPaymentMethodsUpdate","onPaymentMethodsRequest","orderData","pspReference","locale","undefined","h","CoreProvider","i18n","SRPanelProvider","AmountProvider","providerRef","componentToRender","checkout","super","_define_property","createRef","NETWORK_ERROR","AnalyticsErrorEvent","errorType","ErrorEventType","apiError","onError","onOrderUpdated","result","displayFinalAnimation","cleanupFinalResult","onPaymentFailed","askDonation","onPaymentCompleted","setComponentRef","ref","payButton","PayButton","disclaimerMessage","onClick","showReview","register","bind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KAAKwD,aAAexD,KAAKwD,aAAayI,KAAKjM,MAC3CA,KAAKyH,sBAAwBzH,KAAKyH,sBAAsBwE,KAAKjM,MAE7DA,KAAKgE,WAAclD,GAASA,EAAMkD,YAAehE,KACjDA,KAAKkJ,UAAYlJ,KAAKc,MAAMQ,SAAS4H,WAAalJ,KAAKqB,KAAKC,QAAQ4H,UACpElJ,KAAKmK,KAAOnK,KAAKc,MAAMqJ,MAAQnK,KAAKqB,KAAKC,QAAQ6I,KAEjDnK,KAAK4C,sBAAsB5C,KAAKc,OAEhCd,KAAK6I,kBAAoB7I,KAAK6I,kBAAkBoD,KAAKjM,MACrDA,KAAKuH,gBAAkBvH,KAAKuH,gBAAgB0E,KAAKjM,MAEjDA,KAAKH,uBAAuBiB,GAC5Bd,KAAKmB,yBACT,EA3CAuJ,EAdkB/K,EAcKa,YAA2BwJ,GAUlDU,EAxBkB/K,EAwBKuM,aAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sources":["../../../../src/core/Services/http.ts"],"sourcesContent":["import { DEFAULT_HTTP_TIMEOUT, FALLBACK_CONTEXT } from '../config';\nimport AdyenCheckoutError from '../Errors/AdyenCheckoutError';\n\nexport interface HttpOptions {\n accept?: string;\n contentType?: string;\n headers?: Record<string, string>;\n loadingContext?: string;\n method?: string;\n path: string;\n timeout?: number;\n errorLevel?: ErrorLevel;\n errorMessage?: string;\n errorCode?: string;\n}\n\ninterface FetchErrorOptions {\n message?: string;\n level?: ErrorLevel;\n cause?: unknown;\n code?: string;\n}\n\ntype ErrorLevel = 'silent' | 'info' | 'warn' | 'error' | 'fatal';\n\n/**\n * @deprecated Temporary compatibility type. `http` resolves `undefined` for 204 responses and non-fatal errors.\n * Replace with `Promise<T | undefined>` after all consumers handle missing responses.\n */\ntype LegacyHttpPromise<T> = Promise<T>;\n\ntype AdyenApiErrorResponse = {\n errorCode: string;\n message: string;\n errorType: string;\n status: number;\n};\n\nfunction isAdyenApiErrorResponse(data: unknown): data is AdyenApiErrorResponse {\n const response = data as Partial<AdyenApiErrorResponse>;\n return Boolean(data && response.errorCode && response.errorType && response.message && response.status);\n}\n\nexport function http<T>(options: HttpOptions, payload?: unknown): Promise<T> {\n const {\n headers = [],\n errorLevel = 'warn',\n errorCode,\n loadingContext = FALLBACK_CONTEXT,\n method = 'GET',\n path,\n timeout = DEFAULT_HTTP_TIMEOUT\n } = options;\n\n const request: RequestInit = {\n method,\n mode: 'cors',\n cache: 'default',\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json, text/plain, */*',\n 'Content-Type': method === 'POST' ? 'application/json' : 'text/plain',\n ...headers\n },\n redirect: 'follow',\n referrerPolicy: 'no-referrer-when-downgrade',\n ...(AbortSignal?.timeout && { signal: AbortSignal?.timeout(timeout) })\n };\n\n if (payload) {\n request.body = JSON.stringify(payload);\n }\n\n const url = `${loadingContext}${path}`;\n\n return (\n fetch(url, request)\n .then(async response => {\n // Handle empty responses (e.g., 204 No Content)\n if (response.status === 204) {\n return;\n }\n\n const data: unknown = await response.json();\n\n if (response.ok) {\n return data as T;\n }\n\n if (isAdyenApiErrorResponse(data)) {\n handleFetchError({ message: data.message, level: errorLevel, cause: data, code: errorCode });\n return;\n }\n\n const errorMessage = options.errorMessage || `Service at ${url} is not available`;\n handleFetchError({ message: errorMessage, level: errorLevel, cause: data, code: errorCode });\n return;\n })\n /**\n * Catch block handles Network error, CORS error, or exception throw by the `handleFetchError`\n * inside the `then` block\n */\n .catch((error: unknown) => {\n /**\n * If error is instance of AdyenCheckoutError, which means that it was already\n * handled by the `handleFetchError` on the `then` block, then we just throw it.\n * There is no need to create it again\n */\n if (error instanceof AdyenCheckoutError) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions\n const errorMessage = options.errorMessage || `Call to ${url} failed. Error= ${error}`;\n handleFetchError({ message: errorMessage, level: errorLevel, cause: error, code: errorCode });\n }) as LegacyHttpPromise<T>\n );\n}\n\nfunction handleFetchError({ message, level, cause, code }: FetchErrorOptions): void {\n switch (level) {\n case 'silent': {\n break;\n }\n case 'info':\n case 'warn':\n case 'error': {\n console[level](message);\n break;\n }\n default:\n throw new AdyenCheckoutError('NETWORK_ERROR', message, { cause, code });\n }\n}\n\nexport function httpGet<T = unknown>(options: HttpOptions, data?: unknown): Promise<T> {\n return http<T>({ ...options, method: 'GET' }, data);\n}\n\nexport function httpPost<T = unknown>(options: HttpOptions, data?: unknown): Promise<T> {\n return http<T>({ ...options, method: 'POST' }, data);\n}\n"],"names":["http","options","payload","headers","errorLevel","errorCode","loadingContext","FALLBACK_CONTEXT","method","path","timeout","DEFAULT_HTTP_TIMEOUT","request","mode","cache","credentials","Accept","redirect","referrerPolicy","AbortSignal","signal","body","JSON","stringify","url","fetch","then","async","response","status","data","json","ok","Boolean","errorType","message","isAdyenApiErrorResponse","handleFetchError","level","cause","code","errorMessage","catch","error","AdyenCheckoutError","console","httpGet","httpPost"],"mappings":"yHA2CO,SAASA,EAAQC,EAAsBC,GAC1C,MAAMC,QACFA,EAAU,GAAEC,WACZA,EAAa,OAAMC,UACnBA,EAASC,eACTA,EAAiBC,EAAgBC,OACjCA,EAAS,MAAKC,KACdA,EAAIC,QACJA,EAAUC,GACVV,EAEEW,EAAuB,CACzBJ,SACAK,KAAM,OACNC,MAAO,UACPC,YAAa,cACbZ,QAAS,CACLa,OAAQ,oCACR,eAA2B,SAAXR,EAAoB,mBAAqB,gBACtDL,GAEPc,SAAU,SACVC,eAAgB,gCACZC,aAAaT,SAAW,CAAEU,OAAQD,aAAaT,QAAQA,KAG3DR,IACAU,EAAQS,KAAOC,KAAKC,UAAUrB,IAGlC,MAAMsB,EAAM,GAAGlB,IAAiBG,IAEhC,OACIgB,MAAMD,EAAKZ,GACNc,KAAKC,MAAMC,IAER,GAAwB,MAApBA,EAASC,OACT,OAGJ,MAAMC,QAAsBF,EAASG,OAErC,GAAIH,EAASI,GACT,OAAOF,EAGX,GAnDhB,SAAiCA,GAC7B,MAAMF,EAAWE,EACjB,OAAOG,QAAQH,GAAQF,EAASvB,WAAauB,EAASM,WAAaN,EAASO,SAAWP,EAASC,OACpG,CAgDoBO,CAAwBN,GAExB,YADAO,EAAiB,CAAEF,QAASL,EAAKK,QAASG,MAAOlC,EAAYmC,MAAOT,EAAMU,KAAMnC,IAKpFgC,EAAiB,CAAEF,QADElC,EAAQwC,cAAgB,cAAcjB,qBACjBc,MAAOlC,EAAYmC,MAAOT,EAAMU,KAAMnC,MAOnFqC,MAAOC,IAMJ,GAAIA,aAAiBC,EACjB,MAAMD,EAKVN,EAAiB,CAAEF,QADElC,EAAQwC,cAAgB,WAAWjB,oBAAsBmB,IACpCL,MAAOlC,EAAYmC,MAAOI,EAAOH,KAAMnC,KAGjG,CAEA,SAASgC,GAAiBF,QAAEA,EAAOG,MAAEA,EAAKC,MAAEA,EAAKC,KAAEA,IAC/C,OAAQF,GACJ,IAAK,SACD,MAEJ,IAAK,OACL,IAAK,OACL,IAAK,QACDO,QAAQP,GAAOH,GACf,MAEJ,QACI,MAAM,IAAIS,EAAmB,gBAAiBT,EAAS,CAAEI,QAAOC,SAE5E,CAEO,SAASM,EAAqB7C,EAAsB6B,GACvD,OAAO9B,EAAQ,IAAKC,EAASO,OAAQ,OAASsB,EAClD,CAEO,SAASiB,EAAsB9C,EAAsB6B,GACxD,OAAO9B,EAAQ,IAAKC,EAASO,OAAQ,QAAUsB,EACnD"}
1
+ {"version":3,"file":"http.js","sources":["../../../../src/core/Services/http.ts"],"sourcesContent":["import { DEFAULT_HTTP_TIMEOUT, FALLBACK_CONTEXT } from '../config';\nimport AdyenCheckoutError from '../Errors/AdyenCheckoutError';\n\nexport interface HttpOptions {\n accept?: string;\n contentType?: string;\n headers?: Record<string, string>;\n loadingContext?: string;\n method?: string;\n path: string;\n timeout?: number;\n errorLevel?: ErrorLevel;\n errorMessage?: string;\n errorCode?: string;\n}\n\ninterface FetchErrorOptions {\n message?: string;\n level?: ErrorLevel;\n cause?: unknown;\n code?: string;\n}\n\ntype ErrorLevel = 'silent' | 'info' | 'warn' | 'error' | 'fatal';\n\n/**\n * @deprecated Temporary compatibility type. `http` resolves `undefined` for 204 responses and non-fatal errors.\n * Replace with `Promise<T | undefined>` after all consumers handle missing responses.\n */\ntype LegacyHttpPromise<T> = Promise<T>;\n\nexport type AdyenApiErrorResponse = {\n errorCode: string;\n message: string;\n errorType: string;\n status: number;\n};\n\nfunction isAdyenApiErrorResponse(data: unknown): data is AdyenApiErrorResponse {\n const response = data as Partial<AdyenApiErrorResponse>;\n return Boolean(data && response.errorCode && response.errorType && response.message && response.status);\n}\n\nexport function http<T>(options: HttpOptions, payload?: unknown): Promise<T> {\n const {\n headers = [],\n errorLevel = 'warn',\n errorCode,\n loadingContext = FALLBACK_CONTEXT,\n method = 'GET',\n path,\n timeout = DEFAULT_HTTP_TIMEOUT\n } = options;\n\n const request: RequestInit = {\n method,\n mode: 'cors',\n cache: 'default',\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json, text/plain, */*',\n 'Content-Type': method === 'POST' ? 'application/json' : 'text/plain',\n ...headers\n },\n redirect: 'follow',\n referrerPolicy: 'no-referrer-when-downgrade',\n ...(AbortSignal?.timeout && { signal: AbortSignal?.timeout(timeout) })\n };\n\n if (payload) {\n request.body = JSON.stringify(payload);\n }\n\n const url = `${loadingContext}${path}`;\n\n return (\n fetch(url, request)\n .then(async response => {\n // Handle empty responses (e.g., 204 No Content)\n if (response.status === 204) {\n return;\n }\n\n const data: unknown = await response.json();\n\n if (response.ok) {\n return data as T;\n }\n\n if (isAdyenApiErrorResponse(data)) {\n handleFetchError({ message: data.message, level: errorLevel, cause: data, code: errorCode });\n return;\n }\n\n const errorMessage = options.errorMessage || `Service at ${url} is not available`;\n handleFetchError({ message: errorMessage, level: errorLevel, cause: data, code: errorCode });\n return;\n })\n /**\n * Catch block handles Network error, CORS error, or exception throw by the `handleFetchError`\n * inside the `then` block\n */\n .catch((error: unknown) => {\n /**\n * If error is instance of AdyenCheckoutError, which means that it was already\n * handled by the `handleFetchError` on the `then` block, then we just throw it.\n * There is no need to create it again\n */\n if (error instanceof AdyenCheckoutError) {\n throw error;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions\n const errorMessage = options.errorMessage || `Call to ${url} failed. Error= ${error}`;\n handleFetchError({ message: errorMessage, level: errorLevel, cause: error, code: errorCode });\n }) as LegacyHttpPromise<T>\n );\n}\n\nfunction handleFetchError({ message, level, cause, code }: FetchErrorOptions): void {\n switch (level) {\n case 'silent': {\n break;\n }\n case 'info':\n case 'warn':\n case 'error': {\n console[level](message);\n break;\n }\n default:\n throw new AdyenCheckoutError('NETWORK_ERROR', message, { cause, code });\n }\n}\n\nexport function httpGet<T = unknown>(options: HttpOptions, data?: unknown): Promise<T> {\n return http<T>({ ...options, method: 'GET' }, data);\n}\n\nexport function httpPost<T = unknown>(options: HttpOptions, data?: unknown): Promise<T> {\n return http<T>({ ...options, method: 'POST' }, data);\n}\n"],"names":["http","options","payload","headers","errorLevel","errorCode","loadingContext","FALLBACK_CONTEXT","method","path","timeout","DEFAULT_HTTP_TIMEOUT","request","mode","cache","credentials","Accept","redirect","referrerPolicy","AbortSignal","signal","body","JSON","stringify","url","fetch","then","async","response","status","data","json","ok","Boolean","errorType","message","isAdyenApiErrorResponse","handleFetchError","level","cause","code","errorMessage","catch","error","AdyenCheckoutError","console","httpGet","httpPost"],"mappings":"yHA2CO,SAASA,EAAQC,EAAsBC,GAC1C,MAAMC,QACFA,EAAU,GAAEC,WACZA,EAAa,OAAMC,UACnBA,EAASC,eACTA,EAAiBC,EAAgBC,OACjCA,EAAS,MAAKC,KACdA,EAAIC,QACJA,EAAUC,GACVV,EAEEW,EAAuB,CACzBJ,SACAK,KAAM,OACNC,MAAO,UACPC,YAAa,cACbZ,QAAS,CACLa,OAAQ,oCACR,eAA2B,SAAXR,EAAoB,mBAAqB,gBACtDL,GAEPc,SAAU,SACVC,eAAgB,gCACZC,aAAaT,SAAW,CAA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yen.com/checkoutshopper/",o=e("6.47.0-alpha.41c41fe","LIBRARY_VERSION is not defined"),t=e("esm","BUNDLE_TYPE is not defined"),r=["amount","secondaryAmount","countryCode","environment","_environmentUrls","loadingContext","i18n","modules","order","session","clientKey","showPayButton","redirectFromTopWhenInIframe","donation","onPaymentCompleted","onPaymentFailed","beforeRedirect","beforeSubmit","onSubmit","onReview","onAction","onActionHandled","onAdditionalDetails","onChange","onEnterKeyPressed","onError","onBalanceCheck","onOrderCancel","onOrderRequest","onOrderUpdated","onPaymentMethodsRequest"],i=6e4;var d=function(e){return e.WEB="web",e}({});const a="web";var c=function(e){return e.NATIVE="nativeComponent",e.GENERIC="genericComponent",e}({});export{d as CHANNEL,i as DEFAULT_HTTP_TIMEOUT,n as FALLBACK_CONTEXT,r as GENERIC_OPTIONS,t as LIBRARY_BUNDLE_TYPE,o as LIBRARY_VERSION,c as PAYMENT_METHOD_BEHAVIOR,a as PLATFORM};
1
+ function e(e,n){if(null==e)throw new Error(n);return e}const n="https://checkoutshopper-live.adyen.com/checkoutshopper/",o=e("6.47.0","LIBRARY_VERSION is not defined"),t=e("esm","BUNDLE_TYPE is not defined"),r=["amount","secondaryAmount","countryCode","environment","_environmentUrls","loadingContext","i18n","modules","order","session","clientKey","showPayButton","redirectFromTopWhenInIframe","donation","onPaymentCompleted","onPaymentFailed","beforeRedirect","beforeSubmit","onSubmit","onReview","onAction","onActionHandled","onAdditionalDetails","onChange","onEnterKeyPressed","onError","onBalanceCheck","onOrderCancel","onOrderRequest","onOrderUpdated","onPaymentMethodsRequest"],i=6e4;var d=function(e){return e.WEB="web",e}({});const a="web";var c=function(e){return e.NATIVE="nativeComponent",e.GENERIC="genericComponent",e}({});export{d as CHANNEL,i as DEFAULT_HTTP_TIMEOUT,n as FALLBACK_CONTEXT,r as GENERIC_OPTIONS,t as LIBRARY_BUNDLE_TYPE,o as LIBRARY_VERSION,c as PAYMENT_METHOD_BEHAVIOR,a as PLATFORM};
2
2
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sources":["../../../src/core/config.ts"],"sourcesContent":["/**\n * Asserts that a value is defined and throws an error if it is not.\n *\n * @param value The value to check.\n * @param message The error message to throw if the value is undefined.\n * @returns The value if it is defined.\n */\nfunction assertDefined<T>(value: T | undefined, message: string): T {\n if (value === undefined || value === null) {\n throw new Error(message);\n }\n return value;\n}\n\n/**\n * FALLBACK_CONTEXT\n */\nexport const FALLBACK_CONTEXT = 'https://checkoutshopper-live.adyen.com/checkoutshopper/';\n\n/**\n * Library version injected at build time.\n * Always defined - the build process ensures this value is set.\n */\nexport const LIBRARY_VERSION = assertDefined(process.env.VERSION, 'LIBRARY_VERSION is not defined');\n\n/**\n * Bundle type injected at build time.\n * Always defined - the build process ensures this value is set.\n */\nexport const LIBRARY_BUNDLE_TYPE = assertDefined(process.env.BUNDLE_TYPE, 'BUNDLE_TYPE is not defined');\n\nexport const GENERIC_OPTIONS = [\n 'amount',\n 'secondaryAmount',\n 'countryCode',\n 'environment',\n '_environmentUrls',\n 'loadingContext',\n 'i18n',\n 'modules',\n 'order',\n 'session',\n 'clientKey',\n 'showPayButton',\n 'redirectFromTopWhenInIframe',\n 'donation',\n\n // Events\n 'onPaymentCompleted',\n 'onPaymentFailed',\n 'beforeRedirect',\n 'beforeSubmit',\n 'onSubmit',\n 'onReview',\n 'onAction',\n 'onActionHandled',\n 'onAdditionalDetails',\n 'onChange',\n 'onEnterKeyPressed',\n 'onError',\n 'onBalanceCheck',\n 'onOrderCancel',\n 'onOrderRequest',\n 'onOrderUpdated',\n 'onPaymentMethodsRequest'\n] as const;\n\nexport const DEFAULT_HTTP_TIMEOUT = 60000;\n\nexport default {\n FALLBACK_CONTEXT,\n GENERIC_OPTIONS,\n DEFAULT_HTTP_TIMEOUT\n};\n\n/**\n * @internal\n */\n\nexport enum CHANNEL {\n WEB = 'web'\n}\n\n/**\n * @internal\n */\nexport const PLATFORM = 'web';\n\n/**\n * How the SDK handles the rendering of a payment method.\n *\n * - NATIVE: The payment method has a dedicated component in the SDK.\n * - GENERIC: The payment method has no dedicated component; it falls back to a generic component (Redirect).\n * @internal\n */\nexport enum PAYMENT_METHOD_BEHAVIOR {\n NATIVE = 'nativeComponent',\n GENERIC = 'genericComponent'\n}\n"],"names":["assertDefined","value","message","Error","FALLBACK_CONTEXT","LIBRARY_VERSION","LIBRARY_BUNDLE_TYPE","GENERIC_OPTIONS","DEFAULT_HTTP_TIMEOUT","CHANNEL","PLATFORM","PAYMENT_METHOD_BEHAVIOR"],"mappings":"AAOA,SAASA,EAAiBC,EAAsBC,GAC5C,GAAID,QACA,MAAM,IAAIE,MAAMD,GAEpB,OAAOD,CACX,CAKO,MAAMG,EAAmB,0DAMnBC,EAAkBL,EAAc,uBAAqB,kCAMrDM,EAAsBN,EAAc,MAAyB,8BAE7DO,EAAkB,CAC3B,SACA,kBACA,cACA,cACA,mBACA,iBACA,OACA,UACA,QACA,UACA,YACA,gBACA,8BACA,WAGA,qBACA,kBACA,iBACA,eACA,WACA,WACA,WACA,kBACA,sBACA,WACA,oBACA,UACA,iBACA,gBACA,iBACA,iBACA,2BAGSC,EAAuB,IAY7B,IAAKC,EAAAA,SAAAA,GAAAA,mBAAAA,CAEZ,CAFYA,CAEZ,CAAA,GAKO,MAAMC,EAAW,MASjB,IAAKC,EAAAA,SAAAA,GAAAA,+DAAAA,CAGZ,CAHYA,CAGZ,CAAA"}
1
+ {"version":3,"file":"config.js","sources":["../../../src/core/config.ts"],"sourcesContent":["/**\n * Asserts that a value is defined and throws an error if it is not.\n *\n * @param value The value to check.\n * @param message The error message to throw if the value is undefined.\n * @returns The value if it is defined.\n */\nfunction assertDefined<T>(value: T | undefined, message: string): T {\n if (value === undefined || value === null) {\n throw new Error(message);\n }\n return value;\n}\n\n/**\n * FALLBACK_CONTEXT\n */\nexport const FALLBACK_CONTEXT = 'https://checkoutshopper-live.adyen.com/checkoutshopper/';\n\n/**\n * Library version injected at build time.\n * Always defined - the build process ensures this value is set.\n */\nexport const LIBRARY_VERSION = assertDefined(process.env.VERSION, 'LIBRARY_VERSION is not defined');\n\n/**\n * Bundle type injected at build time.\n * Always defined - the build process ensures this value is set.\n */\nexport const LIBRARY_BUNDLE_TYPE = assertDefined(process.env.BUNDLE_TYPE, 'BUNDLE_TYPE is not defined');\n\nexport const GENERIC_OPTIONS = [\n 'amount',\n 'secondaryAmount',\n 'countryCode',\n 'environment',\n '_environmentUrls',\n 'loadingContext',\n 'i18n',\n 'modules',\n 'order',\n 'session',\n 'clientKey',\n 'showPayButton',\n 'redirectFromTopWhenInIframe',\n 'donation',\n\n // Events\n 'onPaymentCompleted',\n 'onPaymentFailed',\n 'beforeRedirect',\n 'beforeSubmit',\n 'onSubmit',\n 'onReview',\n 'onAction',\n 'onActionHandled',\n 'onAdditionalDetails',\n 'onChange',\n 'onEnterKeyPressed',\n 'onError',\n 'onBalanceCheck',\n 'onOrderCancel',\n 'onOrderRequest',\n 'onOrderUpdated',\n 'onPaymentMethodsRequest'\n] as const;\n\nexport const DEFAULT_HTTP_TIMEOUT = 60000;\n\nexport default {\n FALLBACK_CONTEXT,\n GENERIC_OPTIONS,\n DEFAULT_HTTP_TIMEOUT\n};\n\n/**\n * @internal\n */\n\nexport enum CHANNEL {\n WEB = 'web'\n}\n\n/**\n * @internal\n */\nexport const PLATFORM = 'web';\n\n/**\n * How the SDK handles the rendering of a payment method.\n *\n * - NATIVE: The payment method has a dedicated component in the SDK.\n * - GENERIC: The payment method has no dedicated component; it falls back to a generic component (Redirect).\n * @internal\n */\nexport enum PAYMENT_METHOD_BEHAVIOR {\n NATIVE = 'nativeComponent',\n GENERIC = 'genericComponent'\n}\n"],"names":["assertDefined","value","message","Error","FALLBACK_CONTEXT","LIBRARY_VERSION","LIBRARY_BUNDLE_TYPE","GENERIC_OPTIONS","DEFAULT_HTTP_TIMEOUT","CHANNEL","PLATFORM","PAYMENT_METHOD_BEHAVIOR"],"mappings":"AAOA,SAASA,EAAiBC,EAAsBC,GAC5C,GAAID,QACA,MAAM,IAAIE,MAAMD,GAEpB,OAAOD,CACX,CAKO,MAAMG,EAAmB,0DAMnBC,EAAkBL,EAAc,SAAqB,kCAMrDM,EAAsBN,EAAc,MAAyB,8BAE7DO,EAAkB,CAC3B,SACA,kBACA,cACA,cACA,mBACA,iBACA,OACA,UACA,QACA,UACA,YACA,gBACA,8BACA,WAGA,qBACA,kBACA,iBACA,eACA,WACA,WACA,WACA,kBACA,sBACA,WACA,oBACA,UACA,iBACA,gBACA,iBACA,iBACA,2BAGSC,EAAuB,IAY7B,IAAKC,EAAAA,SAAAA,GAAAA,mBAAAA,CAEZ,CAFYA,CAEZ,CAAA,GAKO,MAAMC,EAAW,MASjB,IAAKC,EAAAA,SAAAA,GAAAA,+DAAAA,CAGZ,CAHYA,CAGZ,CAAA"}
@@ -22,9 +22,16 @@ interface LanguageOptions {
22
22
  }
23
23
 
24
24
  declare class Language {
25
- readonly locale: string;
26
25
  readonly languageCode: string;
27
26
  private readonly service;
27
+ /**
28
+ * Locale used to format amounts and dates, and to be passed on to third-party SDKs
29
+ */
30
+ private readonly _formattingLocale;
31
+ /**
32
+ * Locale of the translations that are loaded
33
+ */
34
+ private readonly _translationsLocale;
28
35
  private readonly customTranslations;
29
36
  /**
30
37
  * Supported locales list
@@ -40,10 +47,20 @@ declare class Language {
40
47
  readonly timeAndDateFormatOptions: Intl.DateTimeFormatOptions;
41
48
  readonly timeAndDateFormatter: Intl.DateTimeFormat;
42
49
  constructor(props: LanguageOptions);
50
+ /**
51
+ * Returns the locale requested by the merchant, in the format Intl accepts.
52
+ * Unlike {@link Language.translationsLocale}, it is not limited to the locales we ship translations for.
53
+ */
54
+ get locale(): string;
55
+ /**
56
+ * Returns the locale of the translations that are loaded.
57
+ * Limited to the locales we ship translations for, so a request for an unsupported one resolves to the closest match.
58
+ */
59
+ get translationsLocale(): string;
43
60
  requestTranslations(): Promise<void>;
44
61
  get translations(): Readonly<Translations>;
45
62
  /**
46
- * Returns a translated string from a key in the current {@link Language.locale}
63
+ * Returns a translated string from a key in the current {@link Language.translationsLocale}
47
64
  * @param key - Translation key
48
65
  * @param options - Translation options
49
66
  * @returns Translated string
@@ -4642,6 +4659,13 @@ declare class EPSElement extends IssuerListContainer {
4642
4659
  };
4643
4660
  }
4644
4661
 
4662
+ interface GiftCardBrandConfiguration extends BrandConfiguration {
4663
+ /**
4664
+ * Placeholders for this gift card brand. Keys not set here fall back to the top-level `placeholders`.
4665
+ */
4666
+ placeholders?: Placeholders$1;
4667
+ }
4668
+ type GiftCardBrandsConfiguration = Record<string, GiftCardBrandConfiguration>;
4645
4669
  interface GiftCardElementData {
4646
4670
  paymentMethod: {
4647
4671
  type: 'giftcard';
@@ -4666,7 +4690,11 @@ type onOrderRequestCallbackType = (resolve: (order: Order) => void, reject: (err
4666
4690
  interface GiftCardConfiguration extends UIElementProps {
4667
4691
  pinRequired?: boolean;
4668
4692
  expiryDateRequired?: boolean;
4669
- brandsConfiguration?: CardBrandsConfiguration;
4693
+ brandsConfiguration?: GiftCardBrandsConfiguration;
4694
+ /**
4695
+ * Placeholders for the gift card fields. Used for every brand, unless a brand sets its own in `brandsConfiguration`.
4696
+ */
4697
+ placeholders?: Placeholders$1;
4670
4698
  brand?: string;
4671
4699
  onOrderUpdated?: onOrderUpdatedCallbackType;
4672
4700
  onBalanceCheck?: onBalanceCheckCallbackType;
@@ -4686,7 +4714,18 @@ interface GiftCardValidationError {
4686
4714
  errorI18n?: string;
4687
4715
  error?: string;
4688
4716
  }
4689
- type GiftCardBalanceCheckErrorType = 'no-balance' | 'card-error' | 'currency-error';
4717
+ /**
4718
+ * Errors synthesized client-side from a successful (2xx) balance check response.
4719
+ * These are rendered inline, next to the gift card number field.
4720
+ */
4721
+ declare const BALANCE_CHECK_ERRORS: readonly ["no-balance", "card-error", "currency-error"];
4722
+ type KnownBalanceCheckError = (typeof BALANCE_CHECK_ERRORS)[number];
4723
+ /**
4724
+ * `unknown-error` covers everything we cannot attribute to the card itself
4725
+ * (5xx, network, CORS, timeout, a merchant calling `reject()`) and is rendered
4726
+ * as a banner rather than an inline field error.
4727
+ */
4728
+ type GiftCardBalanceCheckErrorType = KnownBalanceCheckError | 'unknown-error';
4690
4729
 
4691
4730
  interface GiftcardComponentProps extends Partial<Pick<SFPProps, 'clientKey' | 'loadingContext'>> {
4692
4731
  onChange: (state: any) => void;
@@ -4713,6 +4752,7 @@ declare class Giftcard extends Component<Readonly<GiftcardComponentProps>> {
4713
4752
  sfpState: {};
4714
4753
  isValidating: boolean;
4715
4754
  transformedErrors: {};
4755
+ showUnknownError: boolean;
4716
4756
  };
4717
4757
  static readonly defaultProps: {
4718
4758
  pinRequired: boolean;
@@ -4739,10 +4779,6 @@ declare class Giftcard extends Component<Readonly<GiftcardComponentProps>> {
4739
4779
  * Compatible with the transformedErrors structure
4740
4780
  */
4741
4781
  private generateBalanceCheckErrors;
4742
- /**
4743
- * Checks if a status represents a balance check error
4744
- */
4745
- private isBalanceCheckError;
4746
4782
  /**
4747
4783
  * Method called by GiftcardElement to set balance check errors only
4748
4784
  */
@@ -4750,12 +4786,13 @@ declare class Giftcard extends Component<Readonly<GiftcardComponentProps>> {
4750
4786
  showValidation: () => void;
4751
4787
  setIsValidating: (val: boolean) => void;
4752
4788
  setStatus: (status: UIElementStatus) => void;
4753
- render(props: any, { focusedElement, balance, transactionLimit, isValidating, transformedErrors }: {
4789
+ render(props: any, { focusedElement, balance, transactionLimit, isValidating, transformedErrors, showUnknownError }: {
4754
4790
  focusedElement: any;
4755
4791
  balance: any;
4756
4792
  transactionLimit: any;
4757
4793
  isValidating: any;
4758
4794
  transformedErrors: any;
4795
+ showUnknownError: any;
4759
4796
  }): h.JSX.Element;
4760
4797
  }
4761
4798
 
@@ -7452,12 +7489,20 @@ declare abstract class UIElement<P extends UIElementProps = UIElementProps> exte
7452
7489
  updateAmount(amount: PaymentAmount, secondaryAmount?: PaymentAmount): void;
7453
7490
  /**
7454
7491
  * Set status using elementRef, which:
7455
- * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component
7492
+ *
7493
+ * - If Drop-in, will set status for Dropin component, and then it will propagate the
7494
+ * new status for the active payment method componen. This is triggered via componentDidUpdate
7495
+ * on DropinComponent.tsx and it will not push the state if it hasn't changed.
7496
+ *
7456
7497
  * - If Component, it will set its own status
7457
7498
  */
7458
7499
  setElementStatus(status: UIElementStatus): this;
7459
7500
  /**
7460
7501
  * componentRef is a ref to the primary component inside that subclass e.g. CardInput.tsx
7502
+ *
7503
+ * This bypasses elementRef, so inside Drop-in it only changes the view of this component, never Drop-in's own status.
7504
+ * handleError resets the status with setElementStatus('ready'), and Drop-in drops that as "no change" if it never left 'ready'.
7505
+ * So a status that setElementStatus will reset must also be set with setElementStatus.
7461
7506
  */
7462
7507
  setStatus(status: UIElementStatus): this;
7463
7508
  protected onChange(): void;
@@ -8939,5 +8984,5 @@ declare namespace AdyenCheckout {
8939
8984
  var setBundleType: (type: string) => void;
8940
8985
  }
8941
8986
 
8942
- export { ANCVElement as ANCV, AchElement as Ach, AddressElement as Address, AdyenCheckout, AdyenCheckoutError, Affirm, AfterPay, AfterPayB2B, AmazonPayElement as AmazonPay, ApplePayElement as ApplePay, Atome, BacsElement as BacsDirectDebit, BancontactElement as Bancontact, BankTransferElement as BankTransfer, BCMCMobileElement as BcmcMobile, BillDeskOnlineElement as BillDeskOnline, BillDeskWalletElement as BillDeskWallet, BlikElement as Blik, BoletoElement as Boleto, CardElement as Card, CashAppPay, ClickToPayElement as ClickToPay, Core, CustomCard, DokuElement as Doku, DonationElement as Donation, DotpayElement as Dotpay, DragonpayElement as Dragonpay, DropinElement as Dropin, DuitNowElement as DuitNow, EPSElement as EPS, EcontextElement as Econtext, FacilyPay10x as FacilPay10x, FacilyPay12x as FacilPay12x, FacilyPay3x as FacilPay3x, FacilyPay4x as FacilPay4x, FacilyPay6x as FacilPay6x, Fastlane, FastlaneSDK, GiftcardElement as Giftcard, GiropayElement as Giropay, GooglePay, Iris, IrisMode, KlarnaPayments as Klarna, MBWayElement as MBWay, MealVoucherFRElement as MealVoucherFR, MolPayEBankingMYElement as MolPayEBankingMY, MolPayEBankingTHElement as MolPayEBankingTH, MolPayEbankingVNElement as MolPayEBankingVN, MultibancoElement as Multibanco, OnlineBankingCZElement as OnlineBankingCZ, OnlineBankingFI, OnlineBankingINElement as OnlineBankingIN, OnlineBankingPL, OnlineBankingSKElement as OnlineBankingSK, OxxoElement as Oxxo, PayByBank, PayByBankPixElement as PayByBankPix, PayByBankUS, PayMeElement as PayMe, PayNowElement as PayNow, PaypalElement as PayPal, PayToElement as PayTo, PayuNetCashcardElement as PayuCashcard, PayuNetBankingElement as PayuNetBanking, PersonalDetailsElement as PersonalDetails, PixElement as Pix, PreAuthorizedDebitCanada, PromptPayElement as PromptPay, RatePay, RatePayDirectDebit, RedirectElement as Redirect, Riverty, SepaElement as SepaDirectDebit, SwishElement as Swish, ThreeDS2Challenge, ThreeDS2DeviceFingerprint, TrustlyElement as Trustly, TwintElement as Twint, UIElement, UPI, VippsElement as Vipps, WalletINElement as WalletIN, WeChatPayElement as WeChat, index_d as components, initializeFastlane };
8943
- export type { ANCVConfiguration, ANCVDataState, AchConfiguration, AchPlaceholders, ActionDescriptionType, ActionHandledReturnObject, AdditionalDetailsActions, AdditionalDetailsData, AddressData, AddressField, AmazonPayBackendConfiguration, AmazonPayButtonProps, AmazonPayButtonSettings, AmazonPayComponentProps, AmazonPayComponentRef, AmazonPayConfiguration, AmazonPayElementData, AmazonWindowObject, App, ApplePayButtonStyle, ApplePayButtonType, ApplePayConfiguration, ApplePayElementData, ApplePayPaymentAuthorizationResult, ApplePayPaymentOrderDetails, ApplePaySessionRequest, ApplePaySessionResponse, ApplePayWebConfiguration, AwaitComponentProps, AwaitConfiguration, BankDetailsSchema, BankTransferConfiguration, BankTransferSchema, BankTransferState, BeforeSubmitActions, BinLookupResponse, BinLookupResponseRaw, BoletoConfiguration, BoletoElementProps, BoletoInputDataState, BoletoInputErrorState, BoletoInputValidState, BrandConfiguration, BrandObject, BrowserInfo, CReqData, CardAllValidData, CardAutoCompleteData, CardBackendConfiguration, CardBinLookupData, CardBinValueData, CardBrandData, CardBrandsConfiguration, CardConfigSuccessData, CardConfiguration, CardElementData, CardErrorData, CardFieldValidData, CardFocusData, CardLoadData, CardPlaceholders, CashAppPayConfiguration, CashAppPayElementData, CashAppPayEventData, ChallengeData, ChallengeResolveData, ChallengeWindowSize, ChangeActionOptions, ChangePaymentDetailsButtonProps, ChargeAmount, CheckoutAdvancedFlowResponse, CheckoutDetailsRequest, CheckoutSession, CheckoutSessionConfig, ClickToPayConfiguration, ClickToPayPaymentData, ClickToPayProps, ClickToPayScheme, CommonVoucherProps, ComponentFocusObject, ComponentMethodsRef, CoreConfiguration, CoreModules, CorePropsForComponent, CreateFromActionOptions, Currency, CustomCardConfiguration, CustomTranslations, DecodeObject, DeliverySpecifications, DokuVoucherResultProps, DonationCampaign, DonationCampaignOptions, DonationConfiguration, DonationOptions, DonationProps, DragonpayConfiguraton, DragonpayInputData, DragonpayInputIssuerItem, DragonpayInputProps, DragonpayVoucherResultProps, DropinComponentProps, DropinComponentState, DropinConfiguration, DropinStatus, DropinStatusProps, DualBrandButtons, DualBrandSelectElement, DualBrandingChangeHandler, EcontextConfiguration, EcontextInputSchema, EcontextVoucherResultProps, ErrorCodeObject, ExtendedMerchantInfo, FastlaneAddress, FastlaneAuthenticatedCustomerResult, FastlaneConfiguration, FastlaneConsentRenderState, FastlaneData, FastlaneOptions, FastlanePaymentMethodConfiguration, FastlaneProfile, FastlaneSDKConfiguration, FastlaneShipping, FastlaneShippingAddressSelectorResult, FastlaneSignupConfiguration, FastlaneWindowInstance, FieldsetVisibility, FingerPrintData, FingerprintResolveData, FundingSource, FundingSourceKeys, GiftCardBalanceCheckErrorType, GiftCardConfiguration, GiftCardElementData, GiftCardValidationError, GlobalOptions, GooglePayConfiguration, GooglePaymentDataRequest, ICore, IDropin, InstantPaymentTypes, Intent, IrisConfiguration, IrisData, IrisState, IssuerListConfiguration, IssuerListData, KlarnaAction, KlarnaAdditionalDetailsData, KlarnaComponentRef, KlarnaConfiguration, KlarnaSdkData, KlarnaWidgetAuthorizeResponse, KlarnaWidgetProps, LedgerCurrencies, MandateFrequencyType, MandateType, OnChangeData, OnChangeDataErrors, OpenInvoiceActiveFieldsets, OpenInvoiceConfiguration, OpenInvoiceFieldsetsRefs, OpenInvoiceProps, OpenInvoiceState, OpenInvoiceStateData, OpenInvoiceStateError, OpenInvoiceStateValid, OpenInvoiceVisibility, Order, OrderButtonProps, OrderStatus, PayPalConfiguration, PayToConfiguration, PayToData, PayToPlaceholdersType, PayloadJSON, PaymentAction, PaymentActionsType, PaymentAmount, PaymentCompletedData, PaymentData, PaymentFailedData, PaymentMethodBrand, PaymentMethodData, PaymentMethodDisplayMode, PaymentMethodGroup, PaymentMethodOptions, PaymentMethods, PaymentMethodsConfiguration, PaymentMethodsRequestData, PaymentMethodsResponse, PaymentResponseData, PersonalDetailsSchema, PixConfiguration, PixElementData, PostMsgParseErrorObject, PreAuthorizedDebitCanadaConfiguration, PreAuthorizedDebitCanadaPlaceholders, ProcessedPaymentStatusResponse, QRLoaderConfiguration, RawPaymentMethod, RawPaymentResponse, RawPaymentStatusResponse, RawStoredPaymentMethod, RecurringMetadata, RedirectConfiguration, Region, ResultCode, ResultObject, ResultValue, ReviewDetails, SepaConfiguration, SepaElementData, SessionsResponse, SignOutButtonProps, SocialSecurityMode, StatusFromAction, SubmitActions, SubmitData, SupportedLocale, SupportedPayPalFundingSources, ThreeDS2ActionProps, ThreeDS2ChallengeConfiguration, ThreeDS2ConfigProps, ThreeDS2DeviceFingerprintConfiguration, ThreeDS2FingerprintResponse, ThreeDS2FlowObject, ThreeDS2FlowProps, ThreeDS2Token, UIElementProps, UIElementStatus, UPIAppList, UPIConfiguration, UpdateAmazonCheckoutSessionRequest, UpiMode, UpiPaymentData, UpiType, ValidationError, VoucherConfiguration, VoucherDetail, VoucherProps, balanceCheckResponseType, onBalanceCheckCallbackType, onOrderCancelData, onOrderCancelInternalCallback, onOrderCancelType, onOrderRequestCallbackType, onOrderUpdatedCallbackType, onRequiringConfirmationCallbackType };
8987
+ export { ANCVElement as ANCV, AchElement as Ach, AddressElement as Address, AdyenCheckout, AdyenCheckoutError, Affirm, AfterPay, AfterPayB2B, AmazonPayElement as AmazonPay, ApplePayElement as ApplePay, Atome, BALANCE_CHECK_ERRORS, BacsElement as BacsDirectDebit, BancontactElement as Bancontact, BankTransferElement as BankTransfer, BCMCMobileElement as BcmcMobile, BillDeskOnlineElement as BillDeskOnline, BillDeskWalletElement as BillDeskWallet, BlikElement as Blik, BoletoElement as Boleto, CardElement as Card, CashAppPay, ClickToPayElement as ClickToPay, Core, CustomCard, DokuElement as Doku, DonationElement as Donation, DotpayElement as Dotpay, DragonpayElement as Dragonpay, DropinElement as Dropin, DuitNowElement as DuitNow, EPSElement as EPS, EcontextElement as Econtext, FacilyPay10x as FacilPay10x, FacilyPay12x as FacilPay12x, FacilyPay3x as FacilPay3x, FacilyPay4x as FacilPay4x, FacilyPay6x as FacilPay6x, Fastlane, FastlaneSDK, GiftcardElement as Giftcard, GiropayElement as Giropay, GooglePay, Iris, IrisMode, KlarnaPayments as Klarna, MBWayElement as MBWay, MealVoucherFRElement as MealVoucherFR, MolPayEBankingMYElement as MolPayEBankingMY, MolPayEBankingTHElement as MolPayEBankingTH, MolPayEbankingVNElement as MolPayEBankingVN, MultibancoElement as Multibanco, OnlineBankingCZElement as OnlineBankingCZ, OnlineBankingFI, OnlineBankingINElement as OnlineBankingIN, OnlineBankingPL, OnlineBankingSKElement as OnlineBankingSK, OxxoElement as Oxxo, PayByBank, PayByBankPixElement as PayByBankPix, PayByBankUS, PayMeElement as PayMe, PayNowElement as PayNow, PaypalElement as PayPal, PayToElement as PayTo, PayuNetCashcardElement as PayuCashcard, PayuNetBankingElement as PayuNetBanking, PersonalDetailsElement as PersonalDetails, PixElement as Pix, PreAuthorizedDebitCanada, PromptPayElement as PromptPay, RatePay, RatePayDirectDebit, RedirectElement as Redirect, Riverty, SepaElement as SepaDirectDebit, SwishElement as Swish, ThreeDS2Challenge, ThreeDS2DeviceFingerprint, TrustlyElement as Trustly, TwintElement as Twint, UIElement, UPI, VippsElement as Vipps, WalletINElement as WalletIN, WeChatPayElement as WeChat, index_d as components, initializeFastlane };
8988
+ export type { ANCVConfiguration, ANCVDataState, AchConfiguration, AchPlaceholders, ActionDescriptionType, ActionHandledReturnObject, AdditionalDetailsActions, AdditionalDetailsData, AddressData, AddressField, AmazonPayBackendConfiguration, AmazonPayButtonProps, AmazonPayButtonSettings, AmazonPayComponentProps, AmazonPayComponentRef, AmazonPayConfiguration, AmazonPayElementData, AmazonWindowObject, App, ApplePayButtonStyle, ApplePayButtonType, ApplePayConfiguration, ApplePayElementData, ApplePayPaymentAuthorizationResult, ApplePayPaymentOrderDetails, ApplePaySessionRequest, ApplePaySessionResponse, ApplePayWebConfiguration, AwaitComponentProps, AwaitConfiguration, BankDetailsSchema, BankTransferConfiguration, BankTransferSchema, BankTransferState, BeforeSubmitActions, BinLookupResponse, BinLookupResponseRaw, BoletoConfiguration, BoletoElementProps, BoletoInputDataState, BoletoInputErrorState, BoletoInputValidState, BrandConfiguration, BrandObject, BrowserInfo, CReqData, CardAllValidData, CardAutoCompleteData, CardBackendConfiguration, CardBinLookupData, CardBinValueData, CardBrandData, CardBrandsConfiguration, CardConfigSuccessData, CardConfiguration, CardElementData, CardErrorData, CardFieldValidData, CardFocusData, CardLoadData, CardPlaceholders, CashAppPayConfiguration, CashAppPayElementData, CashAppPayEventData, ChallengeData, ChallengeResolveData, ChallengeWindowSize, ChangeActionOptions, ChangePaymentDetailsButtonProps, ChargeAmount, CheckoutAdvancedFlowResponse, CheckoutDetailsRequest, CheckoutSession, CheckoutSessionConfig, ClickToPayConfiguration, ClickToPayPaymentData, ClickToPayProps, ClickToPayScheme, CommonVoucherProps, ComponentFocusObject, ComponentMethodsRef, CoreConfiguration, CoreModules, CorePropsForComponent, CreateFromActionOptions, Currency, CustomCardConfiguration, CustomTranslations, DecodeObject, DeliverySpecifications, DokuVoucherResultProps, DonationCampaign, DonationCampaignOptions, DonationConfiguration, DonationOptions, DonationProps, DragonpayConfiguraton, DragonpayInputData, DragonpayInputIssuerItem, DragonpayInputProps, DragonpayVoucherResultProps, DropinComponentProps, DropinComponentState, DropinConfiguration, DropinStatus, DropinStatusProps, DualBrandButtons, DualBrandSelectElement, DualBrandingChangeHandler, EcontextConfiguration, EcontextInputSchema, EcontextVoucherResultProps, ErrorCodeObject, ExtendedMerchantInfo, FastlaneAddress, FastlaneAuthenticatedCustomerResult, FastlaneConfiguration, FastlaneConsentRenderState, FastlaneData, FastlaneOptions, FastlanePaymentMethodConfiguration, FastlaneProfile, FastlaneSDKConfiguration, FastlaneShipping, FastlaneShippingAddressSelectorResult, FastlaneSignupConfiguration, FastlaneWindowInstance, FieldsetVisibility, FingerPrintData, FingerprintResolveData, FundingSource, FundingSourceKeys, GiftCardBalanceCheckErrorType, GiftCardBrandConfiguration, GiftCardBrandsConfiguration, GiftCardConfiguration, GiftCardElementData, GiftCardValidationError, GlobalOptions, GooglePayConfiguration, GooglePaymentDataRequest, ICore, IDropin, InstantPaymentTypes, Intent, IrisConfiguration, IrisData, IrisState, IssuerListConfiguration, IssuerListData, KlarnaAction, KlarnaAdditionalDetailsData, KlarnaComponentRef, KlarnaConfiguration, KlarnaSdkData, KlarnaWidgetAuthorizeResponse, KlarnaWidgetProps, KnownBalanceCheckError, LedgerCurrencies, MandateFrequencyType, MandateType, OnChangeData, OnChangeDataErrors, OpenInvoiceActiveFieldsets, OpenInvoiceConfiguration, OpenInvoiceFieldsetsRefs, OpenInvoiceProps, OpenInvoiceState, OpenInvoiceStateData, OpenInvoiceStateError, OpenInvoiceStateValid, OpenInvoiceVisibility, Order, OrderButtonProps, OrderStatus, PayPalConfiguration, PayToConfiguration, PayToData, PayToPlaceholdersType, PayloadJSON, PaymentAction, PaymentActionsType, PaymentAmount, PaymentCompletedData, PaymentData, PaymentFailedData, PaymentMethodBrand, PaymentMethodData, PaymentMethodDisplayMode, PaymentMethodGroup, PaymentMethodOptions, PaymentMethods, PaymentMethodsConfiguration, PaymentMethodsRequestData, PaymentMethodsResponse, PaymentResponseData, PersonalDetailsSchema, PixConfiguration, PixElementData, PostMsgParseErrorObject, PreAuthorizedDebitCanadaConfiguration, PreAuthorizedDebitCanadaPlaceholders, ProcessedPaymentStatusResponse, QRLoaderConfiguration, RawPaymentMethod, RawPaymentResponse, RawPaymentStatusResponse, RawStoredPaymentMethod, RecurringMetadata, RedirectConfiguration, Region, ResultCode, ResultObject, ResultValue, ReviewDetails, SepaConfiguration, SepaElementData, SessionsResponse, SignOutButtonProps, SocialSecurityMode, StatusFromAction, SubmitActions, SubmitData, SupportedLocale, SupportedPayPalFundingSources, ThreeDS2ActionProps, ThreeDS2ChallengeConfiguration, ThreeDS2ConfigProps, ThreeDS2DeviceFingerprintConfiguration, ThreeDS2FingerprintResponse, ThreeDS2FlowObject, ThreeDS2FlowProps, ThreeDS2Token, UIElementProps, UIElementStatus, UPIAppList, UPIConfiguration, UpdateAmazonCheckoutSessionRequest, UpiMode, UpiPaymentData, UpiType, ValidationError, VoucherConfiguration, VoucherDetail, VoucherProps, balanceCheckResponseType, onBalanceCheckCallbackType, onOrderCancelData, onOrderCancelInternalCallback, onOrderCancelType, onOrderRequestCallbackType, onOrderUpdatedCallbackType, onRequiringConfirmationCallbackType };
@@ -1,2 +1,2 @@
1
- import{getTranslation as t,formatCustomTranslations as s,parseLocale as e}from"./utils.js";import{getLocalisedAmount as i}from"../utils/amount-util.js";import{CDN_SUPPORTED_LOCALES as o,DEFAULT_LOCALE as a}from"./constants.js";import r from"../packages/server/translations/en-US.json.js";function n(t,s,e){return s in t?Object.defineProperty(t,s,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[s]=e,t}class l{async requestTranslations(){const t=await this.service.fetchTranslationsFromCdn(this.locale);this._translations={...r,...t,...Boolean(this.customTranslations[this.locale])&&this.customTranslations[this.locale]}}get translations(){return this._translations}get(s,e){const i=t(this._translations,s,e);return null!==i?i:s}amount(t,s,e){return i(t,this.locale,s,e)}date(t,s={}){if(void 0===t)return"";const e={year:"numeric",month:"2-digit",day:"2-digit",...s};return new Date(t).toLocaleDateString(this.locale,e)}dateTime(t){return void 0===t?"":this.timeAndDateFormatter.format(new Date(t))}createSupportedLocalesList(t){if(!t)return o;const s=new Set([...o,...Object.keys(t)]);return Array.from(s).sort((t,s)=>t.localeCompare(s))}constructor(t){n(this,"locale",void 0),n(this,"languageCode",void 0),n(this,"service",void 0),n(this,"customTranslations",void 0),n(this,"supportedLocales",void 0),n(this,"_translations",{}),n(this,"timeFormatOptions",{hour:"numeric",minute:"numeric"}),n(this,"timeAndDateFormatOptions",{year:"numeric",month:"2-digit",day:"2-digit",...this.timeFormatOptions}),n(this,"timeAndDateFormatter",void 0);const{locale:i,customTranslations:o,service:r}=t;this.service=r,this.customTranslations=s(o),this.supportedLocales=this.createSupportedLocalesList(this.customTranslations),this.locale=e(i||a,this.supportedLocales),this.languageCode=this.locale.split("-")[0],this.timeAndDateFormatter=Intl.DateTimeFormat(this.locale,this.timeAndDateFormatOptions)}}export{l as Language,l as default};
1
+ import{getTranslation as t,formatCustomTranslations as s,parseLocale as i,resolveFormattingLocale as a}from"./utils.js";import{getLocalisedAmount as o}from"../utils/amount-util.js";import{CDN_SUPPORTED_LOCALES as e,DEFAULT_LOCALE as n}from"./constants.js";import r from"../packages/server/translations/en-US.json.js";function l(t,s,i){return s in t?Object.defineProperty(t,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[s]=i,t}class c{get locale(){return this._formattingLocale}get translationsLocale(){return this._translationsLocale}async requestTranslations(){const t=await this.service.fetchTranslationsFromCdn(this._translationsLocale);this._translations={...r,...t,...Boolean(this.customTranslations[this._translationsLocale])&&this.customTranslations[this._translationsLocale]}}get translations(){return this._translations}get(s,i){const a=t(this._translations,s,i);return null!==a?a:s}amount(t,s,i){return o(t,this._formattingLocale,s,i)}date(t,s={}){if(void 0===t)return"";const i={year:"numeric",month:"2-digit",day:"2-digit",...s};return new Date(t).toLocaleDateString(this._formattingLocale,i)}dateTime(t){return void 0===t?"":this.timeAndDateFormatter.format(new Date(t))}createSupportedLocalesList(t){if(!t)return e;const s=new Set([...e,...Object.keys(t)]);return Array.from(s).sort((t,s)=>t.localeCompare(s))}constructor(t){l(this,"languageCode",void 0),l(this,"service",void 0),l(this,"_formattingLocale",void 0),l(this,"_translationsLocale",void 0),l(this,"customTranslations",void 0),l(this,"supportedLocales",void 0),l(this,"_translations",{}),l(this,"timeFormatOptions",{hour:"numeric",minute:"numeric"}),l(this,"timeAndDateFormatOptions",{year:"numeric",month:"2-digit",day:"2-digit",...this.timeFormatOptions}),l(this,"timeAndDateFormatter",void 0);const{locale:o,customTranslations:e,service:r}=t;this.service=r,this.customTranslations=s(e),this.supportedLocales=this.createSupportedLocalesList(this.customTranslations),this._translationsLocale=i(o||n,this.supportedLocales),this._formattingLocale=a(o||n),this.languageCode=this._translationsLocale.split("-")[0],this.timeAndDateFormatter=Intl.DateTimeFormat(this._formattingLocale,this.timeAndDateFormatOptions)}}export{c as Language,c as default};
2
2
  //# sourceMappingURL=Language.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Language.js","sources":["../../../src/language/Language.ts"],"sourcesContent":["import { formatCustomTranslations, getTranslation, parseLocale } from './utils';\nimport { getLocalisedAmount } from '../utils/amount-util';\nimport { CDN_SUPPORTED_LOCALES, DEFAULT_LOCALE } from './constants';\nimport enUS from '../../../server/translations/en-US.json';\n\nimport type { CustomTranslations, LanguageOptions, Translations } from './types';\nimport type { ILanguageService } from './LanguageService';\n\nexport class Language {\n public readonly locale: string;\n public readonly languageCode: string;\n private readonly service: ILanguageService;\n\n private readonly customTranslations: CustomTranslations;\n\n /**\n * Supported locales list\n * Includes all supported locales from the CDN and any custom locales defined in customTranslations\n */\n private readonly supportedLocales: readonly string[];\n\n /**\n * Translations object\n * Contains all translations for the current locale, including English as fallback\n */\n private _translations: Translations = {};\n\n public readonly timeFormatOptions: Intl.DateTimeFormatOptions = {\n hour: 'numeric',\n minute: 'numeric'\n };\n\n public readonly timeAndDateFormatOptions: Intl.DateTimeFormatOptions = {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n ...this.timeFormatOptions\n };\n\n public readonly timeAndDateFormatter: Intl.DateTimeFormat;\n\n constructor(props: LanguageOptions) {\n const { locale, customTranslations, service } = props;\n\n this.service = service;\n\n this.customTranslations = formatCustomTranslations(customTranslations);\n this.supportedLocales = this.createSupportedLocalesList(this.customTranslations);\n\n this.locale = parseLocale(locale || DEFAULT_LOCALE, this.supportedLocales);\n this.languageCode = this.locale.split('-')[0];\n\n this.timeAndDateFormatter = Intl.DateTimeFormat(this.locale, this.timeAndDateFormatOptions);\n }\n\n public async requestTranslations(): Promise<void> {\n const translations = await this.service.fetchTranslationsFromCdn(this.locale);\n\n this._translations = {\n ...enUS,\n ...translations,\n ...(Boolean(this.customTranslations[this.locale]) && this.customTranslations[this.locale])\n };\n }\n\n public get translations(): Readonly<Translations> {\n return this._translations;\n }\n\n /**\n * Returns a translated string from a key in the current {@link Language.locale}\n * @param key - Translation key\n * @param options - Translation options\n * @returns Translated string\n */\n public get(key: string, options?): string {\n const translation = getTranslation(this._translations, key, options);\n if (translation !== null) {\n return translation;\n }\n\n return key;\n }\n\n /**\n * Returns a localized string for an amount\n * @param amount - Amount to be converted\n * @param currencyCode - Currency code of the amount\n * @param options - Options for String.prototype.toLocaleString\n */\n public amount(amount: number, currencyCode: string, options?: object): string {\n return getLocalisedAmount(amount, this.locale, currencyCode, options);\n }\n\n /**\n * Returns a localized string for a date\n * @param date - Date to be localized\n * @param options - Options for {@link Intl.DateTimeFormatOptions}\n */\n public date(date: string, options: Intl.DateTimeFormatOptions = {}) {\n if (date === undefined) return '';\n const dateOptions: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit', ...options };\n return new Date(date).toLocaleDateString(this.locale, dateOptions);\n }\n\n /**\n * Returns a localized string for a date and time\n * @param date - Date to be localized\n */\n public dateTime(date: string) {\n if (date === undefined) return '';\n return this.timeAndDateFormatter.format(new Date(date));\n }\n\n /**\n * Creates a list of supported locales including the ones passed as custom translations\n *\n * @param customTranslations - Custom translations to include\n * @returns Array of supported locales\n */\n private createSupportedLocalesList(customTranslations?: CustomTranslations): readonly string[] {\n if (!customTranslations) {\n return CDN_SUPPORTED_LOCALES;\n }\n\n const locales = new Set([...CDN_SUPPORTED_LOCALES, ...Object.keys(customTranslations)]);\n return Array.from(locales).sort((a, b) => a.localeCompare(b));\n }\n}\n\nexport default Language;\n"],"names":["Language","requestTranslations","translations","this","service","fetchTranslationsFromCdn","locale","_translations","enUS","Boolean","customTranslations","get","key","options","translation","getTranslation","amount","currencyCode","getLocalisedAmount","date","undefined","dateOptions","year","month","day","Date","toLocaleDateString","dateTime","timeAndDateFormatter","format","createSupportedLocalesList","CDN_SUPPORTED_LOCALES","locales","Set","Object","keys","Array","from","sort","a","b","localeCompare","constructor","props","_define_property","languageCode","supportedLocales","timeFormatOptions","hour","minute","timeAndDateFormatOptions","formatCustomTranslations","parseLocale","DEFAULT_LOCALE","split","Intl","DateTimeFormat"],"mappings":"wZAQO,MAAMA,EA+CT,yBAAaC,GACT,MAAMC,QAAqBC,KAAKC,QAAQC,yBAAyBF,KAAKG,QAEtEH,KAAKI,cAAgB,IACdC,KACAN,KACCO,QAAQN,KAAKO,mBAAmBP,KAAKG,UAAYH,KAAKO,mBAAmBP,KAAKG,QAE1F,CAEA,gBAAWJ,GACP,OAAOC,KAAKI,aAChB,CAQA,GAAAI,CAAWC,EAAaC,GACpB,MAAMC,EAAcC,EAAeZ,KAAKI,cAAeK,EAAKC,GAC5D,OAAoB,OAAhBC,EACOA,EAGJF,CACX,CAQA,MAAAI,CAAcA,EAAgBC,EAAsBJ,GAChD,OAAOK,EAAmBF,EAAQb,KAAKG,OAAQW,EAAcJ,EACjE,CAOA,IAAAM,CAAYA,EAAcN,EAAsC,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/language/Language.ts"],"sourcesContent":["import { formatCustomTranslations, getTranslation, parseLocale, resolveFormattingLocale } from './utils';\nimport { getLocalisedAmount } from '../utils/amount-util';\nimport { CDN_SUPPORTED_LOCALES, DEFAULT_LOCALE } from './constants';\nimport enUS from '../../../server/translations/en-US.json';\n\nimport type { CustomTranslations, LanguageOptions, Translations } from './types';\nimport type { ILanguageService } from './LanguageService';\n\nexport class Language {\n public readonly languageCode: string;\n private readonly service: ILanguageService;\n\n /**\n * Locale used to format amounts and dates, and to be passed on to third-party SDKs\n */\n private readonly _formattingLocale: string;\n\n /**\n * Locale of the translations that are loaded\n */\n private readonly _translationsLocale: string;\n\n private readonly customTranslations: CustomTranslations;\n\n /**\n * Supported locales list\n * Includes all supported locales from the CDN and any custom locales defined in customTranslations\n */\n private readonly supportedLocales: readonly string[];\n\n /**\n * Translations object\n * Contains all translations for the current locale, including English as fallback\n */\n private _translations: Translations = {};\n\n public readonly timeFormatOptions: Intl.DateTimeFormatOptions = {\n hour: 'numeric',\n minute: 'numeric'\n };\n\n public readonly timeAndDateFormatOptions: Intl.DateTimeFormatOptions = {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n ...this.timeFormatOptions\n };\n\n public readonly timeAndDateFormatter: Intl.DateTimeFormat;\n\n constructor(props: LanguageOptions) {\n const { locale, customTranslations, service } = props;\n\n this.service = service;\n\n this.customTranslations = formatCustomTranslations(customTranslations);\n this.supportedLocales = this.createSupportedLocalesList(this.customTranslations);\n\n this._translationsLocale = parseLocale(locale || DEFAULT_LOCALE, this.supportedLocales);\n this._formattingLocale = resolveFormattingLocale(locale || DEFAULT_LOCALE);\n this.languageCode = this._translationsLocale.split('-')[0];\n\n this.timeAndDateFormatter = Intl.DateTimeFormat(this._formattingLocale, this.timeAndDateFormatOptions);\n }\n\n /**\n * Returns the locale requested by the merchant, in the format Intl accepts.\n * Unlike {@link Language.translationsLocale}, it is not limited to the locales we ship translations for.\n */\n public get locale(): string {\n return this._formattingLocale;\n }\n\n /**\n * Returns the locale of the translations that are loaded.\n * Limited to the locales we ship translations for, so a request for an unsupported one resolves to the closest match.\n */\n public get translationsLocale(): string {\n return this._translationsLocale;\n }\n\n public async requestTranslations(): Promise<void> {\n const translations = await this.service.fetchTranslationsFromCdn(this._translationsLocale);\n\n this._translations = {\n ...enUS,\n ...translations,\n ...(Boolean(this.customTranslations[this._translationsLocale]) && this.customTranslations[this._translationsLocale])\n };\n }\n\n public get translations(): Readonly<Translations> {\n return this._translations;\n }\n\n /**\n * Returns a translated string from a key in the current {@link Language.translationsLocale}\n * @param key - Translation key\n * @param options - Translation options\n * @returns Translated string\n */\n public get(key: string, options?): string {\n const translation = getTranslation(this._translations, key, options);\n if (translation !== null) {\n return translation;\n }\n\n return key;\n }\n\n /**\n * Returns a localized string for an amount\n * @param amount - Amount to be converted\n * @param currencyCode - Currency code of the amount\n * @param options - Options for String.prototype.toLocaleString\n */\n public amount(amount: number, currencyCode: string, options?: object): string {\n return getLocalisedAmount(amount, this._formattingLocale, currencyCode, options);\n }\n\n /**\n * Returns a localized string for a date\n * @param date - Date to be localized\n * @param options - Options for {@link Intl.DateTimeFormatOptions}\n */\n public date(date: string, options: Intl.DateTimeFormatOptions = {}) {\n if (date === undefined) return '';\n const dateOptions: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit', ...options };\n return new Date(date).toLocaleDateString(this._formattingLocale, dateOptions);\n }\n\n /**\n * Returns a localized string for a date and time\n * @param date - Date to be localized\n */\n public dateTime(date: string) {\n if (date === undefined) return '';\n return this.timeAndDateFormatter.format(new Date(date));\n }\n\n /**\n * Creates a list of supported locales including the ones passed as custom translations\n *\n * @param customTranslations - Custom translations to include\n * @returns Array of supported locales\n */\n private createSupportedLocalesList(customTranslations?: CustomTranslations): readonly string[] {\n if (!customTranslations) {\n return CDN_SUPPORTED_LOCALES;\n }\n\n const locales = new Set([...CDN_SUPPORTED_LOCALES, ...Object.keys(customTranslations)]);\n return Array.from(locales).sort((a, b) => a.localeCompare(b));\n }\n}\n\nexport default Language;\n"],"names":["Language","locale","this","_formattingLocale","translationsLocale","_translationsLocale","requestTranslations","translations","service","fetchTranslationsFromCdn","_translations","enUS","Boolean","customTranslations","get","key","options","translation","getTranslation","amount","currencyCode","getLocalisedAmount","date","undefined","dateOptions","year","month","day","Date","toLocaleDateString","dateTime","timeAndDateFormatter","format","createSupportedLocalesList","CDN_SUPPORTED_LOCALES","locales","Set","Object","keys","Array","from","sort","a","b","localeCompare","constructor","props","_define_property","languageCode","supportedLocales","timeFormatOptions","hour","minute","timeAndDateFormatOptions","formatCustomTranslations","parseLocale","DEFAULT_LOCALE","resolveFormattingLocale","split","Intl","DateTimeFormat"],"mappings":"qbAQO,MAAMA,EA6DT,UAAWC,GACP,OAAOC,KAAKC,iBAChB,CAMA,sBAAWC,GACP,OAAOF,KAAKG,mBAChB,CAEA,yBAAaC,GACT,MAAMC,QAAqBL,KAAKM,QAAQC,yBAAyBP,KAAKG,qBAEtEH,KAAKQ,cAAgB,IACdC,KACAJ,KACCK,QAAQV,KAAKW,mBAAmBX,KAAKG,uBAAyBH,KAAKW,mBAAmBX,KAAKG,qBAEvG,CAEA,gBAAWE,GACP,OAAOL,KAAKQ,aAChB,CAQA,GAAAI,CAAWC,EAAaC,GACpB,MAAMC,EAAcC,EAAehB,KAAKQ,cAAeK,EAAKC,GAC5D,OAAoB,OAAhBC,EACOA,EAGJF,CACX,CAQA,MAAAI,CAAcA,EAAgBC,EAAsBJ,GAChD,OAAOK,EAAmBF,EAAQjB,KAAKC,kBAAmBiB,EAAcJ,EAC5E,CAOA,IAAAM,CAAYA,EAAcN,EAAsC,IAC5D,QAAaO,IAATD,EAAoB,MAAO,GAC/B,MAAME,EAA0C,CAAEC,KAAM,UAAWC,MAAO,UAAWC,IAAK,aAAcX,GACxG,OAAO,IAAIY,KAAKN,GAAMO,mBAAmB3B,KAAKC,kBAAmBqB,EACrE,CAMOM,QAAAA,CAASR,GACZ,YAAaC,IAATD,EAA2B,GACxB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function s(t,n){if(!t||"string"!=typeof t)return null;const e=t.toLowerCase(),o=n.find(t=>t.toLowerCase()===e);if(o)return o;const s=r(t);return n.find(t=>r(t)===s)||null}function l(t){const n=t.replace("_","-");if(/^([a-z]{2})(-)([A-Z]{2})$/.test(n))return n;const[e,r]=n.split("-");if(!e||!r)return null;const o=[e.toLowerCase(),r.toUpperCase()].join("-");return 5===o.length?o:null}function u(n,e){if(!o(n))return t;const r=l(n);return r&&e.includes(r)?r:s(r||n,e)||t}function c(t={}){return Object.keys(t).reduce((n,e)=>{if(!o(e))return n;return n[l(e)||r(e)]=t[e],n},{})}const i=(t,n)=>t.replace(/%{(\w+)}/g,(t,e)=>n[e]||""),a=(t,n,e={})=>{const{values:r={},count:o=0}=e,s=`${n}__plural`,l=t=>`${n}__${t}`;return Object.prototype.hasOwnProperty.call(t,l(o))?i(t[l(o)],r):Object.prototype.hasOwnProperty.call(t,s)&&o>1?i(t[s],r):Object.prototype.hasOwnProperty.call(t,n)?i(t[n],r):null},p=(t,n)=>{const e=t.split(/%#(.*?)%#/gm);if(n.length!==Math.floor(e.length/2))throw Error("The number of functions provided does not match the number of elements in the translation string.");return e.map((t,e)=>{const r=Math.floor(e/2);return e%2==0?t:n[r](t)})};export{c as formatCustomTranslations,l as formatLocaleToLanguageCountryLocale,a as getTranslation,p as interpolateElement,s as matchLocale,u as parseLocale};
1
+ import{DEFAULT_LOCALE as t,LOCALE_NAME_MIN_LENGTH as n,LOCALE_NAME_MAX_LENGTH as r}from"./constants.js";const e=t=>t.toLowerCase().substring(0,2),o=t=>Boolean(t)&&t.length>=n&&t.length<=r;function l(t,n){if(!t||"string"!=typeof t)return null;const r=t.toLowerCase(),o=n.find(t=>t.toLowerCase()===r);if(o)return o;const l=e(t);return n.find(t=>e(t)===l)||null}function s(t){const n=t.replace("_","-");if(/^([a-z]{2})(-)([A-Z]{2})$/.test(n))return n;const[r,e]=n.split("-");if(!r||!e)return null;const o=[r.toLowerCase(),e.toUpperCase()].join("-");return 5===o.length?o:null}const u=t=>{try{return Intl.NumberFormat.supportedLocalesOf([t])[0]??null}catch{return null}};function c(n){if("string"!=typeof n)return t;const r=n.replace(/_/g,"-").split("-");for(;r.length;){const t=u(r.join("-"));if(t)return t;r.pop()}return t}function i(n,r){if(!o(n))return t;const e=s(n);return e&&r.includes(e)?e:l(e||n,r)||t}function a(t={}){return Object.keys(t).reduce((n,r)=>{if(!o(r))return n;return n[s(r)||e(r)]=t[r],n},{})}const p=(t,n)=>t.replace(/%{(\w+)}/g,(t,r)=>n[r]||""),f=(t,n,r={})=>{const{values:e={},count:o=0}=r,l=`${n}__plural`,s=t=>`${n}__${t}`;return Object.prototype.hasOwnProperty.call(t,s(o))?p(t[s(o)],e):Object.prototype.hasOwnProperty.call(t,l)&&o>1?p(t[l],e):Object.prototype.hasOwnProperty.call(t,n)?p(t[n],e):null},h=(t,n)=>{const r=t.split(/%#(.*?)%#/gm);if(n.length!==Math.floor(r.length/2))throw Error("The number of functions provided does not match the number of elements in the translation string.");return r.map((t,r)=>{const e=Math.floor(r/2);return r%2==0?t:n[e](t)})};export{a as formatCustomTranslations,s as formatLocaleToLanguageCountryLocale,f as getTranslation,h as interpolateElement,l as matchLocale,i as parseLocale,c as resolveFormattingLocale};
2
2
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../src/language/utils.ts"],"sourcesContent":["import { h } from 'preact';\nimport { CustomTranslations } from './types';\nimport { DEFAULT_LOCALE, LOCALE_NAME_MAX_LENGTH, LOCALE_NAME_MIN_LENGTH } from './constants';\n\n/**\n * @description Convert to ISO 639-1\n */\nconst toTwoLetterCode = (locale: string): string => locale.toLowerCase().substring(0, 2);\n\n/**\n * @description Checks if the locale length is valid\n * @param locale - The locale to check\n * @returns true if the locale length is valid, false otherwise\n */\nconst isLocaleLenghtValid = (locale: string): boolean =>\n Boolean(locale) && locale.length >= LOCALE_NAME_MIN_LENGTH && locale.length <= LOCALE_NAME_MAX_LENGTH;\n\n/**\n * Matches a string with one of the locales\n *\n * @param locale - The locale to match\n * @param supportedLocales - Array of possible locales\n *\n * @example\n * matchLocale('en-GB', ['en-US', 'es-ES']);\n * // returns 'en-US'\n */\nexport function matchLocale(locale: string, supportedLocales: readonly string[]): string | null {\n if (!locale || typeof locale !== 'string') return null;\n\n const lowerLocale = locale.toLowerCase();\n const exactMatch = supportedLocales.find(supLoc => supLoc.toLowerCase() === lowerLocale);\n\n if (exactMatch) return exactMatch;\n\n const localeTwoLetter = toTwoLetterCode(locale);\n return supportedLocales.find(supLoc => toTwoLetterCode(supLoc) === localeTwoLetter) || null;\n}\n\n/**\n * Returns a locale with the proper format.\n *\n * @param localeParam - Locale example: 'En_us' or 'en-US'\n *\n * @example\n * formatLocaleToLanguageCountryLocale('En_us');\n * // returns 'en-US'\n */\nexport function formatLocaleToLanguageCountryLocale(localeParam: string): string | null {\n const locale = localeParam.replace('_', '-');\n const format = /^([a-z]{2})(-)([A-Z]{2})$/;\n\n // If it's already formatted, return the locale\n if (format.test(locale)) return locale;\n\n // Split the string in two\n const [languageCode, countryCode] = locale.split('-');\n\n // If the locale or the country codes are missing, return null\n if (!languageCode || !countryCode) return null;\n\n // Ensure correct format and join the strings back together\n const fullLocale = [languageCode.toLowerCase(), countryCode.toUpperCase()].join('-');\n\n return fullLocale.length === 5 ? fullLocale : null;\n}\n\nexport function parseLocale(locale: string, supportedLocales: readonly string[]): string {\n if (!isLocaleLenghtValid(locale)) return DEFAULT_LOCALE;\n\n const formattedLocale = formatLocaleToLanguageCountryLocale(locale);\n const hasMatch = formattedLocale && supportedLocales.includes(formattedLocale);\n\n if (hasMatch) return formattedLocale;\n\n return matchLocale(formattedLocale || locale, supportedLocales) || DEFAULT_LOCALE;\n}\n\n/**\n * @description Makes sure that if custom translation is defined using not properly formatted locale keys, then it gets formatted correctly\n *\n * @example { en_US: { ... }} will be adjusted to { 'en-US': { ... }} . { ar: { ... }} is kept as is.\n */\nexport function formatCustomTranslations(customTranslations: CustomTranslations = {}): CustomTranslations {\n return Object.keys(customTranslations).reduce<CustomTranslations>((memo, localeKey) => {\n if (!isLocaleLenghtValid(localeKey)) return memo;\n\n const locale = formatLocaleToLanguageCountryLocale(localeKey) || toTwoLetterCode(localeKey);\n memo[locale] = customTranslations[localeKey];\n return memo;\n }, {});\n}\n\nconst replaceTranslationValues = (translation: string, values: Record<string, string>) => {\n return translation.replace(/%{(\\w+)}/g, (_, k) => values[k] || '');\n};\n\n/**\n * Returns a translation string by key\n * @param translations -\n * @param key -\n * @param options -\n *\n * @internal\n */\nexport const getTranslation = (\n translations: Record<string, string>,\n key: string,\n options: { values?: Record<string, string>; count?: number } = {}\n): string | null => {\n const { values = {}, count = 0 } = options;\n const keyPlural = `${key}__plural`;\n const keyForCount = (count: number) => `${key}__${count}`;\n\n if (Object.prototype.hasOwnProperty.call(translations, keyForCount(count))) {\n // Find key__count translation key\n return replaceTranslationValues(translations[keyForCount(count)], values);\n } else if (Object.prototype.hasOwnProperty.call(translations, keyPlural) && count > 1) {\n // Find key__plural translation key, if count greater than 1 (e.g. myTranslation__plural)\n return replaceTranslationValues(translations[keyPlural], values);\n } else if (Object.prototype.hasOwnProperty.call(translations, key)) {\n // Find key translation key (e.g. myTranslation)\n return replaceTranslationValues(translations[key], values);\n }\n\n return null;\n};\n\n/**\n * Injects JSX elements in a middle of a translation and returns a JSX array\n * The input string should use %# as the token to know where to insert the component\n * @param translation - Translation string\n * @param renderFunctions - An array function that renders JSX elements\n */\nexport const interpolateElement = (translation: string, renderFunctions: Array<(translation: string) => h.JSX.Element | string>) => {\n // splits by regex group, it guarantees that it only splits with 2 tokens (%#)\n const matches = translation.split(/%#(.*?)%#/gm);\n\n if (renderFunctions.length !== Math.floor(matches.length / 2)) {\n throw Error('The number of functions provided does not match the number of elements in the translation string.');\n }\n\n // the map will create an array of JSX / string elements, this syntax in accepted in JSX/react to render elements\n return matches.map((term, index) => {\n // math to get the index of the renderFunction that should be used\n // since we split on tokens, that means the index of the render function is half of the index of the string\n const indexInFunctionArray = Math.floor(index / 2);\n return index % 2 === 0 ? term : renderFunctions[indexInFunctionArray](term);\n });\n};\n"],"names":["toTwoLetterCode","locale","toLowerCase","substring","isLocaleLenghtValid","Boolean","length","LOCALE_NAME_MIN_LENGTH","LOCALE_NAME_MAX_LENGTH","matchLocale","supportedLocales","lowerLocale","exactMatch","find","supLoc","localeTwoLetter","formatLocaleToLanguageCountryLocale","localeParam","replace","test","languageCode","countryCode","split","fullLocale","toUpperCase","join","parseLocale","DEFAULT_LOCALE","formattedLocale","includes","formatCustomTranslations","customTranslations","Object","keys","reduce","memo","localeKey","replaceTranslationValues","translation","values","_","k","getTranslation","translations","key","options","count","keyPlural","keyForCount","prototype","hasOwnProperty","call","interpolateElement","renderFunctions","matches","Math","floor","Error","map","term","index","indexInFunctionArray"],"mappings":"wGAOA,MAAMA,EAAmBC,GAA2BA,EAAOC,cAAcC,UAAU,EAAG,GAOhFC,EAAuBH,GACzBI,QAAQJ,IAAWA,EAAOK,QAAUC,GAA0BN,EAAOK,QAAUE,EAY5E,SAASC,EAAYR,EAAgBS,GACxC,IAAKT,GAA4B,iBAAXA,EAAqB,OAAO,KAElD,MAAMU,EAAcV,EAAOC,cACrBU,EAAaF,EAAiBG,KAAKC,GAAUA,EAAOZ,gBAAkBS,GAE5E,GAAIC,EAAY,OAAOA,EAEvB,MAAMG,EAAkBf,EAAgBC,GACxC,OAAOS,EAAiBG,KAAKC,GAAUd,EAAgBc,KAAYC,IAAoB,IAC3F,CAWO,SAASC,EAAoCC,GAChD,MAAMhB,EAASgB,EAAYC,QAAQ,IAAK,KAIxC,GAHe,4BAGJC,KAAKlB,GAAS,OAAOA,EAGhC,MAAOmB,EAAcC,GAAepB,EAAOqB,MAAM,KAGjD,IAAKF,IAAiBC,EAAa,OAAO,KAG1C,MAAME,EAAa,CAACH,EAAalB,cAAemB,EAAYG,eAAeC,KAAK,KAEhF,OAA6B,IAAtBF,EAAWjB,OAAeiB,EAAa,IAClD,CA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 {"version":3,"file":"utils.js","sources":["../../../src/language/utils.ts"],"sourcesContent":["import { h } from 'preact';\nimport { CustomTranslations } from './types';\nimport { DEFAULT_LOCALE, LOCALE_NAME_MAX_LENGTH, LOCALE_NAME_MIN_LENGTH } from './constants';\n\n/**\n * @description Convert to ISO 639-1\n */\nconst toTwoLetterCode = (locale: string): string => locale.toLowerCase().substring(0, 2);\n\n/**\n * @description Checks if the locale length is valid\n * @param locale - The locale to check\n * @returns true if the locale length is valid, false otherwise\n */\nconst isLocaleLenghtValid = (locale: string): boolean =>\n Boolean(locale) && locale.length >= LOCALE_NAME_MIN_LENGTH && locale.length <= LOCALE_NAME_MAX_LENGTH;\n\n/**\n * Matches a string with one of the locales\n *\n * @param locale - The locale to match\n * @param supportedLocales - Array of possible locales\n *\n * @example\n * matchLocale('en-GB', ['en-US', 'es-ES']);\n * // returns 'en-US'\n */\nexport function matchLocale(locale: string, supportedLocales: readonly string[]): string | null {\n if (!locale || typeof locale !== 'string') return null;\n\n const lowerLocale = locale.toLowerCase();\n const exactMatch = supportedLocales.find(supLoc => supLoc.toLowerCase() === lowerLocale);\n\n if (exactMatch) return exactMatch;\n\n const localeTwoLetter = toTwoLetterCode(locale);\n return supportedLocales.find(supLoc => toTwoLetterCode(supLoc) === localeTwoLetter) || null;\n}\n\n/**\n * Returns a locale with the proper format.\n *\n * @param localeParam - Locale example: 'En_us' or 'en-US'\n *\n * @example\n * formatLocaleToLanguageCountryLocale('En_us');\n * // returns 'en-US'\n */\nexport function formatLocaleToLanguageCountryLocale(localeParam: string): string | null {\n const locale = localeParam.replace('_', '-');\n const format = /^([a-z]{2})(-)([A-Z]{2})$/;\n\n // If it's already formatted, return the locale\n if (format.test(locale)) return locale;\n\n // Split the string in two\n const [languageCode, countryCode] = locale.split('-');\n\n // If the locale or the country codes are missing, return null\n if (!languageCode || !countryCode) return null;\n\n // Ensure correct format and join the strings back together\n const fullLocale = [languageCode.toLowerCase(), countryCode.toUpperCase()].join('-');\n\n return fullLocale.length === 5 ? fullLocale : null;\n}\n\n/**\n * Returns the locale as Intl spells it ('en_us' -> 'en-US'), or null when Intl has no data for it.\n */\nconst findIntlLocale = (locale: string): string | null => {\n try {\n return Intl.NumberFormat.supportedLocalesOf([locale])[0] ?? null;\n } catch {\n // Intl throws a RangeError on a malformed tag instead of returning an empty list\n return null;\n }\n};\n\n/**\n * Resolves the locale used for Intl formatting and for third-party SDKs. Unlike the translations\n * locale, it is not limited to the locales we ship translations for.\n *\n * Subtags are dropped one at a time, most specific first, because Intl rejects a tag outright when\n * any of its subtags is malformed. Dropping them keeps the part that Intl does understand, so\n * 'zh-Foo-CN' resolves to 'zh' instead of falling all the way back to the default.\n *\n * @param locale - Locale requested by the merchant\n */\nexport function resolveFormattingLocale(locale?: string): string {\n if (!locale || typeof locale !== 'string') return DEFAULT_LOCALE;\n\n const subtags = locale.replace(/_/g, '-').split('-');\n\n while (subtags.length) {\n const match = findIntlLocale(subtags.join('-'));\n if (match) return match;\n subtags.pop();\n }\n\n return DEFAULT_LOCALE;\n}\n\nexport function parseLocale(locale: string, supportedLocales: readonly string[]): string {\n if (!isLocaleLenghtValid(locale)) return DEFAULT_LOCALE;\n\n const formattedLocale = formatLocaleToLanguageCountryLocale(locale);\n const hasMatch = formattedLocale && supportedLocales.includes(formattedLocale);\n\n if (hasMatch) return formattedLocale;\n\n return matchLocale(formattedLocale || locale, supportedLocales) || DEFAULT_LOCALE;\n}\n\n/**\n * @description Makes sure that if custom translation is defined using not properly formatted locale keys, then it gets formatted correctly\n *\n * @example { en_US: { ... }} will be adjusted to { 'en-US': { ... }} . { ar: { ... }} is kept as is.\n */\nexport function formatCustomTranslations(customTranslations: CustomTranslations = {}): CustomTranslations {\n return Object.keys(customTranslations).reduce<CustomTranslations>((memo, localeKey) => {\n if (!isLocaleLenghtValid(localeKey)) return memo;\n\n const locale = formatLocaleToLanguageCountryLocale(localeKey) || toTwoLetterCode(localeKey);\n memo[locale] = customTranslations[localeKey];\n return memo;\n }, {});\n}\n\nconst replaceTranslationValues = (translation: string, values: Record<string, string>) => {\n return translation.replace(/%{(\\w+)}/g, (_, k) => values[k] || '');\n};\n\n/**\n * Returns a translation string by key\n * @param translations -\n * @param key -\n * @param options -\n *\n * @internal\n */\nexport const getTranslation = (\n translations: Record<string, string>,\n key: string,\n options: { values?: Record<string, string>; count?: number } = {}\n): string | null => {\n const { values = {}, count = 0 } = options;\n const keyPlural = `${key}__plural`;\n const keyForCount = (count: number) => `${key}__${count}`;\n\n if (Object.prototype.hasOwnProperty.call(translations, keyForCount(count))) {\n // Find key__count translation key\n return replaceTranslationValues(translations[keyForCount(count)], values);\n } else if (Object.prototype.hasOwnProperty.call(translations, keyPlural) && count > 1) {\n // Find key__plural translation key, if count greater than 1 (e.g. myTranslation__plural)\n return replaceTranslationValues(translations[keyPlural], values);\n } else if (Object.prototype.hasOwnProperty.call(translations, key)) {\n // Find key translation key (e.g. myTranslation)\n return replaceTranslationValues(translations[key], values);\n }\n\n return null;\n};\n\n/**\n * Injects JSX elements in a middle of a translation and returns a JSX array\n * The input string should use %# as the token to know where to insert the component\n * @param translation - Translation string\n * @param renderFunctions - An array function that renders JSX elements\n */\nexport const interpolateElement = (translation: string, renderFunctions: Array<(translation: string) => h.JSX.Element | string>) => {\n // splits by regex group, it guarantees that it only splits with 2 tokens (%#)\n const matches = translation.split(/%#(.*?)%#/gm);\n\n if (renderFunctions.length !== Math.floor(matches.length / 2)) {\n throw Error('The number of functions provided does not match the number of elements in the translation string.');\n }\n\n // the map will create an array of JSX / string elements, this syntax in accepted in JSX/react to render elements\n return matches.map((term, index) => {\n // math to get the index of the renderFunction that should be used\n // since we split on tokens, that means the index of the render function is half of the index of the string\n const indexInFunctionArray = Math.floor(index / 2);\n return index % 2 === 0 ? term : renderFunctions[indexInFunctionArray](term);\n });\n};\n"],"names":["toTwoLetterCode","locale","toLowerCase","substring","isLocaleLenghtValid","Boolean","length","LOCALE_NAME_MIN_LENGTH","LOCALE_NAME_MAX_LENGTH","matchLocale","supportedLocales","lowerLocale","exactMatch","find","supLoc","localeTwoLetter","formatLocaleToLanguageCountryLocale","localeParam","replace","test","languageCode","countryCode","split","fullLocale","toUpperCase","join","findIntlLocale","Intl","NumberFormat","supportedLocalesOf","resolveFormattingLocale","DEFAULT_LOCALE","subtags","match","pop","parseLocale","formattedLocale","includes","formatCustomTranslations","customTranslations","Object","keys","reduce","memo","localeKey","replaceTranslationValues","translation","values","_","k","getTranslation","translations","key","options","count","keyPlural","keyForCount","prototype","hasOwnProperty","call","interpolateElement","renderFunctions","matches","Math","floor","Error","map","term","index","indexInFunctionArray"],"mappings":"wGAOA,MAAMA,EAAmBC,GAA2BA,EAAOC,cAAcC,UAAU,EAAG,GAOhFC,EAAuBH,GACzBI,QAAQJ,IAAWA,EAAOK,QAAUC,GAA0BN,EAAOK,QAAUE,EAY5E,SAASC,EAAYR,EAAgBS,GACxC,IAAKT,GAA4B,iBAAXA,EAAqB,OAAO,KAElD,MAAMU,EAAcV,EAAOC,cACrBU,EAAaF,EAAiBG,KAAKC,GAAUA,EAAOZ,gBAAkBS,GAE5E,GAAIC,EAAY,OAAOA,EAEvB,MAAMG,EAAkBf,EAAgBC,GACxC,OAAOS,EAAiBG,KAAKC,GAAUd,EAAgBc,KAAYC,IAAoB,IAC3F,CAWO,SAASC,EAAoCC,GAChD,MAAMhB,EAASgB,EAAYC,QAAQ,IAAK,KAIxC,GAHe,4BAGJC,KAAKlB,GAAS,OAAOA,EAGhC,MAAOmB,EAAcC,GAAepB,EAAOqB,MAAM,KAGjD,IAAKF,IAAiBC,EAAa,OAAO,KAG1C,MAAME,EAAa,CAACH,EAAalB,cAAemB,EAAYG,eAAeC,KAAK,KAEhF,OAA6B,IAAtBF,EAAWjB,OAAeiB,EAAa,IAClD,CAKA,MAAMG,EAAkBzB,IACpB,IACI,OAAO0B,KAAKC,aAAaC,mBAAmB,CAAC5B,IAAS,IAAM,IAChE,CAAE,MAEE,OAAO,IACX,GAaG,SAAS6B,EAAwB7B,GAC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MAAM,eAElC,GAAIuC,EAAgBvD,SAAWyD,KAAKC,MAAMF,EAAQxD,OAAS,GACvD,MAAM2D,MAAM,qGAIhB,OAAOH,EAAQI,IAAI,CAACC,EAAMC,KAGtB,MAAMC,EAAuBN,KAAKC,MAAMI,EAAQ,GAChD,OAAOA,EAAQ,GAAM,EAAID,EAAON,EAAgBQ,GAAsBF"}
@@ -1,2 +1,2 @@
1
- import r from"./constants/currency-decimals.js";import{currencyMinorUnitsConfig as t}from"./constants/currency-minor-units.js";const n=t=>r[t]||100,e=(r,t)=>{const e=n(t);return parseInt(String(r),10)/e},c=(r,n,c,o={})=>{const s=r.toString(),u=e(s,c),y=n.replace("_","-"),i={style:"currency",currency:c,currencyDisplay:"symbol",...t[c]?{...o,...t[c]}:o};try{return u.toLocaleString(y,i)}catch(r){return s}},o=r=>{if(!r||"object"!=typeof r)return!1;const t="number"==typeof r.value&&!Number.isNaN(r.value),n="string"==typeof r.currency&&r.currency.length>0,e=void 0===r.currencyDisplay||"string"==typeof r.currencyDisplay;return t&&n&&e};export{e as getDecimalAmount,n as getDivider,c as getLocalisedAmount,o as isAmountValid};
1
+ import r from"./constants/currency-decimals.js";import{currencyMinorUnitsConfig as t}from"./constants/currency-minor-units.js";const n=t=>r[t]||100,c=(r,t)=>{const c=n(t);return parseInt(String(r),10)/c},e=(r,n,e,o={})=>{const s=r.toString(),u=c(s,e),y={style:"currency",currency:e,currencyDisplay:"symbol",...t[e]?{...o,...t[e]}:o};try{return u.toLocaleString(n,y)}catch(r){return s}},o=r=>{if(!r||"object"!=typeof r)return!1;const t="number"==typeof r.value&&!Number.isNaN(r.value),n="string"==typeof r.currency&&r.currency.length>0,c=void 0===r.currencyDisplay||"string"==typeof r.currencyDisplay;return t&&n&&c};export{c as getDecimalAmount,n as getDivider,e as getLocalisedAmount,o as isAmountValid};
2
2
  //# sourceMappingURL=amount-util.js.map