@adyen/adyen-web 6.34.0 → 6.35.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.
- package/dist/cjs/adyen.css +4 -5
- package/dist/cjs/adyen.css.map +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +86 -44
- package/dist/es/adyen.css +4 -5
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/ApplePay/ApplePay.js.map +1 -1
- package/dist/es/components/ApplePay/services/ApplePayService.js.map +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferInput/BankTransferInput.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/BrandIcon.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/BrandIcon.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFields.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFields.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardNumber.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/CardNumber.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.js +2 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.js.map +1 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js +2 -0
- package/dist/es/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js.map +1 -0
- package/dist/es/components/Card/components/CardInput/types.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/useSRPanelForCardInputErrors.js +1 -1
- package/dist/es/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es/components/Card/constants.js.map +1 -1
- package/dist/es/components/CustomCard/CustomCard.js +1 -1
- package/dist/es/components/CustomCard/CustomCard.js.map +1 -1
- package/dist/es/components/CustomCard/CustomCardInput/CustomCardInput.js +1 -1
- package/dist/es/components/CustomCard/CustomCardInput/CustomCardInput.js.map +1 -1
- package/dist/es/components/Dragonpay/Dragonpay.js +1 -1
- package/dist/es/components/Dragonpay/Dragonpay.js.map +1 -1
- package/dist/es/components/Dragonpay/components/DragonpayInput/DragonpayInput.js +1 -1
- package/dist/es/components/Dragonpay/components/DragonpayInput/DragonpayInput.js.map +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
- package/dist/es/components/Econtext/Econtext.js +1 -1
- package/dist/es/components/Econtext/Econtext.js.map +1 -1
- package/dist/es/components/Econtext/components/EcontextInput/EcontextInput.js.map +1 -1
- package/dist/es/components/Giftcard/components/GiftcardComponent.js +1 -1
- package/dist/es/components/Giftcard/components/GiftcardComponent.js.map +1 -1
- package/dist/es/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es/components/PayTo/components/PayToNameFields.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/UPI/components/UPIMandate/UPIMandate.js.map +1 -1
- package/dist/es/components/internal/Address/validate.formats.js +1 -1
- package/dist/es/components/internal/Address/validate.formats.js.map +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es/components/internal/FormFields/InputDate/utils.js +1 -1
- package/dist/es/components/internal/FormFields/InputDate/utils.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SFPUtils.js +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SFPUtils.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/extensions.js +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/initCSF.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/partials/processBrand.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/partials/processBrand.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/cardType.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/cardType.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/iframes/postMessageValidation.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/utils/iframes/postMessageValidation.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js.map +1 -1
- package/dist/es/core/Analytics/Analytics.js +1 -1
- package/dist/es/core/Analytics/Analytics.js.map +1 -1
- package/dist/es/core/Analytics/AnalyticsService.js.map +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es/core/ProcessResponse/PaymentMethods/filters.js +1 -1
- package/dist/es/core/ProcessResponse/PaymentMethods/filters.js.map +1 -1
- package/dist/es/core/config.js +1 -1
- package/dist/es/core/config.js.map +1 -1
- package/dist/es/core/core.js +1 -1
- package/dist/es/core/core.js.map +1 -1
- package/dist/es/external/preact/compat/dist/compat.js +1 -1
- package/dist/es/external/preact/compat/dist/compat.js.map +1 -1
- package/dist/es/external/preact/dist/preact.js +1 -1
- package/dist/es/external/preact/dist/preact.js.map +1 -1
- package/dist/es/index.d.ts +86 -44
- package/dist/es/language/utils.js +1 -1
- package/dist/es/language/utils.js.map +1 -1
- package/dist/es/utils/Script.js.map +1 -1
- package/dist/es/utils/createSdkData.js +1 -1
- package/dist/es/utils/createSdkData.js.map +1 -1
- package/dist/es/utils/debounce.js.map +1 -1
- package/dist/es/utils/getErrorMessage.js +1 -1
- package/dist/es/utils/getErrorMessage.js.map +1 -1
- package/dist/es/utils/hookUtils.js.map +1 -1
- package/dist/es/utils/promiseTimeout.js.map +1 -1
- package/dist/es-legacy/adyen.css +4 -5
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/ApplePay/ApplePay.js.map +1 -1
- package/dist/es-legacy/components/ApplePay/services/ApplePayService.js.map +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferInput/BankTransferInput.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/BrandIcon.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/BrandIcon.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFields.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFields.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardNumber.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/CardNumber.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.js +2 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.js.map +1 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js +2 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/DualBrandSelector.module.scss.js.map +1 -0
- package/dist/es-legacy/components/Card/components/CardInput/types.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/useSRPanelForCardInputErrors.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es-legacy/components/Card/constants.js.map +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCard.js +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCard.js.map +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCardInput/CustomCardInput.js +1 -1
- package/dist/es-legacy/components/CustomCard/CustomCardInput/CustomCardInput.js.map +1 -1
- package/dist/es-legacy/components/Dragonpay/Dragonpay.js +1 -1
- package/dist/es-legacy/components/Dragonpay/Dragonpay.js.map +1 -1
- package/dist/es-legacy/components/Dragonpay/components/DragonpayInput/DragonpayInput.js +1 -1
- package/dist/es-legacy/components/Dragonpay/components/DragonpayInput/DragonpayInput.js.map +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
- package/dist/es-legacy/components/Econtext/Econtext.js +1 -1
- package/dist/es-legacy/components/Econtext/Econtext.js.map +1 -1
- package/dist/es-legacy/components/Econtext/components/EcontextInput/EcontextInput.js.map +1 -1
- package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js +1 -1
- package/dist/es-legacy/components/Giftcard/components/GiftcardComponent.js.map +1 -1
- package/dist/es-legacy/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es-legacy/components/PayTo/components/PayToNameFields.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIMandate/UPIMandate.js.map +1 -1
- package/dist/es-legacy/components/internal/Address/validate.formats.js +1 -1
- package/dist/es-legacy/components/internal/Address/validate.formats.js.map +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Field/Field.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/InputDate/utils.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/InputDate/utils.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SFPUtils.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SFPUtils.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleBrandFromBinLookup.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/initCSF.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/partials/processBrand.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/partials/processBrand.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/cardType.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/cardType.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/iframes/postMessageValidation.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/utils/iframes/postMessageValidation.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js.map +1 -1
- package/dist/es-legacy/core/Analytics/Analytics.js +1 -1
- package/dist/es-legacy/core/Analytics/Analytics.js.map +1 -1
- package/dist/es-legacy/core/Analytics/AnalyticsService.js.map +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js +1 -1
- package/dist/es-legacy/core/Analytics/events/AnalyticsInfoEvent.js.map +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentMethods/filters.js +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentMethods/filters.js.map +1 -1
- package/dist/es-legacy/core/config.js +1 -1
- package/dist/es-legacy/core/config.js.map +1 -1
- package/dist/es-legacy/core/core.js +1 -1
- package/dist/es-legacy/core/core.js.map +1 -1
- package/dist/es-legacy/external/preact/compat/dist/compat.js +1 -1
- package/dist/es-legacy/external/preact/compat/dist/compat.js.map +1 -1
- package/dist/es-legacy/external/preact/dist/preact.js +1 -1
- package/dist/es-legacy/external/preact/dist/preact.js.map +1 -1
- package/dist/es-legacy/language/utils.js +1 -1
- package/dist/es-legacy/language/utils.js.map +1 -1
- package/dist/es-legacy/utils/Script.js.map +1 -1
- package/dist/es-legacy/utils/createSdkData.js +1 -1
- package/dist/es-legacy/utils/createSdkData.js.map +1 -1
- package/dist/es-legacy/utils/debounce.js.map +1 -1
- package/dist/es-legacy/utils/getErrorMessage.js +1 -1
- package/dist/es-legacy/utils/getErrorMessage.js.map +1 -1
- package/dist/es-legacy/utils/hookUtils.js.map +1 -1
- package/dist/es-legacy/utils/promiseTimeout.js.map +1 -1
- package/package.json +27 -27
- package/styles/adyen.css +4 -5
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js +0 -2
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js.map +0 -1
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js +0 -2
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +0 -1
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js +0 -2
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioButtonIcon.js.map +0 -1
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js +0 -2
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Component as e,createElement as t}from"../../../../external/preact/dist/preact.js";import r from"./DoFingerprint3DS2.js";import{isErrorObject as o,createOldFingerprintResolveData as s,createFingerprintResolveData as n,prepareFingerPrintData as i}from"../utils.js";import{isValidHttpUrl as a}from"../../../../utils/isValidURL.js";import{THREEDS2_FINGERPRINT_ERROR as p,MISSING_TOKEN_IN_ACTION_MSG as m,TIMEOUT as l,THREEDS2_NUM as c,THREEDS2_FINGERPRINT as h}from"../../constants.js";import{AnalyticsLogEvent as d,LogEventSubtype as S,LogEventType as D}from"../../../../core/Analytics/events/AnalyticsLogEvent.js";import{ErrorEventCode as u,ErrorEventType as g,AnalyticsErrorEvent as f}from"../../../../core/Analytics/events/AnalyticsErrorEvent.js";function E(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class C extends e{componentDidMount(){if(!o(this.state.fingerPrintData)){const e="test"===this.props.environment&&this.props._environmentUrls?.api?.includes("http://localhost:8080"),{threeDSMethodURL:t,threeDSMethodNotificationURL:r,postMessageDomain:o,threeDSServerTransID:s}=this.state.fingerPrintData;if(!a(t,e))return this.setStatusComplete({threeDSCompInd:"U"},{errorCode:u.THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL,message:`${p}: Decoded token is missing a valid threeDSMethodURL property`}),void console.debug("### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL");const n=a(r,e),i=a(o,e),m=s?.length;if(!n||!i||!m)return this.setStatusComplete({threeDSCompInd:"N"},{errorCode:u.THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS,message:`${p}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`}),void console.debug("### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)");this.setState({status:"retrievingFingerPrint"})}else{const e=this.state.fingerPrintData.error,t=e.
|
|
1
|
+
import{Component as e,createElement as t}from"../../../../external/preact/dist/preact.js";import r from"./DoFingerprint3DS2.js";import{isErrorObject as o,createOldFingerprintResolveData as s,createFingerprintResolveData as n,prepareFingerPrintData as i}from"../utils.js";import{isValidHttpUrl as a}from"../../../../utils/isValidURL.js";import{THREEDS2_FINGERPRINT_ERROR as p,MISSING_TOKEN_IN_ACTION_MSG as m,TIMEOUT as l,THREEDS2_NUM as c,THREEDS2_FINGERPRINT as h}from"../../constants.js";import{AnalyticsLogEvent as d,LogEventSubtype as S,LogEventType as D}from"../../../../core/Analytics/events/AnalyticsLogEvent.js";import{ErrorEventCode as u,ErrorEventType as g,AnalyticsErrorEvent as f}from"../../../../core/Analytics/events/AnalyticsErrorEvent.js";function E(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class C extends e{componentDidMount(){if(!o(this.state.fingerPrintData)){const e="test"===this.props.environment&&this.props._environmentUrls?.api?.includes("http://localhost:8080"),{threeDSMethodURL:t,threeDSMethodNotificationURL:r,postMessageDomain:o,threeDSServerTransID:s}=this.state.fingerPrintData;if(!a(t,e))return this.setStatusComplete({threeDSCompInd:"U"},{errorCode:u.THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL,message:`${p}: Decoded token is missing a valid threeDSMethodURL property`}),void console.debug("### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL");const n=a(r,e),i=a(o,e),m=s?.length;if(!n||!i||!m)return this.setStatusComplete({threeDSCompInd:"N"},{errorCode:u.THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS,message:`${p}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`}),void console.debug("### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)");this.setState({status:"retrievingFingerPrint"})}else{const e=this.state.fingerPrintData.error,t=e.includes(m)?u.THREEDS2_ACTION_IS_MISSING_TOKEN:u.THREEDS2_TOKEN_DECODE_OR_PARSING_FAILED;this.setStatusComplete({threeDSCompInd:"N"},{errorCode:t,message:`${p}: ${e}`}),console.debug("### PrepareFingerprint3DS2:: token does not exist or could not be base64 decoded &/or JSON.parsed")}}setStatusComplete(e,t=null){this.setState({status:"complete"},()=>{const r=(this.props.isMDFlow?s:n)(this.props.dataKey,e,this.props.paymentData);let o;const i=t||e;if(i.errorCode){const e={code:i.errorCode===l?u.THREEDS2_TIMEOUT:i.errorCode,errorType:g.threeDS2};o=new f({component:this.props.type,message:i.message,...e}),this.props.onSubmitAnalytics(o)}let a;switch(e?.threeDSCompInd){case"Y":a="success";break;case"N":a=t?t.errorCode===l?l:"failedInternal":"failed";break;case"U":a="noThreeDSMethodURL"}o=new d({component:this.props.type,type:D.threeDS2,subType:S.fingerprintCompleted,message:`${c} fingerprinting has completed`,result:a}),this.props.onSubmitAnalytics(o),this.props.onComplete(r)})}render({showSpinner:e},{status:o,fingerPrintData:s}){return"retrievingFingerPrint"===o?t(r,{onCompleteFingerprint:e=>{this.setStatusComplete(e.result)},onErrorFingerprint:e=>{const t={errorCode:e.errorCode,message:`${h}: ${e.errorCode}`};this.setStatusComplete(e.result,t)},showSpinner:e,...s,onActionHandled:this.props.onActionHandled,onFormSubmit:this.onFormSubmit}):null}constructor(e){super(e),E(this,"onFormSubmit",e=>{const t=new d({component:this.props.type,type:D.threeDS2,subType:S.fingerprintDataSentWeb,message:e});this.props.onSubmitAnalytics(t)});const{token:t,notificationURL:r}=this.props;if(t){const e=i({token:t,notificationURL:r});this.state={status:"init",fingerPrintData:e}}else this.state={fingerPrintData:{success:!1,error:m}},console.debug(`${p}: ${m}`)}}E(C,"type","scheme"),E(C,"defaultProps",{onComplete:()=>{},onError:()=>{},paymentData:"",showSpinner:!0,isMDFlow:!1});export{C as default};
|
|
2
2
|
//# sourceMappingURL=PrepareFingerprint3DS2.js.map
|
package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrepareFingerprint3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoFingerprint3DS2 from './DoFingerprint3DS2';\nimport { createFingerprintResolveData, createOldFingerprintResolveData, isErrorObject, prepareFingerPrintData } from '../utils';\nimport { PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State } from './types';\nimport { FingerPrintData, ResultObject, ErrorCodeObject, LegacyFingerprintResolveData, FingerprintResolveData } from '../../types';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { THREEDS2_FINGERPRINT, THREEDS2_FINGERPRINT_ERROR, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG, TIMEOUT } from '../../constants';\nimport { AnalyticsLogEvent, LogEventSubtype, LogEventType } from '../../../../core/Analytics/events/AnalyticsLogEvent';\nimport { AbstractAnalyticsEvent } from '../../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { AnalyticsErrorEvent, ErrorEventCode, ErrorEventType } from '../../../../core/Analytics/events/AnalyticsErrorEvent';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static readonly type = 'scheme';\n\n public static readonly defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n const { token, notificationURL } = this.props; // See comments on prepareFingerPrintData regarding notificationURL\n\n if (token) {\n const fingerPrintData: FingerPrintData | ErrorObject = prepareFingerPrintData({ token, notificationURL });\n\n this.state = {\n status: 'init',\n fingerPrintData: fingerPrintData as FingerPrintData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { fingerPrintData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_FINGERPRINT_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n component: this.props.type,\n type: LogEventType.threeDS2,\n subType: LogEventSubtype.fingerprintDataSentWeb,\n message: msg\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasFingerPrintData = !isErrorObject(this.state.fingerPrintData);\n\n if (hasFingerPrintData) {\n const shouldAllowHttpDomains =\n /** Allow http urls if in development and testing against localhost:8080 */\n (process.env.NODE_ENV === 'development' && process.env.__CLIENT_ENV__?.indexOf('localhost:8080') > -1) ||\n /**\n * Allows the checkoutshopper demo on localhost:8080 to work -\n * requires a configuration in localhost of environment: 'test', _environmentUrls: {api: 'http://localhost:8080/'}\n */\n (this.props.environment === 'test' && this.props._environmentUrls?.api?.includes('http://localhost:8080'));\n\n /**\n * Check the structure of the created fingerPrintData\n */\n const { threeDSMethodURL, threeDSMethodNotificationURL, postMessageDomain, threeDSServerTransID } = this.state\n .fingerPrintData as FingerPrintData;\n\n const hasValid3DSMethodURL = isValidHttpUrl(threeDSMethodURL, shouldAllowHttpDomains);\n\n // Only render component if we have a threeDSMethodURL. Otherwise, exit with threeDSCompInd: 'U'\n if (!hasValid3DSMethodURL) {\n this.setStatusComplete(\n { threeDSCompInd: 'U' },\n {\n errorCode: ErrorEventCode.THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing a valid threeDSMethodURL property`\n }\n );\n\n /**\n * NOTE: we can now use this.props.isMDFlow to decide if we want to send any of these errors to the onError handler\n * - this is problematic in the regular flow since merchants tend to treat any calls to their onError handler as 'fatal',\n * but in the MDFlow we control what the onError handler does.\n */\n // if (this.props.isMDFlow) {}\n\n console.debug('### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL');\n return;\n }\n\n const hasValid3DSMethodNotificationURL = isValidHttpUrl(threeDSMethodNotificationURL, shouldAllowHttpDomains);\n const hasValidPostMessageDomain = isValidHttpUrl(postMessageDomain, shouldAllowHttpDomains);\n const hasTransServerID = threeDSServerTransID?.length;\n\n if (!hasValid3DSMethodNotificationURL || !hasValidPostMessageDomain || !hasTransServerID) {\n /**\n * NOTE: EMVCo_3DS_CoreSpec_v2.3.1_20220831.pdf states that we should return: threeDSCompInd: 'N'\n * when the fingerprinting process \"Did not run or did not successfully complete\"\n */\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode: ErrorEventCode.THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`\n }\n );\n\n console.debug(\n '### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)'\n );\n\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'retrievingFingerPrint' });\n //\n } else {\n // Only render component if we have fingerPrintData. Otherwise, complete with threeDSCompInd: 'N'\n\n const errorMsg: string = (this.state.fingerPrintData as ErrorObject).error;\n\n const errorCode =\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? ErrorEventCode.THREEDS2_ACTION_IS_MISSING_TOKEN\n : ErrorEventCode.THREEDS2_TOKEN_DECODE_OR_PARSING_FAILED;\n\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode,\n message: `${THREEDS2_FINGERPRINT_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n }\n );\n\n console.debug('### PrepareFingerprint3DS2:: token does not exist or could not be base64 decoded &/or JSON.parsed');\n }\n }\n\n setStatusComplete(resultObj: ResultObject, errorCodeObject: ErrorCodeObject = null) {\n this.setState({ status: 'complete' }, () => {\n /**\n * Create the data in the way that the /details endpoint expects.\n * This is different for the flow triggered by the threeds2InMDFlow process than for the new, v67, 'threeDS2' action\n */\n const resolveDataFunction = this.props.isMDFlow ? createOldFingerprintResolveData : createFingerprintResolveData;\n const data: LegacyFingerprintResolveData | FingerprintResolveData = resolveDataFunction(\n this.props.dataKey,\n resultObj,\n this.props.paymentData\n );\n\n let event: AbstractAnalyticsEvent;\n\n /** Are we in an error scenario? If so, submit analytics about it */\n const finalResObject = errorCodeObject ? errorCodeObject : resultObj;\n if (finalResObject.errorCode) {\n const errorTypeAndCode = {\n code: finalResObject.errorCode === TIMEOUT ? ErrorEventCode.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: ErrorEventType.threeDS2\n };\n\n /**\n * Timeout or data parsing problems:\n *\n * (threeDSCompInd:\"U\"):\n * - Decoded token is missing a valid threeDSMethodURL property,\n * or, (threeDSCompInd:\"N\"):\n * - Fingerprint process has timed out,\n * also, (threeDSCompInd:\"N\"):\n * - Missing \"token\" property from threeDS2 action\n * - or, decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)\n * - or, token could not be base64 decoded &/or JSON.parsed\n */\n\n event = new AnalyticsErrorEvent({\n component: this.props.type,\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n });\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(event);\n }\n\n /** Calculate \"result\" for analytics */\n let result: string;\n\n switch (resultObj?.threeDSCompInd) {\n case 'Y':\n result = 'success';\n break;\n case 'N': {\n if (!errorCodeObject) {\n result = 'failed'; // 'failed' is the result returned from the threeDSMethodURL\n } else {\n result = errorCodeObject.errorCode === TIMEOUT ? TIMEOUT : 'failedInternal'; // timed-out; or, 'failed' as a result of internal checks\n }\n break;\n }\n case 'U':\n result = 'noThreeDSMethodURL';\n break;\n default:\n }\n\n /**\n * The fingerprint process is completed, one way or another.\n * The resultObj will be {threeDSCompInd:\"Y\"} in the case of success,\n * else {threeDSCompInd:\"U\"} or {threeDSCompInd:\"N\"} - if we've had some kind of timeout or data parsing problem (as described above)\n */\n\n event = new AnalyticsLogEvent({\n component: this.props.type,\n type: LogEventType.threeDS2,\n subType: LogEventSubtype.fingerprintCompleted,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n result\n });\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to callSubmit3DS2Fingerprint (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n render({ showSpinner }, { status, fingerPrintData }) {\n if (status === 'retrievingFingerPrint') {\n return (\n <DoFingerprint3DS2\n onCompleteFingerprint={fingerprint => {\n this.setStatusComplete(fingerprint.result);\n }}\n onErrorFingerprint={fingerprint => {\n /**\n * Called when fingerprint times-out (which is still a valid scenario)...\n */\n const timeoutObject: ErrorCodeObject = {\n errorCode: fingerprint.errorCode, // 'timeout'\n message: `${THREEDS2_FINGERPRINT}: ${fingerprint.errorCode}`\n };\n\n this.setStatusComplete(fingerprint.result, timeoutObject); // fingerprint.result = threeDSCompInd: 'N'\n }}\n showSpinner={showSpinner}\n {...fingerPrintData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareFingerprint3DS2;\n"],"names":["PrepareFingerprint3DS2","Component","componentDidMount","isErrorObject","this","state","fingerPrintData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","threeDSMethodURL","threeDSMethodNotificationURL","postMessageDomain","threeDSServerTransID","isValidHttpUrl","setStatusComplete","threeDSCompInd","errorCode","ErrorEventCode","THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL","message","THREEDS2_FINGERPRINT_ERROR","console","debug","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","indexOf","MISSING_TOKEN_IN_ACTION_MSG","THREEDS2_ACTION_IS_MISSING_TOKEN","THREEDS2_TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","isMDFlow","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","paymentData","event","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ErrorEventType","threeDS2","AnalyticsErrorEvent","component","type","onSubmitAnalytics","result","AnalyticsLogEvent","LogEventType","subType","LogEventSubtype","fingerprintCompleted","THREEDS2_NUM","onComplete","render","showSpinner","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT","onActionHandled","onFormSubmit","constructor","super","_define_property","msg","fingerprintDataSentWeb","token","notificationURL","prepareFingerPrintData","success","defaultProps","onError"],"mappings":"22BAYA,MAAMA,UAA+BC,EAyCjCC,iBAAAA,GAGI,IAF4BC,EAAcC,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AoBlF,KAAKI,MAExC,GAAI6E,EAAO,CACP,MAAM/E,EAAiDiF,EAAuB,CAAEF,QAAOC,oBAEvFlF,KAAKC,MAAQ,CACT4B,OAAQ,OACR3B,gBAAiBA,EAEzB,MAEIF,KAAKC,MAAQ,CAAEC,gBAAiB,CAAEkF,SAAS,EAAOrD,MAAOE,IAEzDZ,QAAQC,MAAM,GAAGF,MAA+Ba,IAExD,EA3BA6C,EADElF,EACqB2D,OAAO,UAE9BuB,EAHElF,EAGqByF,eAAe,CAClCrB,WAAY,OACZsB,QAAS,OACT3C,YAAa,GACbuB,aAAa,EACb3B,UAAU"}
|
|
1
|
+
{"version":3,"file":"PrepareFingerprint3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoFingerprint3DS2 from './DoFingerprint3DS2';\nimport { createFingerprintResolveData, createOldFingerprintResolveData, isErrorObject, prepareFingerPrintData } from '../utils';\nimport { PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State } from './types';\nimport { FingerPrintData, ResultObject, ErrorCodeObject, LegacyFingerprintResolveData, FingerprintResolveData } from '../../types';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { THREEDS2_FINGERPRINT, THREEDS2_FINGERPRINT_ERROR, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG, TIMEOUT } from '../../constants';\nimport { AnalyticsLogEvent, LogEventSubtype, LogEventType } from '../../../../core/Analytics/events/AnalyticsLogEvent';\nimport { AbstractAnalyticsEvent } from '../../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { AnalyticsErrorEvent, ErrorEventCode, ErrorEventType } from '../../../../core/Analytics/events/AnalyticsErrorEvent';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static readonly type = 'scheme';\n\n public static readonly defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n const { token, notificationURL } = this.props; // See comments on prepareFingerPrintData regarding notificationURL\n\n if (token) {\n const fingerPrintData: FingerPrintData | ErrorObject = prepareFingerPrintData({ token, notificationURL });\n\n this.state = {\n status: 'init',\n fingerPrintData: fingerPrintData as FingerPrintData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { fingerPrintData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_FINGERPRINT_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n component: this.props.type,\n type: LogEventType.threeDS2,\n subType: LogEventSubtype.fingerprintDataSentWeb,\n message: msg\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasFingerPrintData = !isErrorObject(this.state.fingerPrintData);\n\n if (hasFingerPrintData) {\n const shouldAllowHttpDomains =\n /** Allow http urls if in development and testing against localhost:8080 */\n (process.env.NODE_ENV === 'development' && process.env.__CLIENT_ENV__?.includes('localhost:8080')) ||\n /**\n * Allows the checkoutshopper demo on localhost:8080 to work -\n * requires a configuration in localhost of environment: 'test', _environmentUrls: {api: 'http://localhost:8080/'}\n */\n (this.props.environment === 'test' && this.props._environmentUrls?.api?.includes('http://localhost:8080'));\n\n /**\n * Check the structure of the created fingerPrintData\n */\n const { threeDSMethodURL, threeDSMethodNotificationURL, postMessageDomain, threeDSServerTransID } = this.state\n .fingerPrintData as FingerPrintData;\n\n const hasValid3DSMethodURL = isValidHttpUrl(threeDSMethodURL, shouldAllowHttpDomains);\n\n // Only render component if we have a threeDSMethodURL. Otherwise, exit with threeDSCompInd: 'U'\n if (!hasValid3DSMethodURL) {\n this.setStatusComplete(\n { threeDSCompInd: 'U' },\n {\n errorCode: ErrorEventCode.THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing a valid threeDSMethodURL property`\n }\n );\n\n /**\n * NOTE: we can now use this.props.isMDFlow to decide if we want to send any of these errors to the onError handler\n * - this is problematic in the regular flow since merchants tend to treat any calls to their onError handler as 'fatal',\n * but in the MDFlow we control what the onError handler does.\n */\n // if (this.props.isMDFlow) {}\n\n console.debug('### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL');\n return;\n }\n\n const hasValid3DSMethodNotificationURL = isValidHttpUrl(threeDSMethodNotificationURL, shouldAllowHttpDomains);\n const hasValidPostMessageDomain = isValidHttpUrl(postMessageDomain, shouldAllowHttpDomains);\n const hasTransServerID = threeDSServerTransID?.length;\n\n if (!hasValid3DSMethodNotificationURL || !hasValidPostMessageDomain || !hasTransServerID) {\n /**\n * NOTE: EMVCo_3DS_CoreSpec_v2.3.1_20220831.pdf states that we should return: threeDSCompInd: 'N'\n * when the fingerprinting process \"Did not run or did not successfully complete\"\n */\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode: ErrorEventCode.THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`\n }\n );\n\n console.debug(\n '### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)'\n );\n\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'retrievingFingerPrint' });\n //\n } else {\n // Only render component if we have fingerPrintData. Otherwise, complete with threeDSCompInd: 'N'\n\n const errorMsg: string = (this.state.fingerPrintData as ErrorObject).error;\n\n const errorCode = errorMsg.includes(MISSING_TOKEN_IN_ACTION_MSG)\n ? ErrorEventCode.THREEDS2_ACTION_IS_MISSING_TOKEN\n : ErrorEventCode.THREEDS2_TOKEN_DECODE_OR_PARSING_FAILED;\n\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode,\n message: `${THREEDS2_FINGERPRINT_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n }\n );\n\n console.debug('### PrepareFingerprint3DS2:: token does not exist or could not be base64 decoded &/or JSON.parsed');\n }\n }\n\n setStatusComplete(resultObj: ResultObject, errorCodeObject: ErrorCodeObject = null) {\n this.setState({ status: 'complete' }, () => {\n /**\n * Create the data in the way that the /details endpoint expects.\n * This is different for the flow triggered by the threeds2InMDFlow process than for the new, v67, 'threeDS2' action\n */\n const resolveDataFunction = this.props.isMDFlow ? createOldFingerprintResolveData : createFingerprintResolveData;\n const data: LegacyFingerprintResolveData | FingerprintResolveData = resolveDataFunction(\n this.props.dataKey,\n resultObj,\n this.props.paymentData\n );\n\n let event: AbstractAnalyticsEvent;\n\n /** Are we in an error scenario? If so, submit analytics about it */\n const finalResObject = errorCodeObject ? errorCodeObject : resultObj;\n if (finalResObject.errorCode) {\n const errorTypeAndCode = {\n code: finalResObject.errorCode === TIMEOUT ? ErrorEventCode.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: ErrorEventType.threeDS2\n };\n\n /**\n * Timeout or data parsing problems:\n *\n * (threeDSCompInd:\"U\"):\n * - Decoded token is missing a valid threeDSMethodURL property,\n * or, (threeDSCompInd:\"N\"):\n * - Fingerprint process has timed out,\n * also, (threeDSCompInd:\"N\"):\n * - Missing \"token\" property from threeDS2 action\n * - or, decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)\n * - or, token could not be base64 decoded &/or JSON.parsed\n */\n\n event = new AnalyticsErrorEvent({\n component: this.props.type,\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n });\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(event);\n }\n\n /** Calculate \"result\" for analytics */\n let result: string;\n\n switch (resultObj?.threeDSCompInd) {\n case 'Y':\n result = 'success';\n break;\n case 'N': {\n if (!errorCodeObject) {\n result = 'failed'; // 'failed' is the result returned from the threeDSMethodURL\n } else {\n result = errorCodeObject.errorCode === TIMEOUT ? TIMEOUT : 'failedInternal'; // timed-out; or, 'failed' as a result of internal checks\n }\n break;\n }\n case 'U':\n result = 'noThreeDSMethodURL';\n break;\n default:\n }\n\n /**\n * The fingerprint process is completed, one way or another.\n * The resultObj will be {threeDSCompInd:\"Y\"} in the case of success,\n * else {threeDSCompInd:\"U\"} or {threeDSCompInd:\"N\"} - if we've had some kind of timeout or data parsing problem (as described above)\n */\n\n event = new AnalyticsLogEvent({\n component: this.props.type,\n type: LogEventType.threeDS2,\n subType: LogEventSubtype.fingerprintCompleted,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n result\n });\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to callSubmit3DS2Fingerprint (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n render({ showSpinner }, { status, fingerPrintData }) {\n if (status === 'retrievingFingerPrint') {\n return (\n <DoFingerprint3DS2\n onCompleteFingerprint={fingerprint => {\n this.setStatusComplete(fingerprint.result);\n }}\n onErrorFingerprint={fingerprint => {\n /**\n * Called when fingerprint times-out (which is still a valid scenario)...\n */\n const timeoutObject: ErrorCodeObject = {\n errorCode: fingerprint.errorCode, // 'timeout'\n message: `${THREEDS2_FINGERPRINT}: ${fingerprint.errorCode}`\n };\n\n this.setStatusComplete(fingerprint.result, timeoutObject); // fingerprint.result = threeDSCompInd: 'N'\n }}\n showSpinner={showSpinner}\n {...fingerPrintData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareFingerprint3DS2;\n"],"names":["PrepareFingerprint3DS2","Component","componentDidMount","isErrorObject","this","state","fingerPrintData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","threeDSMethodURL","threeDSMethodNotificationURL","postMessageDomain","threeDSServerTransID","isValidHttpUrl","setStatusComplete","threeDSCompInd","errorCode","ErrorEventCode","THREEDS2_TOKEN_IS_MISSING_THREEDSMETHODURL","message","THREEDS2_FINGERPRINT_ERROR","console","debug","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","THREEDS2_TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","MISSING_TOKEN_IN_ACTION_MSG","THREEDS2_ACTION_IS_MISSING_TOKEN","THREEDS2_TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","isMDFlow","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","paymentData","event","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ErrorEventType","threeDS2","AnalyticsErrorEvent","component","type","onSubmitAnalytics","result","AnalyticsLogEvent","LogEventType","subType","LogEventSubtype","fingerprintCompleted","THREEDS2_NUM","onComplete","render","showSpinner","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT","onActionHandled","onFormSubmit","constructor","super","_define_property","msg","fingerprintDataSentWeb","token","notificationURL","prepareFingerPrintData","success","defaultProps","onError"],"mappings":"22BAYA,MAAMA,UAA+BC,EAyCjCC,iBAAAA,GAGI,IAF4BC,EAAcC,KAAKC,MAAMC,iBAE7B,CACpB,MAAMC,EAO0B,SAA3BH,KAAKI,MAAMC,aAA0BL,KAAKI,MAAME,kBAAkBC,KAAKC,SAAS,0BAK/EC,iBAAEA,EAAgBC,6BAAEA,EAA4BC,kBAAEA,EAAiBC,qBAAEA,GAAyBZ,KAAKC,MACpGC,gBAKL,IAH6BW,EAAeJ,EAAkBN,GAoB1D,OAhBAH,KAAKc,kBACD,CAAEC,eAAgB,KAClB,CACIC,UAAWC,EAAeC,2CAC1BC,QAAS,GAAGC,uEAWpBC,QAAQC,MAAM,mEAIlB,MAAMC,EAAmCV,EAAeH,EAA8BP,GAChFqB,EAA4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
|
|
|
1
|
-
{"version":3,"file":"UPIMandate.js","sources":["../../../../../../src/components/UPI/components/UPIMandate/UPIMandate.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useMemo } from 'preact/hooks';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport Alert from '../../../internal/Alert';\nimport type { PaymentAmount } from '../../../../types/global-types';\n\nexport
|
|
1
|
+
{"version":3,"file":"UPIMandate.js","sources":["../../../../../../src/components/UPI/components/UPIMandate/UPIMandate.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useMemo } from 'preact/hooks';\nimport { useCoreContext } from '../../../../core/Context/CoreProvider';\nimport Alert from '../../../internal/Alert';\nimport type { PaymentAmount } from '../../../../types/global-types';\n\nexport interface Mandate {\n /**\n * Mandate amount in the smallest unit of the currency. Maximum amount the shopper authorizes\n * for future recurring charges.\n */\n amount: string;\n /**\n * Charge cadence for the mandate.\n */\n frequency: 'monthly' | 'weekly' | 'adhoc';\n /**\n * - `max`: merchant can charge any amount up to `amount` during future billing cycles.\n * - `exact`: merchant must charge exactly `amount` on each recurring charge.\n */\n amountRule: 'max' | 'exact';\n /**\n * End date of the mandate in `YYYY-MM-DD` format. Required by the Checkout API.\n * Recommended to set between 7 and 10 years in the future.\n */\n endsAt: string;\n /**\n * Start date of the mandate in `YYYY-MM-DD` format. Defaults to the mandate creation date.\n */\n startsAt?: string;\n /**\n * Free-form description of the mandate shown on the shopper's UPI app.\n */\n remarks?: string;\n}\n\nexport interface UPIMandateProps {\n mandate: Mandate;\n amount?: PaymentAmount;\n}\n\nconst UPIMandate = ({ mandate, amount }: Readonly<UPIMandateProps>): h.JSX.Element => {\n const { i18n } = useCoreContext();\n\n const mandateContent = useMemo((): h.JSX.Element => {\n const { amount: mandateAmount, frequency, amountRule } = mandate;\n const { value: paymentAmount, currency } = amount || {};\n\n if (!frequency || !amountRule || !mandateAmount || !currency) {\n console.warn('No mandate information because of missing one of the following: frequency, amountRule, amount or currency');\n return null;\n }\n\n const formattedMandateAmount = i18n.amount(Number(mandateAmount), currency);\n const formattedTransactionAmount = paymentAmount ? i18n.amount(paymentAmount, currency) : null;\n\n const frequencyText = i18n.get(`upi.mandate.frequency.${frequency}`);\n const introText = i18n.get('upi.mandate.intro');\n const recurringAmount = `${formattedMandateAmount}${frequencyText}`;\n\n if (amountRule === 'exact') {\n return (\n <span>\n {introText} (<strong>{recurringAmount}</strong>).\n </span>\n );\n }\n\n // amountRule === 'max'\n const maxAmountText = i18n.get('upi.mandate.upTo', { values: { amount: recurringAmount } });\n\n if (formattedTransactionAmount) {\n const extraText = i18n.get('upi.mandate.max.extraText');\n return (\n <span>\n {introText} (<strong>{formattedTransactionAmount}</strong>). {extraText} (<strong>{maxAmountText}</strong>).\n </span>\n );\n }\n\n return (\n <span>\n {introText} (<strong>{maxAmountText}</strong>).\n </span>\n );\n }, [mandate, amount, i18n]);\n\n if (!mandateContent) return null;\n\n return (\n <Alert icon=\"info_black\" type=\"info\">\n {mandateContent}\n </Alert>\n );\n};\n\nexport default UPIMandate;\n"],"names":["UPIMandate","mandate","amount","i18n","useCoreContext","mandateContent","useMemo","mandateAmount","frequency","amountRule","value","paymentAmount","currency","console","warn","formattedMandateAmount","Number","formattedTransactionAmount","frequencyText","get","introText","recurringAmount","h","span","strong","maxAmountText","values","extraText","Alert","icon","type"],"mappings":"+QAyCA,MAAMA,EAAa,EAAGC,UAASC,aAC3B,MAAMC,KAAEA,GAASC,IAEXC,EAAiBC,EAAQ,KAC3B,MAAQJ,OAAQK,EAAaC,UAAEA,EAASC,WAAEA,GAAeR,GACjDS,MAAOC,EAAaC,SAAEA,GAAaV,GAAU,CAAA,EAErD,KAAKM,GAAcC,GAAeF,GAAkBK,GAEhD,OADAC,QAAQC,KAAK,6GACN,KAGX,MAAMC,EAAyBZ,EAAKD,OAAOc,OAAOT,GAAgBK,GAC5DK,EAA6BN,EAAgBR,EAAKD,OAAOS,EAAeC,GAAY,KAEpFM,EAAgBf,EAAKgB,IAAI,yBAAyBX,KAClDY,EAAYjB,EAAKgB,IAAI,qBACrBE,EAAkB,GAAGN,IAAyBG,IAEpD,GAAmB,UAAfT,EACA,OACIa,EAACC,OAAAA,KACIH,EAAU,KAAEE,EAACE,cAAQH,GAAyB,MAM3D,MAAMI,EAAgBtB,EAAKgB,IAAI,mBAAoB,CAAEO,OAAQ,CAAExB,OAAQmB,KAEvE,GAAIJ,EAA4B,CAC5B,MAAMU,EAAYxB,EAAKgB,IAAI,6BAC3B,OACIG,EAACC,OAAAA,KACIH,EAAU,KAAEE,EAACE,SAAAA,KAAQP,GAAoC,MAAIU,EAAU,KAAEL,EAACE,SAAAA,KAAQC,GAAuB,KAGtH,CAEA,OACIH,EAACC,OAAAA,KACIH,EAAU,KAAEE,EAACE,cAAQC,GAAuB,OAGtD,CAACxB,EAASC,EAAQC,IAErB,OAAKE,EAGDiB,EAACM,EAAAA,CAAMC,KAAK,aAAaC,KAAK,QACzBzB,GAJmB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFormattingRegEx as o,SPECIAL_CHARS as t,trimValWithOneSpace as a}from"../../../utils/validator-utils.js";const e=t=>({formatterFn:a=>a.replace(o("^\\d","g"),"").substring(0,t),format:new Array(t).fill("9").join(""),maxlength:t}),r=o(t),l=o=>a(o).replace(r,""),s={postalCode:{formatterFn:(o,t)=>{const a=t.state.data.country,e=m[a]?.postalCode.formatterFn;return e?e(o):o}},street:{formatterFn:l},houseNumberOrName:{formatterFn:l},city:{formatterFn:l}},m={AT:{postalCode:e(4)},AU:{postalCode:e(4)},BE:{postalCode:e(4)},BG:{postalCode:e(4)},BR:{postalCode:{formatterFn:t=>{const a=t.replace(o("^\\d-","g"),""),e=a.
|
|
1
|
+
import{getFormattingRegEx as o,SPECIAL_CHARS as t,trimValWithOneSpace as a}from"../../../utils/validator-utils.js";const e=t=>({formatterFn:a=>a.replace(o("^\\d","g"),"").substring(0,t),format:new Array(t).fill("9").join(""),maxlength:t}),r=o(t),l=o=>a(o).replace(r,""),s={postalCode:{formatterFn:(o,t)=>{const a=t.state.data.country,e=m[a]?.postalCode.formatterFn;return e?e(o):o}},street:{formatterFn:l},houseNumberOrName:{formatterFn:l},city:{formatterFn:l}},m={AT:{postalCode:e(4)},AU:{postalCode:e(4)},BE:{postalCode:e(4)},BG:{postalCode:e(4)},BR:{postalCode:{formatterFn:t=>{const a=t.replace(o("^\\d-","g"),""),e=a.includes("-")?9:8;return a.substring(0,e)},format:"12345678 or 12345-678",maxlength:9}},CA:{postalCode:{format:"A9A 9A9 or A9A9A9",maxlength:7}},CH:{postalCode:e(4)},CY:{postalCode:e(4)},CZ:{postalCode:{format:"999 99",maxlength:6}},DE:{postalCode:e(5)},DK:{postalCode:{format:"9999",maxlength:7}},EE:{postalCode:e(5)},ES:{postalCode:e(5)},FI:{postalCode:e(5)},FR:{postalCode:e(5)},GB:{postalCode:{formatterFn:a=>a.replace(o(t),"").substring(0,8),format:"AA99 9AA or A99 9AA or A9 9AA",maxlength:8}},GR:{postalCode:{format:"999 99",maxlength:6}},HR:{postalCode:{format:"[1-5]9999",maxlength:5}},HU:{postalCode:e(4)},IE:{postalCode:{format:"A99 A999",maxlength:8}},IS:{postalCode:e(3)},IT:{postalCode:e(5)},LI:{postalCode:e(4)},LT:{postalCode:{format:"9999 or 99999 or LT-99999",maxlength:8}},LU:{postalCode:e(4)},LV:{postalCode:{format:"9999 or LV-9999",maxlength:7}},MC:{postalCode:{format:"980NN",maxlength:5}},MT:{postalCode:{format:"AA99 or AAA99 or AA9999 or AAA9999",maxlength:8}},MY:{postalCode:e(5)},NL:{postalCode:{format:"9999AA",maxlength:7}},NZ:{postalCode:e(4)},NO:{postalCode:e(4)},PL:{postalCode:{formatterFn:t=>{const a=t.replace(o("^\\d-","g"),""),e=a.includes("-")?6:5;return a.substring(0,e)},format:"99999 or 99-999",maxlength:6}},PT:{postalCode:{formatterFn:t=>t.replace(o("^\\d-","g"),"").substring(0,8),format:"9999-999",maxlength:8}},RO:{postalCode:e(6)},SI:{postalCode:{format:"9999 or SI-9999",maxlength:7}},SE:{postalCode:e(5)},SG:{postalCode:e(6)},SK:{postalCode:{format:"99999 or SK-99999",maxlength:8}},JP:{postalCode:{format:"999-9999",maxlength:8}},US:{postalCode:{formatterFn:t=>{const a=t.replace(o("^\\d-","g"),""),e=a.includes("-")?10:5;return a.substring(0,e)},format:"99999 or 99999-9999"}}};export{s as addressFormatters,m as countrySpecificFormatters};
|
|
2
2
|
//# sourceMappingURL=validate.formats.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.formats.js","sources":["../../../../../src/components/internal/Address/validate.formats.ts"],"sourcesContent":["import { CountryFormatRules, FormatRules } from '../../../utils/Validator/types';\nimport { Formatter } from '../../../utils/useForm/types';\nimport { getFormattingRegEx, SPECIAL_CHARS, trimValWithOneSpace } from '../../../utils/validator-utils';\n\nconst createFormatByDigits = (digits: number): Formatter => {\n const format = new Array(digits).fill('9').join('');\n return {\n // Formatter - excludes non digits and limits to maxlength\n formatterFn: val => val.replace(getFormattingRegEx('^\\\\d', 'g'), '').substring(0, digits),\n format,\n maxlength: digits\n };\n};\n\nconst specialCharsRegEx = getFormattingRegEx(SPECIAL_CHARS);\nconst formattingFn = val => trimValWithOneSpace(val).replace(specialCharsRegEx, '');\n\nexport const addressFormatters: FormatRules = {\n postalCode: {\n formatterFn: (val, context) => {\n const country = context.state.data.country;\n\n // Country specific formatting rule\n const specificRule = countrySpecificFormatters[country]?.postalCode.formatterFn;\n if (specificRule) {\n return specificRule(val);\n }\n\n // Default formatting rule: allow anything\n return val;\n }\n },\n street: {\n formatterFn: formattingFn\n },\n houseNumberOrName: {\n formatterFn: formattingFn\n },\n city: {\n formatterFn: formattingFn\n }\n};\n\n// TODO make proper formatter fns for those entries that don't just have a straightforward, x number of digits, no spaces, format\n// check against our internal documentation on address postal code\n// which, for example, says BR isn't just 8 digits (it can be spilt by a hyphen) & CZ can also be 5 digits, no spaces\nexport const countrySpecificFormatters: CountryFormatRules = {\n AT: {\n postalCode: createFormatByDigits(4)\n },\n AU: {\n postalCode: createFormatByDigits(4)\n },\n BE: {\n postalCode: createFormatByDigits(4)\n },\n BG: {\n postalCode: createFormatByDigits(4)\n },\n BR: {\n postalCode: {\n // Formatter - excludes non digits, but allows hyphens, and limits to a maxlength that varies depending on whether a hyphen is present or not\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.indexOf('-') > -1 ? 9 : 8;\n return nuVal.substring(0, maxlength);\n },\n format: '12345678 or 12345-678',\n maxlength: 9\n }\n },\n CA: {\n postalCode: {\n format: 'A9A 9A9 or A9A9A9',\n maxlength: 7\n }\n },\n CH: {\n postalCode: createFormatByDigits(4)\n },\n CY: {\n postalCode: createFormatByDigits(4)\n },\n CZ: {\n postalCode: {\n format: '999 99',\n maxlength: 6\n }\n },\n DE: {\n postalCode: createFormatByDigits(5)\n },\n DK: {\n postalCode: {\n format: '9999',\n maxlength: 7\n }\n },\n EE: {\n postalCode: createFormatByDigits(5)\n },\n ES: {\n postalCode: createFormatByDigits(5)\n },\n FI: {\n postalCode: createFormatByDigits(5)\n },\n FR: {\n postalCode: createFormatByDigits(5)\n },\n GB: {\n postalCode: {\n // Disallow special chars & set to maxlength\n formatterFn: val => val.replace(getFormattingRegEx(SPECIAL_CHARS), '').substring(0, 8),\n format: 'AA99 9AA or A99 9AA or A9 9AA',\n maxlength: 8\n }\n },\n GR: {\n postalCode: {\n format: '999 99',\n maxlength: 6\n }\n },\n HR: {\n postalCode: {\n format: '[1-5]9999',\n maxlength: 5\n }\n },\n HU: {\n postalCode: createFormatByDigits(4)\n },\n IE: {\n postalCode: {\n format: 'A99 A999',\n maxlength: 8\n }\n },\n IS: {\n postalCode: createFormatByDigits(3)\n },\n IT: {\n postalCode: createFormatByDigits(5)\n },\n LI: {\n postalCode: createFormatByDigits(4)\n },\n LT: {\n postalCode: {\n format: '9999 or 99999 or LT-99999',\n maxlength: 8\n }\n },\n LU: {\n postalCode: createFormatByDigits(4)\n },\n LV: {\n postalCode: {\n format: '9999 or LV-9999',\n maxlength: 7\n }\n },\n MC: {\n postalCode: {\n format: '980NN',\n maxlength: 5\n }\n },\n MT: {\n postalCode: {\n format: 'AA99 or AAA99 or AA9999 or AAA9999',\n maxlength: 8\n }\n },\n MY: {\n postalCode: createFormatByDigits(5)\n },\n NL: {\n postalCode: {\n format: '9999AA',\n maxlength: 7\n }\n },\n NZ: {\n postalCode: createFormatByDigits(4)\n },\n NO: {\n postalCode: createFormatByDigits(4)\n },\n PL: {\n postalCode: {\n // Formatter - excludes non digits, but allows hyphens, and limits to a maxlength that varies depending on whether a hyphen is present or not\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.indexOf('-') > -1 ? 6 : 5;\n return nuVal.substring(0, maxlength);\n },\n format: '99999 or 99-999',\n maxlength: 6\n }\n },\n PT: {\n postalCode: {\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n return nuVal.substring(0, 8);\n },\n format: '9999-999',\n maxlength: 8\n }\n },\n RO: {\n postalCode: createFormatByDigits(6)\n },\n SI: {\n postalCode: {\n format: '9999 or SI-9999',\n maxlength: 7\n }\n },\n SE: {\n postalCode: createFormatByDigits(5)\n },\n SG: {\n postalCode: createFormatByDigits(6)\n },\n SK: {\n postalCode: {\n format: '99999 or SK-99999',\n maxlength: 8\n }\n },\n JP: {\n postalCode: {\n format: '999-9999',\n maxlength: 8\n }\n },\n US: {\n postalCode: {\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.indexOf('-') > -1 ? 10 : 5;\n return nuVal.substring(0, maxlength);\n },\n format: '99999 or 99999-9999'\n }\n }\n};\n"],"names":["createFormatByDigits","digits","formatterFn","val","replace","getFormattingRegEx","substring","format","Array","fill","join","maxlength","specialCharsRegEx","SPECIAL_CHARS","formattingFn","trimValWithOneSpace","addressFormatters","postalCode","context","country","state","data","specificRule","countrySpecificFormatters","street","houseNumberOrName","city","AT","AU","BE","BG","BR","nuVal","indexOf","CA","CH","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HR","HU","IE","IS","IT","LI","LT","LU","LV","MC","MT","MY","NL","NZ","NO","PL","PT","RO","SI","SE","SG","SK","JP","US"],"mappings":"mHAIA,MAAMA,EAAwBC,IAEnB,CAEHC,YAAaC,GAAOA,EAAIC,QAAQC,EAAmB,OAAQ,KAAM,IAAIC,UAAU,EAAGL,GAClFM,OAJW,IAAIC,MAAMP,GAAQQ,KAAK,KAAKC,KAAK,IAK5CC,UAAWV,IAIbW,EAAoBP,EAAmBQ,GACvCC,EAAeX,GAAOY,EAAoBZ,GAAKC,QAAQQ,EAAmB,IAEnEI,EAAiC,CAC1CC,WAAY,CACRf,YAAa,CAACC,EAAKe,KACf,MAAMC,EAAUD,EAAQE,MAAMC,KAAKF,QAG7BG,EAAeC,EAA0BJ,IAAUF,WAAWf,YACpE,OAAIoB,EACOA,EAAanB,GAIjBA,IAGfqB,OAAQ,CACJtB,YAAaY,GAEjBW,kBAAmB,CACfvB,YAAaY,GAEjBY,KAAM,CACFxB,YAAaY,IAORS,EAAgD,CACzDI,GAAI,CACAV,WAAYjB,EAAqB,IAErC4B,GAAI,CACAX,WAAYjB,EAAqB,IAErC6B,GAAI,CACAZ,WAAYjB,EAAqB,IAErC8B,GAAI,CACAb,WAAYjB,EAAqB,IAErC+B,GAAI,CACAd,WAAY,CAERf,YAAaC,IACT,MAAM6B,EAAQ7B,EAAIC,QAAQC,EAAmB,QAAS,KAAM,IACtDM,EAAYqB,EAAMC,QAAQ,MAAO,EAAK,EAAI,EAChD,OAAOD,EAAM1B,UAAU,EAAGK,IAE9BJ,OAAQ,wBACRI,UAAW,IAGnBuB,GAAI,CACAjB,WAAY,CACRV,OAAQ,oBACRI,UAAW,IAGnBwB,GAAI,CACAlB,WAAYjB,EAAqB,IAErCoC,GAAI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AAQ7B,EAAIC,QAAQC,EAAmB,QAAS,KAAM,IACtDM,EAAYqB,EAAMC,QAAQ,MAAO,EAAK,EAAI,EAChD,OAAOD,EAAM1B,UAAU,EAAGK,IAE9BJ,OAAQ,kBACRI,UAAW,IAGnBmD,GAAI,CACA7C,WAAY,CACRf,YAAaC,GACKA,EAAIC,QAAQC,EAAmB,QAAS,KAAM,IAC/CC,UAAU,EAAG,GAE9BC,OAAQ,WACRI,UAAW,IAGnBoD,GAAI,CACA9C,WAAYjB,EAAqB,IAErCgE,GAAI,CACA/C,WAAY,CACRV,OAAQ,kBACRI,UAAW,IAGnBsD,GAAI,CACAhD,WAAYjB,EAAqB,IAErCkE,GAAI,CACAjD,WAAYjB,EAAqB,IAErCmE,GAAI,CACAlD,WAAY,CACRV,OAAQ,oBACRI,UAAW,IAGnByD,GAAI,CACAnD,WAAY,CACRV,OAAQ,WACRI,UAAW,IAGnB0D,GAAI,CACApD,WAAY,CACRf,YAAaC,IACT,MAAM6B,EAAQ7B,EAAIC,QAAQC,EAAmB,QAAS,KAAM,IACtDM,EAAYqB,EAAMC,QAAQ,MAAO,EAAK,GAAK,EACjD,OAAOD,EAAM1B,UAAU,EAAGK,IAE9BJ,OAAQ"}
|
|
1
|
+
{"version":3,"file":"validate.formats.js","sources":["../../../../../src/components/internal/Address/validate.formats.ts"],"sourcesContent":["import { CountryFormatRules, FormatRules } from '../../../utils/Validator/types';\nimport { Formatter } from '../../../utils/useForm/types';\nimport { getFormattingRegEx, SPECIAL_CHARS, trimValWithOneSpace } from '../../../utils/validator-utils';\n\nconst asCountryFormatRules = <T extends CountryFormatRules>(rules: T): T & CountryFormatRules => rules;\n\nconst createFormatByDigits = (digits: number): Formatter => {\n const format = new Array(digits).fill('9').join('');\n return {\n // Formatter - excludes non digits and limits to maxlength\n formatterFn: val => val.replace(getFormattingRegEx('^\\\\d', 'g'), '').substring(0, digits),\n format,\n maxlength: digits\n };\n};\n\nconst specialCharsRegEx = getFormattingRegEx(SPECIAL_CHARS);\nconst formattingFn = val => trimValWithOneSpace(val).replace(specialCharsRegEx, '');\n\nexport const addressFormatters: FormatRules = {\n postalCode: {\n formatterFn: (val, context) => {\n const country = context.state.data.country;\n\n // Country specific formatting rule\n const specificRule = countrySpecificFormatters[country]?.postalCode.formatterFn;\n if (specificRule) {\n return specificRule(val);\n }\n\n // Default formatting rule: allow anything\n return val;\n }\n },\n street: {\n formatterFn: formattingFn\n },\n houseNumberOrName: {\n formatterFn: formattingFn\n },\n city: {\n formatterFn: formattingFn\n }\n};\n\n// TODO make proper formatter fns for those entries that don't just have a straightforward, x number of digits, no spaces, format\n// check against our internal documentation on address postal code\n// which, for example, says BR isn't just 8 digits (it can be spilt by a hyphen) & CZ can also be 5 digits, no spaces\nexport const countrySpecificFormatters = asCountryFormatRules({\n AT: {\n postalCode: createFormatByDigits(4)\n },\n AU: {\n postalCode: createFormatByDigits(4)\n },\n BE: {\n postalCode: createFormatByDigits(4)\n },\n BG: {\n postalCode: createFormatByDigits(4)\n },\n BR: {\n postalCode: {\n // Formatter - excludes non digits, but allows hyphens, and limits to a maxlength that varies depending on whether a hyphen is present or not\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.includes('-') ? 9 : 8;\n return nuVal.substring(0, maxlength);\n },\n format: '12345678 or 12345-678',\n maxlength: 9\n }\n },\n CA: {\n postalCode: {\n format: 'A9A 9A9 or A9A9A9',\n maxlength: 7\n }\n },\n CH: {\n postalCode: createFormatByDigits(4)\n },\n CY: {\n postalCode: createFormatByDigits(4)\n },\n CZ: {\n postalCode: {\n format: '999 99',\n maxlength: 6\n }\n },\n DE: {\n postalCode: createFormatByDigits(5)\n },\n DK: {\n postalCode: {\n format: '9999',\n maxlength: 7\n }\n },\n EE: {\n postalCode: createFormatByDigits(5)\n },\n ES: {\n postalCode: createFormatByDigits(5)\n },\n FI: {\n postalCode: createFormatByDigits(5)\n },\n FR: {\n postalCode: createFormatByDigits(5)\n },\n GB: {\n postalCode: {\n // Disallow special chars & set to maxlength\n formatterFn: val => val.replace(getFormattingRegEx(SPECIAL_CHARS), '').substring(0, 8),\n format: 'AA99 9AA or A99 9AA or A9 9AA',\n maxlength: 8\n }\n },\n GR: {\n postalCode: {\n format: '999 99',\n maxlength: 6\n }\n },\n HR: {\n postalCode: {\n format: '[1-5]9999',\n maxlength: 5\n }\n },\n HU: {\n postalCode: createFormatByDigits(4)\n },\n IE: {\n postalCode: {\n format: 'A99 A999',\n maxlength: 8\n }\n },\n IS: {\n postalCode: createFormatByDigits(3)\n },\n IT: {\n postalCode: createFormatByDigits(5)\n },\n LI: {\n postalCode: createFormatByDigits(4)\n },\n LT: {\n postalCode: {\n format: '9999 or 99999 or LT-99999',\n maxlength: 8\n }\n },\n LU: {\n postalCode: createFormatByDigits(4)\n },\n LV: {\n postalCode: {\n format: '9999 or LV-9999',\n maxlength: 7\n }\n },\n MC: {\n postalCode: {\n format: '980NN',\n maxlength: 5\n }\n },\n MT: {\n postalCode: {\n format: 'AA99 or AAA99 or AA9999 or AAA9999',\n maxlength: 8\n }\n },\n MY: {\n postalCode: createFormatByDigits(5)\n },\n NL: {\n postalCode: {\n format: '9999AA',\n maxlength: 7\n }\n },\n NZ: {\n postalCode: createFormatByDigits(4)\n },\n NO: {\n postalCode: createFormatByDigits(4)\n },\n PL: {\n postalCode: {\n // Formatter - excludes non digits, but allows hyphens, and limits to a maxlength that varies depending on whether a hyphen is present or not\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.includes('-') ? 6 : 5;\n return nuVal.substring(0, maxlength);\n },\n format: '99999 or 99-999',\n maxlength: 6\n }\n },\n PT: {\n postalCode: {\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n return nuVal.substring(0, 8);\n },\n format: '9999-999',\n maxlength: 8\n }\n },\n RO: {\n postalCode: createFormatByDigits(6)\n },\n SI: {\n postalCode: {\n format: '9999 or SI-9999',\n maxlength: 7\n }\n },\n SE: {\n postalCode: createFormatByDigits(5)\n },\n SG: {\n postalCode: createFormatByDigits(6)\n },\n SK: {\n postalCode: {\n format: '99999 or SK-99999',\n maxlength: 8\n }\n },\n JP: {\n postalCode: {\n format: '999-9999',\n maxlength: 8\n }\n },\n US: {\n postalCode: {\n formatterFn: val => {\n const nuVal = val.replace(getFormattingRegEx('^\\\\d-', 'g'), '');\n const maxlength = nuVal.includes('-') ? 10 : 5;\n return nuVal.substring(0, maxlength);\n },\n format: '99999 or 99999-9999'\n }\n }\n});\n"],"names":["createFormatByDigits","digits","formatterFn","val","replace","getFormattingRegEx","substring","format","Array","fill","join","maxlength","specialCharsRegEx","SPECIAL_CHARS","formattingFn","trimValWithOneSpace","addressFormatters","postalCode","context","country","state","data","specificRule","countrySpecificFormatters","street","houseNumberOrName","city","AT","AU","BE","BG","BR","nuVal","includes","CA","CH","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HR","HU","IE","IS","IT","LI","LT","LU","LV","MC","MT","MY","NL","NZ","NO","PL","PT","RO","SI","SE","SG","SK","JP","US"],"mappings":"mHAIA,MAEMA,EAAwBC,IAEnB,CAEHC,YAAaC,GAAOA,EAAIC,QAAQC,EAAmB,OAAQ,KAAM,IAAIC,UAAU,EAAGL,GAClFM,OAJW,IAAIC,MAAMP,GAAQQ,KAAK,KAAKC,KAAK,IAK5CC,UAAWV,IAIbW,EAAoBP,EAAmBQ,GACvCC,EAAeX,GAAOY,EAAoBZ,GAAKC,QAAQQ,EAAmB,IAEnEI,EAAiC,CAC1CC,WAAY,CACRf,YAAa,CAACC,EAAKe,KACf,MAAMC,EAAUD,EAAQE,MAAMC,KAAKF,QAG7BG,EAAeC,EAA0BJ,IAAUF,WAAWf,YACpE,OAAIoB,EACOA,EAAanB,GAIjBA,IAGfqB,OAAQ,CACJtB,YAAaY,GAEjBW,kBAAmB,CACfvB,YAAaY,GAEjBY,KAAM,CACFxB,YAAaY,I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1,2 @@
|
|
|
1
|
-
import{render as t}from"../../../external/preact/dist/preact.js";import e from"../../../utils/uuid.js";import
|
|
1
|
+
import{render as t}from"../../../external/preact/dist/preact.js";import e from"../../../utils/uuid.js";import o from"../../../core/Errors/AdyenCheckoutError.js";import{NO_CHECKOUT_ATTEMPT_ID as r}from"../../../core/Analytics/constants.js";import{on as s,off as n}from"../../../utils/listenerUtils.js";import{createSdkData as i}from"../../../utils/createSdkData.js";import a from"../../components-name-map.js";import{PAYMENT_METHOD_BEHAVIOR as h}from"../../../core/config.js";function c(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class u{buildElementProps(t){this.props=this.formatProps({...this.constructor.defaultProps,...t})}formatProps(t){return t}formatData(){return{}}submitAnalytics(t){return null}handleKeyPress(t){return null}setState(t){this.state={...this.state,...t}}get data(){const t=this.state.order||this.props.order,e=this.formatData(),o=Boolean(a(e.paymentMethod?.type)),s=this.core.modules.risk.data,n=this.core.modules.analytics.checkoutAttemptId??r,c=o?h.NATIVE:h.GENERIC,u=i(n,s,c);return e.paymentMethod&&n&&(e.paymentMethod.checkoutAttemptId=n),e.paymentMethod&&u&&(e.paymentMethod.sdkData=u),{...s&&{riskData:{clientData:s}},...t&&{order:{orderData:t.orderData,pspReference:t.pspReference}},...e,clientStateDataIndicator:!0}}activate(){}render(){throw new Error("Payment method cannot be rendered.")}mount(e){const o="string"==typeof e?document.querySelector(e):e;if(!o)throw new Error("Component could not mount. Root node was not found.");return this._node&&this.unmount(),this._node=o,s(this._node,"keypress",this.handleKeyPress,!1),this._component=this.render(),t(this._component,o),this}update(t){return this.props=this.formatProps({...this.props,...t}),this.state={},this.unmount().mount(this._node)}unmount(){return n(this._node,"keypress",this.handleKeyPress),this._node&&t(null,this._node),this}remove(){this.unmount(),this.core&&this.core.remove(this)}constructor(t,r){c(this,"_id",`${this.constructor.type}-${e()}`),c(this,"core",void 0),c(this,"props",void 0),c(this,"state",{}),c(this,"_component",void 0),c(this,"_node",null);const s=function(t){return!!t&&("function"==typeof t.initialize&&"function"==typeof t.createFromAction)}(t);if(!s)throw new o("IMPLEMENTATION_ERROR",`Trying to initialise the component '${this.constructor.type}' without a reference to an instance of AdyenCheckout`);this.core=t,this.buildElementProps(r),this.handleKeyPress=this.handleKeyPress.bind(this)}}c(u,"defaultProps",{});export{u as default};
|
|
2
2
|
//# sourceMappingURL=BaseElement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, h, render } from 'preact';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { NO_CHECKOUT_ATTEMPT_ID } from '../../../core/Analytics/constants';\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport { off, on } from '../../../utils/listenerUtils';\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { createSdkData } from '../../../utils/createSdkData';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nabstract class BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n public readonly core: ICore;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n\n protected static readonly defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n\n this.handleKeyPress = this.handleKeyPress.bind(this);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: AbstractAnalyticsEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const order = this.state.order || this.props.order;\n const componentData = this.formatData();\n
|
|
1
|
+
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, h, render } from 'preact';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { NO_CHECKOUT_ATTEMPT_ID } from '../../../core/Analytics/constants';\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport { off, on } from '../../../utils/listenerUtils';\nimport { AbstractAnalyticsEvent } from '../../../core/Analytics/events/AbstractAnalyticsEvent';\nimport { createSdkData } from '../../../utils/createSdkData';\nimport getComponentNameOfPaymentType from '../../components-name-map';\nimport { PAYMENT_METHOD_BEHAVIOR } from '../../../core/config';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nabstract class BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n public readonly core: ICore;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n\n protected static readonly defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n\n this.handleKeyPress = this.handleKeyPress.bind(this);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: AbstractAnalyticsEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const order = this.state.order || this.props.order;\n const componentData = this.formatData();\n const doesPaymentMethodHaveNativeComponent = Boolean(getComponentNameOfPaymentType(componentData.paymentMethod?.type));\n const clientData = this.core.modules.risk.data;\n const checkoutAttemptId = this.core.modules.analytics.checkoutAttemptId ?? NO_CHECKOUT_ATTEMPT_ID;\n const paymentMethodBehavior = doesPaymentMethodHaveNativeComponent ? PAYMENT_METHOD_BEHAVIOR.NATIVE : PAYMENT_METHOD_BEHAVIOR.GENERIC;\n\n const sdkData = createSdkData(checkoutAttemptId, clientData, paymentMethodBehavior);\n if (componentData.paymentMethod && checkoutAttemptId) {\n componentData.paymentMethod.checkoutAttemptId = checkoutAttemptId;\n }\n\n if (componentData.paymentMethod && sdkData) {\n componentData.paymentMethod.sdkData = sdkData;\n }\n\n return {\n ...(clientData && { riskData: { clientData } }),\n ...(order && { order: { orderData: order.orderData, pspReference: order.pspReference } }),\n ...componentData,\n clientStateDataIndicator: true\n };\n }\n\n /**\n * Method used to make the payment method active\n * (Useful when there are different payment methods available and activating one PM must trigger a specific task)\n */\n public activate(): void {\n return;\n }\n\n public render(): ComponentChild | Error {\n // render() not implemented in the element\n throw new Error('Payment method cannot be rendered.');\n }\n\n /**\n * Mounts an element into the dom\n * @param domNode - Node (or selector) where we will mount the payment element\n * @returns this - the payment element instance we mounted\n */\n public mount(domNode: HTMLElement | string): this {\n const node = typeof domNode === 'string' ? document.querySelector<HTMLElement>(domNode) : domNode;\n\n if (!node) {\n throw new Error('Component could not mount. Root node was not found.');\n }\n\n if (this._node) {\n this.unmount(); // new, if this._node exists then we are \"remounting\" so we first need to unmount if it's not already been done\n }\n\n this._node = node;\n\n // Add listener for key press events, notably 'Enter' key presses\n on(this._node, 'keypress', this.handleKeyPress, false);\n\n this._component = this.render();\n\n render(this._component, node);\n\n return this;\n }\n\n /**\n * Updates props, resets the internal state and remounts the element.\n *\n * @param props - props to update\n * @returns this - the element instance\n */\n public update(props: Partial<P>): this {\n this.props = this.formatProps({ ...this.props, ...props });\n this.state = {};\n\n return this.unmount().mount(this._node); // for new mount fny\n }\n\n /**\n * Unmounts a payment element from the DOM\n */\n public unmount(): this {\n // Remove listener\n off(this._node, 'keypress', this.handleKeyPress);\n\n if (this._node) {\n render(null, this._node);\n }\n\n return this;\n }\n\n /**\n * Unmounts an element and removes it from the parent instance\n * For \"destroy\" type cleanup - when you don't intend to use the component again\n */\n public remove() {\n this.unmount();\n\n if (this.core) {\n this.core.remove(this);\n }\n }\n}\n\nexport default BaseElement;\n"],"names":["BaseElement","buildElementProps","componentProps","this","props","formatProps","constructor","formatData","submitAnalytics","analyticsObj","handleKeyPress","e","setState","newState","state","data","order","componentData","doesPaymentMethodHaveNativeComponent","Boolean","getComponentNameOfPaymentType","paymentMethod","type","clientData","core","modules","risk","checkoutAttemptId","analytics","NO_CHECKOUT_ATTEMPT_ID","paymentMethodBehavior","PAYMENT_METHOD_BEHAVIOR","NATIVE","GENERIC","sdkData","createSdkData","riskData","orderData","pspReference","clientStateDataIndicator","activate","render","Error","mount","domNode","node","document","querySelector","_node","unmount","on","_component","update","off","remove","checkout","_define_property","_id","uuid","isCoreInstance","initialize","createFromAction","assertIsCoreInstance","AdyenCheckoutError","bind","defaultProps"],"mappings":"mlBAwBA,MAAeA,EA4BDC,iBAAAA,CAAkBC,GACxBC,KAAKC,MAAQD,KAAKE,YAAY,IAAKF,KAAKG,YAAY,gBAAoBJ,GAC5E,CAMUG,WAAAA,CAAYD,GAClB,OAAOA,CACX,CAMA,UAAAG,GACI,MAAO,CAAA,CACX,CAGUC,eAAAA,CAAgBC,GACtB,OAAO,IACX,CAGUC,cAAAA,CAAeC,GACrB,OAAO,IACX,CAEUC,QAAAA,CAASC,GACfV,KAAKW,MAAQ,IAAKX,KAAKW,SAAUD,EACrC,CAMA,QAAWE,GACP,MAAMC,EAAQb,KAAKW,MAAME,OAASb,KAAKC,MAAMY,MACvCC,EAAgBd,KAAKI,aACrBW,EAAuCC,QAAQC,EAA8BH,EAAcI,eAAeC,OAC1GC,EAAapB,KAAKqB,KAAKC,QAAQC,KAAKX,KACpCY,EAAoBxB,KAAKqB,KAAKC,QAAQG,UAAUD,mBAAqBE,EACrEC,EAAwBZ,EAAuCa,EAAwBC,OAASD,EAAwBE,QAExHC,EAAUC,EAAcR,EAAmBJ,EAAYO,GAS7D,OARIb,EAAcI,eAAi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Bd,SAA8BJ,GAC1B,QAAKA,IAC+C,mBAAxBA,EAASK,YAAkE,mBAA9BL,EAASM,iBAEtF,CAe+BC,CAAqBP,GAE5C,IAAKI,EACD,MAAM,IAAII,EACN,uBACA,uCAAuC5D,KAAKG,YAAY,6DAIhEH,KAAKqB,KAAO+B,EACZpD,KAAKF,kBAAkBG,GAEvBD,KAAKO,eAAiBP,KAAKO,eAAesD,KAAK7D,KACnD,EAhBAqD,EAVWxD,EAUeiE,eAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../../../../_virtual/index.js";import{createElement as a,Fragment as n,toChildArray as t,cloneElement as l}from"../../../../external/preact/dist/preact.js";import i from"../../Spinner/Spinner.js";import o from"../../Icon/Icon.js";import{ARIA_ERROR_SUFFIX as r,ARIA_CONTEXT_SUFFIX as
|
|
1
|
+
import e from"../../../../_virtual/index.js";import{createElement as a,Fragment as n,toChildArray as t,cloneElement as l}from"../../../../external/preact/dist/preact.js";import i from"../../Spinner/Spinner.js";import o from"../../Icon/Icon.js";import{ARIA_ERROR_SUFFIX as r,ARIA_CONTEXT_SUFFIX as d}from"../../../../core/Errors/constants.js";import{useRef as s,useMemo as c,useState as u,useCallback as m}from"../../../../external/preact/hooks/dist/hooks.js";import{getUniqueId as p}from"../../../../utils/idGenerator.js";import{PREFIX as _}from"../../Icon/constants.js";import h from"../../../../utils/uuid.js";const f=f=>{const{children:k,className:y,classNameModifiers:b,dir:v,disabled:x,readOnly:E,errorMessage:N,helper:F,inputWrapperModifiers:g,isLoading:$,isValid:j,label:w,labelEndAdornment:I,name:L,onBlur:C,onFieldBlur:A,onFocus:M,onFocusField:S,showValidIcon:T,useLabelElement:V,showErrorElement:q,showContextualElement:B,staticValue:H,contextualText:R,filled:W,focused:z,i18n:G,contextVisibleToScreenReader:O,renderAlternativeToLabel:P,onInputContainerClick:D}=f,J=O??!0,K=q&&"string"==typeof N&&N.length>0,Q=B&&!K&&R&&R.length>0,U=s(p(`adyen-checkout-${L}`)),X=c(()=>H?`input-static-value-${h()}`:null,[H]),[Y,Z]=u(!1),[ee,ae]=u(!1);null!=z&&Z(!!z),null!=W&&ae(!!W);const ne=m(e=>{Z(!0),M?.(e)},[M]),te=m(e=>{Z(!1),C?.(e),A?.(e)},[C,A]),le=m(()=>a(n,null,"string"==typeof w&&a("span",{className:e({"adyen-checkout__label__text":!0,"adyen-checkout__label__text--error":N}),"data-id":L,"data-testid":L},w),"function"==typeof w&&w(),I&&a("span",{className:"adyen-checkout__label-adornment--end"},I),F&&a("span",{className:"adyen-checkout__helper-text"},F)),[w,N,I,F]),ie=m(()=>{const s=a("span",{className:e({"adyen-checkout-contextual-text--error":!0,"adyen-checkout-contextual-text--hidden":!K}),...J&&{id:`${U.current}${r}`},"aria-hidden":J?void 0:"true"},N),c=a("span",{className:e({"adyen-checkout-contextual-text":!0,"adyen-checkout-contextual-text--hidden":!Q}),...J&&{id:`${U.current}${d}`},"aria-hidden":J?void 0:"true"},R);return a(n,null,a("div",{className:e(["adyen-checkout__input-wrapper",...g.map(e=>`adyen-checkout__input-wrapper--${e}`)]),dir:v,onClick:D},H&&a("span",{id:X,className:"adyen-checkout__field-static-value"},H),t(k).map(e=>{const a={isValid:j,onFocusHandler:ne,onBlurHandler:te,isInvalid:!!N,"aria-owns":X,...L&&{uniqueId:U.current},showErrorElement:q};return l(e,a)}),$&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading"},a(i,{size:"small"})),j&&!1!==T&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid"},a(o,{type:`${_}checkmark_black`,alt:G?.get("field.valid")})),N&&a("span",{className:"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid"},a(o,{type:`${_}field_error`,alt:G?.get("error.title")}))),s,c)},[k,N,R,$,j,ne,te]),oe=m(({onFocusField:n,focused:t,filled:l,disabled:i,name:o,uniqueId:r,useLabelElement:d,isSecuredField:s,children:c,renderAlternativeToLabel:u})=>{const m={onClick:n,className:e({"adyen-checkout__label":!0,"adyen-checkout__label--focused":t,"adyen-checkout__label--filled":l,"adyen-checkout__label--disabled":i})};return d?a("label",{...m,...!s&&o&&{htmlFor:r}},c):u(m,c,r)},[]);return a("div",{"data-testid":"form-field",className:e("adyen-checkout__field",y,b?.map(e=>`adyen-checkout__field--${e}`),{"adyen-checkout__field--error":N,"adyen-checkout__field--valid":j,"adyen-checkout__field--inactive":E||x})},a(oe,{onFocusField:S,name:L,disabled:x,filled:ee,focused:Y,useLabelElement:V,uniqueId:U.current,isSecuredField:!J,renderAlternativeToLabel:P},le()),ie())};f.defaultProps={className:"",classNameModifiers:[],inputWrapperModifiers:[],useLabelElement:!0,showErrorElement:!0,showContextualElement:!0,renderAlternativeToLabel:()=>null};export{f as default};
|
|
2
2
|
//# sourceMappingURL=Field.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Field.js","sources":["../../../../../../src/components/internal/FormFields/Field/Field.tsx"],"sourcesContent":["import classNames from 'classnames';\nimport { cloneElement, ComponentChild, Fragment, FunctionalComponent, h, toChildArray, VNode } from 'preact';\nimport Spinner from '../../Spinner';\nimport Icon from '../../Icon';\nimport { ARIA_CONTEXT_SUFFIX, ARIA_ERROR_SUFFIX } from '../../../../core/Errors/constants';\nimport { useCallback, useMemo, useRef, useState } from 'preact/hooks';\nimport { getUniqueId } from '../../../../utils/idGenerator';\nimport { FieldProps } from './types';\nimport './Field.scss';\nimport { PREFIX } from '../../Icon/constants';\nimport uuid from '../../../../utils/uuid';\n\nconst Field: FunctionalComponent<Readonly<FieldProps>> = props => {\n const {\n children,\n className,\n classNameModifiers,\n dir,\n disabled,\n readOnly,\n errorMessage,\n helper,\n inputWrapperModifiers,\n isLoading,\n isValid,\n label,\n labelEndAdornment,\n name,\n onBlur,\n onFieldBlur,\n onFocus,\n // onFocusField is a securedField related function that allows a label click to set focus on a securedField (equates to CardInput setFocusOn)\n // TODO should rename it to make its purpose clear => setFocusOnSecuredField\n onFocusField,\n showValidIcon,\n useLabelElement,\n showErrorElement,\n showContextualElement,\n staticValue,\n contextualText,\n // Redeclare prop names to avoid internal clashes\n filled: propsFilled,\n focused: propsFocused,\n i18n,\n contextVisibleToScreenReader,\n renderAlternativeToLabel,\n onInputContainerClick\n } = props;\n\n // Controls whether any error element has an aria-hidden=\"true\" attr (which means it is the error for a securedField)\n // or whether it has an id attr that can be pointed to by an aria-describedby attr on an input element\n const contextVisibleToSR = contextVisibleToScreenReader ?? true;\n const showError = showErrorElement && typeof errorMessage === 'string' && errorMessage.length > 0;\n const showContext = showContextualElement && !showError && contextualText?.length > 0;\n\n const uniqueId = useRef(getUniqueId(`adyen-checkout-${name}`));\n const staticValueId = useMemo(() => (staticValue ? `input-static-value-${uuid()}` : null), [staticValue]);\n\n const [focused, setFocused] = useState(false);\n const [filled, setFilled] = useState(false);\n\n // The means by which focussed/filled is set for securedFields\n if (propsFocused != null) setFocused(!!propsFocused);\n if (propsFilled != null) setFilled(!!propsFilled);\n\n // The means by which focussed/filled is set for other fields - this function is passed down to them and triggered\n const onFocusHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(true);\n onFocus?.(event);\n },\n [onFocus]\n );\n\n const onBlurHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(false);\n onBlur?.(event);\n // When we also need to fire a specific function when a field blurs // TODO - what is the use case?\n onFieldBlur?.(event);\n },\n [onBlur, onFieldBlur]\n );\n\n const renderLabelOrAlternativeContents = useCallback(() => {\n return (\n <Fragment>\n {typeof label === 'string' && (\n <span\n className={classNames({\n 'adyen-checkout__label__text': true,\n 'adyen-checkout__label__text--error': errorMessage\n })}\n data-id={name}\n data-testid={name}\n >\n {label}\n </span>\n )}\n\n {/*TODO - in what scenario is label a function? */}\n {/*@ts-ignore - function is callable*/}\n {typeof label === 'function' && label()}\n\n {labelEndAdornment && <span className=\"adyen-checkout__label-adornment--end\">{labelEndAdornment}</span>}\n\n {helper && <span className={'adyen-checkout__helper-text'}>{helper}</span>}\n </Fragment>\n );\n }, [label, errorMessage, labelEndAdornment, helper]);\n\n const renderInputRelatedElements = useCallback(() => {\n const errorElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text--error': true, 'adyen-checkout-contextual-text--hidden': !showError })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_ERROR_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? null : 'true'}\n >\n {errorMessage}\n </span>\n );\n const contextualElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text': true, 'adyen-checkout-contextual-text--hidden': !showContext })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_CONTEXT_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? null : 'true'}\n >\n {contextualText}\n </span>\n );\n\n return (\n <Fragment>\n {/* The <div> element has a child <input> element that allows keyboard interaction */}\n {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}\n <div\n className={classNames([\n 'adyen-checkout__input-wrapper',\n ...inputWrapperModifiers.map(m => `adyen-checkout__input-wrapper--${m}`)\n ])}\n dir={dir}\n onClick={onInputContainerClick}\n >\n {staticValue && (\n <span id={staticValueId} className=\"adyen-checkout__field-static-value\">\n {staticValue}\n </span>\n )}\n\n {toChildArray(children).map((child: ComponentChild): ComponentChild => {\n const propsFromFieldComponent = {\n isValid,\n onFocusHandler,\n onBlurHandler,\n isInvalid: !!errorMessage,\n 'aria-owns': staticValueId,\n ...(name && { uniqueId: uniqueId.current }),\n showErrorElement: showErrorElement\n };\n\n return cloneElement(child as VNode, propsFromFieldComponent);\n })}\n\n {isLoading && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading\">\n <Spinner size=\"small\" />\n </span>\n )}\n\n {isValid && showValidIcon !== false && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid\">\n <Icon type={`${PREFIX}checkmark_black`} alt={i18n?.get('field.valid')} />\n </span>\n )}\n\n {errorMessage && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid\">\n <Icon type={`${PREFIX}field_error`} alt={i18n?.get('error.title')} />\n </span>\n )}\n </div>\n {errorElem}\n {contextualElem}\n </Fragment>\n );\n }, [children, errorMessage, contextualText, isLoading, isValid, onFocusHandler, onBlurHandler]);\n\n /**\n * Use cases:\n * - Not all form controls want/need a label e.g. many checkboxes describe what they are in their own markup and don't need the wrapping Field to also generate a labelling element\n * - securedFields *can't* have a label (screen-reader's can make the association, over different browser contexts, between the label and the input)\n */\n const LabelOrAlternative = useCallback(\n ({ onFocusField, focused, filled, disabled, name, uniqueId, useLabelElement, isSecuredField, children, renderAlternativeToLabel }) => {\n const defaultWrapperProps = {\n onClick: onFocusField,\n className: classNames({\n 'adyen-checkout__label': true,\n 'adyen-checkout__label--focused': focused,\n 'adyen-checkout__label--filled': filled,\n 'adyen-checkout__label--disabled': disabled\n })\n };\n\n return useLabelElement ? (\n // if we are NOT dealing with the label for a securedField... we can give it a `for` attribute\n <label {...defaultWrapperProps} {...(!isSecuredField && name && { htmlFor: uniqueId })}>\n {children}\n </label>\n ) : (\n renderAlternativeToLabel(defaultWrapperProps, children, uniqueId) // defaults to null\n\n // Example usage:\n // const alternativeLabelContent = (defaultWrapperProps, children, uniqueId) => {\n // return (\n // <div {...defaultWrapperProps} role={'label'} htmlFor={uniqueId}>\n // {children}\n // </div>\n // );\n // };\n // <Field name={'myField'} useLabelElement={false} renderAlternativeToLabel={alternativeLabelContent}>\n );\n },\n []\n );\n\n /**\n * RENDER\n */\n return (\n <div\n data-testid=\"form-field\"\n className={classNames(\n 'adyen-checkout__field',\n className,\n classNameModifiers.map(m => `adyen-checkout__field--${m}`),\n {\n 'adyen-checkout__field--error': errorMessage,\n 'adyen-checkout__field--valid': isValid,\n 'adyen-checkout__field--inactive': readOnly || disabled\n }\n )}\n >\n <LabelOrAlternative\n onFocusField={onFocusField}\n name={name}\n disabled={disabled}\n filled={filled}\n focused={focused}\n useLabelElement={useLabelElement}\n uniqueId={uniqueId.current}\n isSecuredField={!contextVisibleToSR}\n renderAlternativeToLabel={renderAlternativeToLabel}\n >\n {renderLabelOrAlternativeContents()}\n </LabelOrAlternative>\n {renderInputRelatedElements()}\n </div>\n );\n};\n\nField.defaultProps = {\n className: '',\n classNameModifiers: [],\n inputWrapperModifiers: [],\n useLabelElement: true,\n showErrorElement: true,\n showContextualElement: true,\n renderAlternativeToLabel: () => null\n};\n\nexport default Field;\n"],"names":["Field","props","children","className","classNameModifiers","dir","disabled","readOnly","errorMessage","helper","inputWrapperModifiers","isLoading","isValid","label","labelEndAdornment","name","onBlur","onFieldBlur","onFocus","onFocusField","showValidIcon","useLabelElement","showErrorElement","showContextualElement","staticValue","contextualText","filled","propsFilled","focused","propsFocused","i18n","contextVisibleToScreenReader","renderAlternativeToLabel","onInputContainerClick","contextVisibleToSR","showError","length","showContext","uniqueId","useRef","getUniqueId","staticValueId","useMemo","uuid","setFocused","useState","setFilled","onFocusHandler","useCallback","event","onBlurHandler","renderLabelOrAlternativeContents","h","Fragment","span","classNames","data-id","data-testid","renderInputRelatedElements","errorElem","id","current","ARIA_ERROR_SUFFIX","aria-hidden","contextualElem","ARIA_CONTEXT_SUFFIX","div","map","m","onClick","toChildArray","child","propsFromFieldComponent","isInvalid","cloneElement","Spinner","size","Icon","type","PREFIX","alt","get","LabelOrAlternative","isSecuredField","defaultWrapperProps","htmlFor","defaultProps"],"mappings":"omBAYA,MAAMA,EAAmDC,IACrD,MAAMC,SACFA,EAAQC,UACRA,EAASC,mBACTA,EAAkBC,IAClBA,EAAGC,SACHA,EAAQC,SACRA,EAAQC,aACRA,EAAYC,OACZA,EAAMC,sBACNA,EAAqBC,UACrBA,EAASC,QACTA,EAAOC,MACPA,EAAKC,kBACLA,EAAiBC,KACjBA,EAAIC,OACJA,EAAMC,YACNA,EAAWC,QACXA,EAAOC,aAGPA,EAAYC,cACZA,EAAaC,gB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A,IAAUuE,MAA2BD,GAAkBpE,GAAQ,CAAEsE,QAAS/C,IACtEpC,GAGL8B,EAAyBoD,EAAqBlF,EAAUoC,IAahE,IAMJ,OACIc,EAACc,MAAAA,CACGT,cAAY,aACZtD,UAAWoD,EACP,wBACApD,EACAC,EAAmB+D,IAAIC,GAAK,0BAA0BA,KACtD,CACI,+BAAgC5D,EAChC,+BAAgCI,EAChC,kCAAmCL,GAAYD,KAIvD8C,EAAC8B,GAAAA,CACG/D,aAAcA,EACdJ,KAAMA,EACNT,SAAUA,EACVoB,OAAQA,GACRE,QAASA,EACTP,gBAAiBA,EACjBiB,SAAUA,EAASuB,QACnBsB,gBAAiBjD,EACjBF,yBAA0BA,GAEzBmB,MAEJO,OAKb1D,EAAMsF,aAAe,CACjBnF,UAAW,GACXC,mBAAoB,GACpBM,sBAAuB,GACvBW,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBS,yBAA0B,IAAM"}
|
|
1
|
+
{"version":3,"file":"Field.js","sources":["../../../../../../src/components/internal/FormFields/Field/Field.tsx"],"sourcesContent":["import classNames from 'classnames';\nimport { cloneElement, ComponentChild, Fragment, FunctionalComponent, h, toChildArray, VNode } from 'preact';\nimport Spinner from '../../Spinner';\nimport Icon from '../../Icon';\nimport { ARIA_CONTEXT_SUFFIX, ARIA_ERROR_SUFFIX } from '../../../../core/Errors/constants';\nimport { useCallback, useMemo, useRef, useState } from 'preact/hooks';\nimport { getUniqueId } from '../../../../utils/idGenerator';\nimport { FieldProps } from './types';\nimport './Field.scss';\nimport { PREFIX } from '../../Icon/constants';\nimport uuid from '../../../../utils/uuid';\n\nconst Field: FunctionalComponent<Readonly<FieldProps>> = props => {\n const {\n children,\n className,\n classNameModifiers,\n dir,\n disabled,\n readOnly,\n errorMessage,\n helper,\n inputWrapperModifiers,\n isLoading,\n isValid,\n label,\n labelEndAdornment,\n name,\n onBlur,\n onFieldBlur,\n onFocus,\n // onFocusField is a securedField related function that allows a label click to set focus on a securedField (equates to CardInput setFocusOn)\n // TODO should rename it to make its purpose clear => setFocusOnSecuredField\n onFocusField,\n showValidIcon,\n useLabelElement,\n showErrorElement,\n showContextualElement,\n staticValue,\n contextualText,\n // Redeclare prop names to avoid internal clashes\n filled: propsFilled,\n focused: propsFocused,\n i18n,\n contextVisibleToScreenReader,\n renderAlternativeToLabel,\n onInputContainerClick\n } = props;\n\n // Controls whether any error element has an aria-hidden=\"true\" attr (which means it is the error for a securedField)\n // or whether it has an id attr that can be pointed to by an aria-describedby attr on an input element\n const contextVisibleToSR = contextVisibleToScreenReader ?? true;\n const showError = showErrorElement && typeof errorMessage === 'string' && errorMessage.length > 0;\n const showContext = showContextualElement && !showError && contextualText && contextualText.length > 0;\n\n const uniqueId = useRef(getUniqueId(`adyen-checkout-${name}`));\n const staticValueId = useMemo(() => (staticValue ? `input-static-value-${uuid()}` : null), [staticValue]);\n\n const [focused, setFocused] = useState(false);\n const [filled, setFilled] = useState(false);\n\n // The means by which focussed/filled is set for securedFields\n if (propsFocused != null) setFocused(!!propsFocused);\n if (propsFilled != null) setFilled(!!propsFilled);\n\n // The means by which focussed/filled is set for other fields - this function is passed down to them and triggered\n const onFocusHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(true);\n onFocus?.(event);\n },\n [onFocus]\n );\n\n const onBlurHandler = useCallback(\n (event: h.JSX.TargetedEvent<HTMLInputElement>) => {\n setFocused(false);\n onBlur?.(event);\n // When we also need to fire a specific function when a field blurs // TODO - what is the use case?\n onFieldBlur?.(event);\n },\n [onBlur, onFieldBlur]\n );\n\n const renderLabelOrAlternativeContents = useCallback(() => {\n return (\n <Fragment>\n {typeof label === 'string' && (\n <span\n className={classNames({\n 'adyen-checkout__label__text': true,\n 'adyen-checkout__label__text--error': errorMessage\n })}\n data-id={name}\n data-testid={name}\n >\n {label}\n </span>\n )}\n\n {/*TODO - in what scenario is label a function? */}\n {/*@ts-ignore - function is callable*/}\n {typeof label === 'function' && label()}\n\n {labelEndAdornment && <span className=\"adyen-checkout__label-adornment--end\">{labelEndAdornment}</span>}\n\n {helper && <span className={'adyen-checkout__helper-text'}>{helper}</span>}\n </Fragment>\n );\n }, [label, errorMessage, labelEndAdornment, helper]);\n\n const renderInputRelatedElements = useCallback(() => {\n const errorElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text--error': true, 'adyen-checkout-contextual-text--hidden': !showError })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_ERROR_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? undefined : 'true'}\n >\n {errorMessage}\n </span>\n );\n const contextualElem = (\n <span\n className={classNames({ 'adyen-checkout-contextual-text': true, 'adyen-checkout-contextual-text--hidden': !showContext })}\n {...(contextVisibleToSR && { id: `${uniqueId.current}${ARIA_CONTEXT_SUFFIX}` })}\n aria-hidden={contextVisibleToSR ? undefined : 'true'}\n >\n {contextualText}\n </span>\n );\n\n return (\n <Fragment>\n {/* The <div> element has a child <input> element that allows keyboard interaction */}\n {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}\n <div\n className={classNames([\n 'adyen-checkout__input-wrapper',\n ...inputWrapperModifiers.map(m => `adyen-checkout__input-wrapper--${m}`)\n ])}\n dir={dir}\n onClick={onInputContainerClick}\n >\n {staticValue && (\n <span id={staticValueId} className=\"adyen-checkout__field-static-value\">\n {staticValue}\n </span>\n )}\n\n {toChildArray(children).map((child: ComponentChild): ComponentChild => {\n const propsFromFieldComponent = {\n isValid,\n onFocusHandler,\n onBlurHandler,\n isInvalid: !!errorMessage,\n 'aria-owns': staticValueId,\n ...(name && { uniqueId: uniqueId.current }),\n showErrorElement: showErrorElement\n };\n\n return cloneElement(child as VNode, propsFromFieldComponent);\n })}\n\n {isLoading && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--loading\">\n <Spinner size=\"small\" />\n </span>\n )}\n\n {isValid && showValidIcon !== false && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--valid\">\n <Icon type={`${PREFIX}checkmark_black`} alt={i18n?.get('field.valid')} />\n </span>\n )}\n\n {errorMessage && (\n <span className=\"adyen-checkout-input__inline-validation adyen-checkout-input__inline-validation--invalid\">\n <Icon type={`${PREFIX}field_error`} alt={i18n?.get('error.title')} />\n </span>\n )}\n </div>\n {errorElem}\n {contextualElem}\n </Fragment>\n );\n }, [children, errorMessage, contextualText, isLoading, isValid, onFocusHandler, onBlurHandler]);\n\n /**\n * Use cases:\n * - Not all form controls want/need a label e.g. many checkboxes describe what they are in their own markup and don't need the wrapping Field to also generate a labelling element\n * - securedFields *can't* have a label (screen-reader's can make the association, over different browser contexts, between the label and the input)\n */\n const LabelOrAlternative = useCallback(\n ({ onFocusField, focused, filled, disabled, name, uniqueId, useLabelElement, isSecuredField, children, renderAlternativeToLabel }) => {\n const defaultWrapperProps = {\n onClick: onFocusField,\n className: classNames({\n 'adyen-checkout__label': true,\n 'adyen-checkout__label--focused': focused,\n 'adyen-checkout__label--filled': filled,\n 'adyen-checkout__label--disabled': disabled\n })\n };\n\n return useLabelElement ? (\n // if we are NOT dealing with the label for a securedField... we can give it a `for` attribute\n <label {...defaultWrapperProps} {...(!isSecuredField && name && { htmlFor: uniqueId })}>\n {children}\n </label>\n ) : (\n renderAlternativeToLabel(defaultWrapperProps, children, uniqueId) // defaults to null\n\n // Example usage:\n // const alternativeLabelContent = (defaultWrapperProps, children, uniqueId) => {\n // return (\n // <div {...defaultWrapperProps} role={'label'} htmlFor={uniqueId}>\n // {children}\n // </div>\n // );\n // };\n // <Field name={'myField'} useLabelElement={false} renderAlternativeToLabel={alternativeLabelContent}>\n );\n },\n []\n );\n\n /**\n * RENDER\n */\n return (\n <div\n data-testid=\"form-field\"\n className={classNames(\n 'adyen-checkout__field',\n className,\n classNameModifiers?.map(m => `adyen-checkout__field--${m}`),\n {\n 'adyen-checkout__field--error': errorMessage,\n 'adyen-checkout__field--valid': isValid,\n 'adyen-checkout__field--inactive': readOnly || disabled\n }\n )}\n >\n <LabelOrAlternative\n onFocusField={onFocusField}\n name={name}\n disabled={disabled}\n filled={filled}\n focused={focused}\n useLabelElement={useLabelElement}\n uniqueId={uniqueId.current}\n isSecuredField={!contextVisibleToSR}\n renderAlternativeToLabel={renderAlternativeToLabel}\n >\n {renderLabelOrAlternativeContents()}\n </LabelOrAlternative>\n {renderInputRelatedElements()}\n </div>\n );\n};\n\nField.defaultProps = {\n className: '',\n classNameModifiers: [],\n inputWrapperModifiers: [],\n useLabelElement: true,\n showErrorElement: true,\n showContextualElement: true,\n renderAlternativeToLabel: () => null\n};\n\nexport default Field;\n"],"names":["Field","props","children","className","classNameModifiers","dir","disabled","readOnly","errorMessage","helper","inputWrapperModifiers","isLoading","isValid","label","labelEndAdornment","name","onBlur","onFieldBlur","onFocus","onFocusField","showValidIcon","useLabelElement","showErrorElement","showContextualElement","staticValue","contextualText","filled","propsFilled","focused","propsFocused","i18n","contextVisibleToScreenReader","renderAlternativeToLabel","onInputContainerClick","contextVisibleToSR","showError","length","showContext","uniqueId","useRef","getUniqueId","staticValueId","useMemo","uuid","setFocused","useState","setFilled","onFocusHandler","useCallback","event","onBlurHandler","renderLabelOrAlternativeContents","h","Fragment","span","classNames","data-id","data-testid","renderInputRelatedElements","errorElem","id","current","ARIA_ERROR_SUFFIX","aria-hidden","undefined","contextualElem","ARIA_CONTEXT_SUFFIX","div","map","m","onClick","toChildArray","child","propsFromFieldComponent","isInvalid","cloneElement","Spinner","size","Icon","type","PREFIX","alt","get","LabelOrAlternative","isSecuredField","defaultWrapperProps","htmlFor","defaultProps"],"mappings":"omBAYA,MAAMA,EAAmDC,IACrD,MAAMC,SACFA,EAAQC,UACRA,EAASC,mBACTA,EAAkBC,IAClBA,EAAGC,SACHA,EAAQC,SACRA,EAAQC,aACRA,EAAYC,OACZA,EAAMC,sBACNA,EAAqBC,UACrBA,EAASC,QACTA,EAAOC,MACPA,EAAKC,kBACLA,EAAiBC,KACjBA,EAAIC,OACJ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EACzB,iCAAkC3B,EAClC,gCAAiCF,EACjC,kCAAmCpB,KAI3C,OAAOe,EAEH+B,EAACvC,QAAAA,IAAUwE,MAA2BD,GAAkBrE,GAAQ,CAAEuE,QAAShD,IACtEpC,GAGL8B,EAAyBqD,EAAqBnF,EAAUoC,IAahE,IAMJ,OACIc,EAACe,MAAAA,CACGV,cAAY,aACZtD,UAAWoD,EACP,wBACApD,EACAC,GAAoBgE,IAAIC,GAAK,0BAA0BA,KACvD,CACI,+BAAgC7D,EAChC,+BAAgCI,EAChC,kCAAmCL,GAAYD,KAIvD8C,EAAC+B,GAAAA,CACGhE,aAAcA,EACdJ,KAAMA,EACNT,SAAUA,EACVoB,OAAQA,GACRE,QAASA,EACTP,gBAAiBA,EACjBiB,SAAUA,EAASuB,QACnBuB,gBAAiBlD,EACjBF,yBAA0BA,GAEzBmB,MAEJO,OAKb1D,EAAMuF,aAAe,CACjBpF,UAAW,GACXC,mBAAoB,GACpBM,sBAAuB,GACvBW,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBS,yBAA0B,IAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=()=>{const e=document.createElement("input");return e.setAttribute("type","date"),"date"===e.type},t=e=>{const t=e.replace(/\D|\s/g,"").replace(/^(00)(.*)?/,"01$2").replace(/^(3[2-9])(.*)?/,"0$1$2").replace(/^([4-9])(.*)?/,"0$1").replace(/^([0-9]{2})(00)(.*)?/,"$101").replace(/^(3[01])(02)(.*)?/,"29$2").replace(/^([0-9]{2})([2-9]|1[3-9])(.*)?/,"$10$2").replace(/^([0-9]{2})([0-9]{2})([0-9])/,"$1/$2/$3").replace(/^([0-9]{2})([0-9])/,"$1/$2"),[r="",c="",l=""]=t.split("/");return 4===l.length&&"29"===r&&"02"===c&&(Number(l)%4!=0||"00"===l.substr(2,2)&&Number(l)%400!=0)?t.replace(/^29/,"28"):t},r=(e="")=>{if(
|
|
1
|
+
const e=()=>{const e=document.createElement("input");return e.setAttribute("type","date"),"date"===e.type},t=e=>{const t=e.replace(/\D|\s/g,"").replace(/^(00)(.*)?/,"01$2").replace(/^(3[2-9])(.*)?/,"0$1$2").replace(/^([4-9])(.*)?/,"0$1").replace(/^([0-9]{2})(00)(.*)?/,"$101").replace(/^(3[01])(02)(.*)?/,"29$2").replace(/^([0-9]{2})([2-9]|1[3-9])(.*)?/,"$10$2").replace(/^([0-9]{2})([0-9]{2})([0-9])/,"$1/$2/$3").replace(/^([0-9]{2})([0-9])/,"$1/$2"),[r="",c="",l=""]=t.split("/");return 4===l.length&&"29"===r&&"02"===c&&(Number(l)%4!=0||"00"===l.substr(2,2)&&Number(l)%400!=0)?t.replace(/^29/,"28"):t},r=(e="")=>{if(!e.includes("/"))return e;const[t="",r="",c=""]=e.split("/");return t&&r&&c?`${c}-${r}-${t}`:null};export{e as checkDateInputSupport,t as formatDate,r as unformatDate};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../../src/components/internal/FormFields/InputDate/utils.ts"],"sourcesContent":["/**\n * Returns either the date input is supported or not in the current browser\n */\nconst checkDateInputSupport = (): boolean => {\n const input = document.createElement('input');\n input.setAttribute('type', 'date');\n return input.type === 'date';\n};\n\n/**\n * Returns a formatted date\n * @param value -\n * @example\n * formatDate('22111990');\n * // '22/11/1990'\n */\nconst formatDate = (value: string): string => {\n const date = value\n .replace(/\\D|\\s/g, '') // Digits only\n .replace(/^(00)(.*)?/, '01$2') // 00 -> 01\n .replace(/^(3[2-9])(.*)?/, '0$1$2') // 34 -> 03/04\n .replace(/^([4-9])(.*)?/, '0$1') // 4 -> 04\n .replace(/^([0-9]{2})(00)(.*)?/, '$101') // 01/00 -> 01/01\n .replace(/^(3[01])(02)(.*)?/, '29$2') // Force up to day 29 for Feb\n .replace(/^([0-9]{2})([2-9]|1[3-9])(.*)?/, '$10$2') // 01/4 -> 01/04\n .replace(/^([0-9]{2})([0-9]{2})([0-9])/, '$1/$2/$3') // 22111990 -> 22/11/1990\n .replace(/^([0-9]{2})([0-9])/, '$1/$2'); // 2211 -> 22/11\n\n const [day = '', month = '', year = ''] = date.split('/');\n\n // Check leap year\n if (year.length === 4 && day === '29' && month === '02' && (Number(year) % 4 !== 0 || (year.substr(2, 2) === '00' && Number(year) % 400 !== 0))) {\n return date.replace(/^29/, '28');\n }\n\n return date;\n};\n\n/**\n * Receives a formatted date and returns it as the API expects it\n * @param value -\n * @example\n * unformatDate('22/11/1990');\n * // '1990-11-22'\n */\nconst unformatDate = (value = ''): string => {\n if (value.
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../../src/components/internal/FormFields/InputDate/utils.ts"],"sourcesContent":["/**\n * Returns either the date input is supported or not in the current browser\n */\nconst checkDateInputSupport = (): boolean => {\n const input = document.createElement('input');\n input.setAttribute('type', 'date');\n return input.type === 'date';\n};\n\n/**\n * Returns a formatted date\n * @param value -\n * @example\n * formatDate('22111990');\n * // '22/11/1990'\n */\nconst formatDate = (value: string): string => {\n const date = value\n .replace(/\\D|\\s/g, '') // Digits only\n .replace(/^(00)(.*)?/, '01$2') // 00 -> 01\n .replace(/^(3[2-9])(.*)?/, '0$1$2') // 34 -> 03/04\n .replace(/^([4-9])(.*)?/, '0$1') // 4 -> 04\n .replace(/^([0-9]{2})(00)(.*)?/, '$101') // 01/00 -> 01/01\n .replace(/^(3[01])(02)(.*)?/, '29$2') // Force up to day 29 for Feb\n .replace(/^([0-9]{2})([2-9]|1[3-9])(.*)?/, '$10$2') // 01/4 -> 01/04\n .replace(/^([0-9]{2})([0-9]{2})([0-9])/, '$1/$2/$3') // 22111990 -> 22/11/1990\n .replace(/^([0-9]{2})([0-9])/, '$1/$2'); // 2211 -> 22/11\n\n const [day = '', month = '', year = ''] = date.split('/');\n\n // Check leap year\n if (year.length === 4 && day === '29' && month === '02' && (Number(year) % 4 !== 0 || (year.substr(2, 2) === '00' && Number(year) % 400 !== 0))) {\n return date.replace(/^29/, '28');\n }\n\n return date;\n};\n\n/**\n * Receives a formatted date and returns it as the API expects it\n * @param value -\n * @example\n * unformatDate('22/11/1990');\n * // '1990-11-22'\n */\nconst unformatDate = (value = ''): string => {\n if (!value.includes('/')) return value;\n const [day = '', month = '', year = ''] = value.split('/');\n if (!day || !month || !year) return null;\n return `${year}-${month}-${day}`;\n};\n\nexport { checkDateInputSupport, formatDate, unformatDate };\n"],"names":["checkDateInputSupport","input","document","createElement","setAttribute","type","formatDate","value","date","replace","day","month","year","split","length","Number","substr","unformatDate","includes"],"mappings":"MAGMA,EAAwB,KAC1B,MAAMC,EAAQC,SAASC,cAAc,SAErC,OADAF,EAAMG,aAAa,OAAQ,QACL,SAAfH,EAAMI,MAUXC,EAAcC,IAChB,MAAMC,EAAOD,EACRE,QAAQ,SAAU,IAClBA,QAAQ,aAAc,QACtBA,QAAQ,iBAAkB,SAC1BA,QAAQ,gBAAiB,OACzBA,QAAQ,uBAAwB,QAChCA,QAAQ,oBAAqB,QAC7BA,QAAQ,iCAAkC,SAC1CA,QAAQ,+BAAgC,YACxCA,QAAQ,qBAAsB,UAE5BC,EAAM,GAAIC,EAAQ,GAAIC,EAAO,IAAMJ,EAAKK,MAAM,KAGrD,OAAoB,IAAhBD,EAAKE,QAAwB,OAARJ,GAA0B,OAAVC,IAAmBI,OAAOH,GAAQ,GAAM,GAA4B,OAAtBA,EAAKI,OAAO,EAAG,IAAeD,OAAOH,GAAQ,KAAQ,GACjIJ,EAAKC,QAAQ,MAAO,MAGxBD,GAULS,EAAe,CAACV,EAAQ,MAC1B,IAAKA,EAAMW,SAAS,KAAM,OAAOX,EACjC,MAAOG,EAAM,GAAIC,EAAQ,GAAIC,EAAO,IAAML,EAAMM,MAAM,KACtD,OAAKH,GAAQC,GAAUC,EAChB,GAAGA,KAAQD,KAASD,IADS"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ENCRYPTED_EXPIRY_DATE as e,ENCRYPTED_EXPIRY_MONTH as r,ENCRYPTED_EXPIRY_YEAR as l,ENCRYPTED_SECURITY_CODE as i,CVC_POLICY_OPTIONAL as t,DATE_POLICY_OPTIONAL as c,CVC_POLICY_HIDDEN as o,DATE_POLICY_HIDDEN as s}from"../lib/constants.js";import{EMPTY_FIELD_ERROR_MESSAGES as d}from"../../../../core/Errors/constants.js";const a=e=>e?Array.prototype.slice.call(e.querySelectorAll('[data-cse*="encrypted"]')).map(e=>e.getAttribute("data-cse")):[],p=(i,t)=>(t===e?(i[r]=!1,i[l]=!1):i[t]=!1,i),y=(d,a)=>(p,y)=>{let n=!0!==a.valid[y]?((i,t)=>1!==t||i!==r&&i!==l?i:e)(y,d):null;return n=((e,r,l)=>{const{isFieldOfType:d,fieldIsValid:a}=l.reduce((l,i)=>(l.isFieldOfType||(l.isFieldOfType=e===i,l.fieldIsValid=!r.errors[i]),l),{isFieldOfType:!1,fieldIsValid:!1}),p=e===i?"cvcPolicy":"expiryDatePolicy",y="cvcPolicy"===p?t:c,n="cvcPolicy"===p?o:s;return(r[p]===y||r[p]===n)&&a&&d?null:e})(n,a,[i,e,r,l]),n&&!p.includes(n)&&p.push(n),p},n=(e,r,l)=>({rootNode:r,fieldType:e,error:l.errors?.[e]||d[e],type:"card"});export{n as getErrorObject,y as getErrorReducer,a as getFields,p as validFieldsReducer};
|
|
1
|
+
import{ENCRYPTED_EXPIRY_DATE as e,ENCRYPTED_EXPIRY_MONTH as r,ENCRYPTED_EXPIRY_YEAR as l,ENCRYPTED_SECURITY_CODE as i,CVC_POLICY_OPTIONAL as t,DATE_POLICY_OPTIONAL as c,CVC_POLICY_HIDDEN as o,DATE_POLICY_HIDDEN as s}from"../lib/constants.js";import{EMPTY_FIELD_ERROR_MESSAGES as d}from"../../../../core/Errors/constants.js";const a=e=>e?Array.prototype.slice.call(e.querySelectorAll('[data-cse*="encrypted"]')).map(e=>e.getAttribute("data-cse")):[],p=(i,t)=>(t===e?(i[r]=!1,i[l]=!1):i[t]=!1,i),y=(d,a)=>(p,y)=>{let n=!0!==a.valid[y]?((i,t)=>1!==t||i!==r&&i!==l?i:e)(y,d):null;return n=((e,r,l)=>{const{isFieldOfType:d,fieldIsValid:a}=l.reduce((l,i)=>(l.isFieldOfType||(l.isFieldOfType=e===i,l.fieldIsValid=!r.errors?.[i]),l),{isFieldOfType:!1,fieldIsValid:!1}),p=e===i?"cvcPolicy":"expiryDatePolicy",y="cvcPolicy"===p?t:c,n="cvcPolicy"===p?o:s;return(r[p]===y||r[p]===n)&&a&&d?null:e})(n,a,[i,e,r,l]),n&&!p.includes(n)&&p.push(n),p},n=(e,r,l)=>({rootNode:r,fieldType:e,error:l.errors?.[e]||d[e],type:"card"});export{n as getErrorObject,y as getErrorReducer,a as getFields,p as validFieldsReducer};
|
|
2
2
|
//# sourceMappingURL=SFPUtils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SFPUtils.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SFPUtils.ts"],"sourcesContent":["// ROUTINES USED IN SecuredFieldsProvider.componentDidMount TO DETECT & MAP FIELD NAMES ///////////\nimport {\n CVC_POLICY_HIDDEN,\n CVC_POLICY_OPTIONAL,\n DATE_POLICY_HIDDEN,\n DATE_POLICY_OPTIONAL,\n ENCRYPTED_EXPIRY_DATE,\n ENCRYPTED_EXPIRY_MONTH,\n ENCRYPTED_EXPIRY_YEAR,\n ENCRYPTED_SECURITY_CODE\n} from '../lib/constants';\nimport { EMPTY_FIELD_ERROR_MESSAGES } from '../../../../core/Errors/constants';\nimport type { SFPState } from './types';\n\n/**\n * Make an array of encrypted field names based on the value of the 'data-cse' attribute of elements in the rootNode\n */\nexport const getFields = rootNode => {\n if (rootNode) {\n return Array.prototype.slice.call(rootNode.querySelectorAll('[data-cse*=\"encrypted\"]')).map(f => f.getAttribute('data-cse'));\n }\n return [];\n};\n\n/**\n * If, visually, we're dealing with a single date field (expiryDate) we still need separate entries\n * for expiryMonth & expiryYear - since that is how the values will be delivered from securedFields\n */\nexport const validFieldsReducer = (acc, cur) => {\n if (cur === ENCRYPTED_EXPIRY_DATE) {\n acc[ENCRYPTED_EXPIRY_MONTH] = false;\n acc[ENCRYPTED_EXPIRY_YEAR] = false;\n } else {\n acc[cur] = false;\n }\n\n return acc;\n};\n// -- end ROUTINES USED IN SecuredFieldsProvider.componentDidMount --------------------------------\n\n// ROUTINES USED IN SecuredFieldsProvider.showValidation TO GENERATE ERRORS ///////////\n/**\n * If, visually, we're dealing with a single date field (expiryDate) remap the separate entries we have\n * for the valid states of expiryMonth & expiryYear back to the single key we use to an store an error\n * i.e `\"encryptedExpiryMonth\" & \"encryptedExpiryYear\" => \"encryptedExpiryDate\"`\n */\nconst mapDateFields = (field, numDateFields) => {\n const isDateField = field === ENCRYPTED_EXPIRY_MONTH || field === ENCRYPTED_EXPIRY_YEAR;\n return numDateFields === 1 && isDateField ? ENCRYPTED_EXPIRY_DATE : field;\n};\n\n/**\n * Skip generating an error for an optional field, unless it is already in error\n */\nconst skipOptionalFields = (field, state, fieldNames) => {\n
|
|
1
|
+
{"version":3,"file":"SFPUtils.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SFPUtils.ts"],"sourcesContent":["// ROUTINES USED IN SecuredFieldsProvider.componentDidMount TO DETECT & MAP FIELD NAMES ///////////\nimport {\n CVC_POLICY_HIDDEN,\n CVC_POLICY_OPTIONAL,\n DATE_POLICY_HIDDEN,\n DATE_POLICY_OPTIONAL,\n ENCRYPTED_EXPIRY_DATE,\n ENCRYPTED_EXPIRY_MONTH,\n ENCRYPTED_EXPIRY_YEAR,\n ENCRYPTED_SECURITY_CODE\n} from '../lib/constants';\nimport { EMPTY_FIELD_ERROR_MESSAGES } from '../../../../core/Errors/constants';\nimport type { SFPState, SFPErrorMap, SFPValid } from './types';\n\n/**\n * Make an array of encrypted field names based on the value of the 'data-cse' attribute of elements in the rootNode\n */\nexport const getFields = (rootNode: HTMLElement) => {\n if (rootNode) {\n return Array.prototype.slice.call(rootNode.querySelectorAll('[data-cse*=\"encrypted\"]')).map((f: HTMLElement) => f.getAttribute('data-cse'));\n }\n return [];\n};\n\n/**\n * If, visually, we're dealing with a single date field (expiryDate) we still need separate entries\n * for expiryMonth & expiryYear - since that is how the values will be delivered from securedFields\n */\nexport const validFieldsReducer = (acc: Record<string, boolean>, cur: string): Record<string, boolean> => {\n if (cur === ENCRYPTED_EXPIRY_DATE) {\n acc[ENCRYPTED_EXPIRY_MONTH] = false;\n acc[ENCRYPTED_EXPIRY_YEAR] = false;\n } else {\n acc[cur] = false;\n }\n\n return acc;\n};\n// -- end ROUTINES USED IN SecuredFieldsProvider.componentDidMount --------------------------------\n\n// ROUTINES USED IN SecuredFieldsProvider.showValidation TO GENERATE ERRORS ///////////\n/**\n * If, visually, we're dealing with a single date field (expiryDate) remap the separate entries we have\n * for the valid states of expiryMonth & expiryYear back to the single key we use to an store an error\n * i.e `\"encryptedExpiryMonth\" & \"encryptedExpiryYear\" => \"encryptedExpiryDate\"`\n */\nconst mapDateFields = (field: string, numDateFields: number) => {\n const isDateField = field === ENCRYPTED_EXPIRY_MONTH || field === ENCRYPTED_EXPIRY_YEAR;\n return numDateFields === 1 && isDateField ? ENCRYPTED_EXPIRY_DATE : field;\n};\n\n/**\n * Skip generating an error for an optional field, unless it is already in error\n */\nconst skipOptionalFields = (field: string, state: SFPState, fieldNames: string[]) => {\n const { isFieldOfType, fieldIsValid } = fieldNames.reduce(\n (acc: { isFieldOfType: boolean; fieldIsValid: boolean }, fieldName: string) => {\n if (!acc.isFieldOfType) {\n // console.log('### utils:: fieldName:: ', fieldName, 'match=', field === fieldName);\n acc.isFieldOfType = field === fieldName;\n acc.fieldIsValid = !state.errors?.[fieldName as keyof SFPErrorMap];\n }\n return acc;\n },\n { isFieldOfType: false, fieldIsValid: false }\n );\n\n const policyType = field === ENCRYPTED_SECURITY_CODE ? 'cvcPolicy' : 'expiryDatePolicy';\n\n const policyOptional = policyType === 'cvcPolicy' ? CVC_POLICY_OPTIONAL : DATE_POLICY_OPTIONAL;\n const policyHidden = policyType === 'cvcPolicy' ? CVC_POLICY_HIDDEN : DATE_POLICY_HIDDEN;\n\n // if policy != required\n return (state[policyType] === policyOptional || state[policyType] === policyHidden) && fieldIsValid && isFieldOfType ? null : field;\n};\n\nexport const getErrorReducer = (numDateFields: number, state: SFPState) => (acc: string[], field: string) => {\n // We're only interested in the non-valid fields from the state.valid object...\n let val: string | null =\n state.valid[field as keyof SFPValid] !== true\n ? mapDateFields(field, numDateFields) // Map the keys we use for the valid state to the key(s) we use for the error state\n : null;\n\n // Skip error generation for optional/hidden CVC & Date unless the fields are already in error\n val = skipOptionalFields(val, state, [ENCRYPTED_SECURITY_CODE, ENCRYPTED_EXPIRY_DATE, ENCRYPTED_EXPIRY_MONTH, ENCRYPTED_EXPIRY_YEAR]);\n\n // console.log('### utils:::: ############# val=', val);\n\n if (val && !acc.includes(val)) acc.push(val);\n\n return acc;\n};\n\n/**\n * Create an object suitable for sending to our handleOnError function\n */\nexport const getErrorObject = (fieldType: string, rootNode: HTMLElement, state: SFPState) => {\n // Get existing error OR field is empty in which case get field specific msg OR use default\n const error: string | undefined =\n state.errors?.[fieldType as keyof SFPErrorMap] || EMPTY_FIELD_ERROR_MESSAGES[fieldType as keyof typeof EMPTY_FIELD_ERROR_MESSAGES];\n\n return {\n rootNode,\n fieldType,\n error,\n type: 'card'\n };\n};\n// -- end ROUTINES USED IN SecuredFieldsProvider.showValidation -----------------------\n"],"names":["getFields","rootNode","Array","prototype","slice","call","querySelectorAll","map","f","getAttribute","validFieldsReducer","acc","cur","ENCRYPTED_EXPIRY_DATE","ENCRYPTED_EXPIRY_MONTH","ENCRYPTED_EXPIRY_YEAR","getErrorReducer","numDateFields","state","field","val","valid","mapDateFields","fieldNames","isFieldOfType","fieldIsValid","reduce","fieldName","errors","policyType","ENCRYPTED_SECURITY_CODE","policyOptional","CVC_POLICY_OPTIONAL","DATE_POLICY_OPTIONAL","policyHidden","CVC_POLICY_HIDDEN","DATE_POLICY_HIDDEN","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