@adyen/adyen-web 6.23.0 → 6.24.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/README.md +1 -1
- package/dist/cjs/adyen.css +3 -1
- package/dist/cjs/adyen.css.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +24 -5
- package/dist/es/adyen.css +3 -1
- package/dist/es/adyen.css.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/ExpirationDate.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/ExpirationDate.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/StoredCardFields.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/StoredCardFields.js.map +1 -1
- package/dist/es/components/Dropin/Dropin.js +1 -1
- package/dist/es/components/Dropin/Dropin.js.map +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/InstantPaymentMethods.js +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/InstantPaymentMethods.js.map +1 -1
- package/dist/es/components/PayPal/components/PaypalButtons.js +1 -1
- package/dist/es/components/PayPal/components/PaypalButtons.js.map +1 -1
- package/dist/es/components/PayPal/defaultProps.js +1 -1
- package/dist/es/components/PayPal/defaultProps.js.map +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2Challenge.js +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2Challenge.js.map +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2DeviceFingerprint.js +1 -1
- package/dist/es/components/ThreeDS2/ThreeDS2DeviceFingerprint.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/utils.js +1 -1
- package/dist/es/components/ThreeDS2/components/utils.js.map +1 -1
- package/dist/es/components/helpers/QRLoaderContainer/QRLoaderContainer.js +1 -1
- package/dist/es/components/helpers/QRLoaderContainer/QRLoaderContainer.js.map +1 -1
- package/dist/es/components/internal/Address/Address.js +1 -1
- package/dist/es/components/internal/Address/Address.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/Fieldset/Fieldset.js +1 -1
- package/dist/es/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es/core/ProcessResponse/PaymentAction/actionTypes.js +1 -1
- package/dist/es/core/ProcessResponse/PaymentAction/actionTypes.js.map +1 -1
- package/dist/es/core/config.js +1 -1
- package/dist/es/index.d.ts +24 -5
- package/dist/es-legacy/adyen.css +3 -1
- package/dist/es-legacy/adyen.css.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/ExpirationDate.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/ExpirationDate.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/StoredCardFields.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/StoredCardFields.js.map +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js.map +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/InstantPaymentMethods.js +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/InstantPaymentMethods.js.map +1 -1
- package/dist/es-legacy/components/PayPal/components/PaypalButtons.js +1 -1
- package/dist/es-legacy/components/PayPal/components/PaypalButtons.js.map +1 -1
- package/dist/es-legacy/components/PayPal/defaultProps.js +1 -1
- package/dist/es-legacy/components/PayPal/defaultProps.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2Challenge.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2Challenge.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2DeviceFingerprint.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/ThreeDS2DeviceFingerprint.js.map +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.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/utils.js +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/utils.js.map +1 -1
- package/dist/es-legacy/components/helpers/QRLoaderContainer/QRLoaderContainer.js +1 -1
- package/dist/es-legacy/components/helpers/QRLoaderContainer/QRLoaderContainer.js.map +1 -1
- package/dist/es-legacy/components/internal/Address/Address.js +1 -1
- package/dist/es-legacy/components/internal/Address/Address.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/Fieldset/Fieldset.js +1 -1
- package/dist/es-legacy/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentAction/actionTypes.js +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentAction/actionTypes.js.map +1 -1
- package/dist/es-legacy/core/config.js +1 -1
- package/package.json +149 -157
- package/styles/adyen.css +3 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrepareChallenge3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoChallenge3DS2 from './DoChallenge3DS2';\nimport { createChallengeResolveData, prepareChallengeData, createOldChallengeResolveData, isErrorObject } from '../utils';\nimport { PrepareChallenge3DS2Props, PrepareChallenge3DS2State, StatusErrorInfoObject } from './types';\nimport { ChallengeData, ResultObject, ThreeDS2FlowObject, ErrorCodeObject } from '../../types';\nimport '../../ThreeDS2.scss';\nimport Img from '../../../internal/Img';\nimport './challenge.scss';\nimport { hasOwnProperty } from '../../../../utils/hasOwnProperty';\nimport useImage from '../../../../core/Context/useImage';\nimport AdyenCheckoutError, { ERROR } from '../../../../core/Errors/AdyenCheckoutError';\nimport { THREEDS2_CHALLENGE, THREEDS2_CHALLENGE_ERROR, THREEDS2_FULL, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG } from '../../constants';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\n\nclass PrepareChallenge3DS2 extends Component<PrepareChallenge3DS2Props, PrepareChallenge3DS2State> {\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n if (this.props.token) {\n const challengeData: ChallengeData | ErrorObject = prepareChallengeData({\n token: this.props.token,\n size: this.props.challengeWindowSize || this.props.size // TODO confirm that this.props.size is legacy and can be removed\n });\n\n this.state = {\n status: 'init',\n challengeData: challengeData as ChallengeData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { challengeData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_CHALLENGE_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.CHALLENGE_DATA_SENT\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasChallengeData = !isErrorObject(this.state.challengeData);\n\n if (hasChallengeData) {\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 challengeData\n */\n const { acsURL } = this.state.challengeData as ChallengeData;\n const hasValidAcsURL = isValidHttpUrl(acsURL, shouldAllowHttpDomains);\n\n // Only render component if we have an acsURL.\n if (!hasValidAcsURL) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL}: ${this.props.i18n.get('err.gen.9102')}` //\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing a valid acsURL property`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no valid acsURL');\n return;\n }\n\n const { acsTransID, messageVersion, threeDSServerTransID } = (this.state.challengeData as ChallengeData).cReqData;\n\n // Only render component if we have a acsTransID, messageVersion & threeDSServerTransID\n if (!acsTransID || !messageVersion || !threeDSServerTransID) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug(\n '### PrepareChallenge3DS2::exiting:: missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)'\n );\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'performingChallenge' });\n //\n } else {\n const errorMsg: string = (this.state.challengeData as ErrorObject).error;\n\n const errorCode =\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED;\n\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo:\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? `${Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN}: ${this.props.i18n.get('err.gen.9102')}`\n : `${Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if the base64 decoding errors *ever* happen\n const event = new AnalyticsErrorEvent({\n code: errorCode,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no challengeData');\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 ? createOldChallengeResolveData : createChallengeResolveData;\n const data = resolveDataFunction(this.props.dataKey, resultObj.transStatus, this.props.paymentData);\n\n if (errorCodeObject) {\n console.debug('### PrepareChallenge3DS2::errorCodeObject::', errorCodeObject);\n }\n\n let event: AnalyticsEvent;\n\n /** Are we in an \"error\" i.e. timeout or no transStatus, 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' ? Analytics3DS2Errors.THREEDS2_TIMEOUT : Analytics3DS2Errors.NO_TRANSSTATUS,\n errorType: finalResObject.errorCode === 'timeout' ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\n };\n\n // Challenge process has timed out,\n // or, It's an error reported by the backend 'cos no transStatus could be retrieved // TODO - check logs to see if this *ever* happens\n\n event = new AnalyticsErrorEvent({\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?.transStatus) {\n case 'Y':\n result = 'success';\n break;\n case 'N':\n result = 'failed';\n break;\n case 'U':\n result = !errorCodeObject ? 'cancelled' : 'timeout';\n break;\n default:\n }\n if (resultObj?.errorCode) {\n result = 'noTransStatus';\n }\n\n /** Create log object - the process is completed, one way or another */\n\n event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} challenge has completed`,\n subType: Analytics3DS2Events.CHALLENGE_COMPLETED,\n result\n });\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to onAdditionalDetails (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n /**\n * Display error in the UI,\n * and, optionally, decide whether to send any of these errors to the merchant defined onError callback\n *\n * @param errorInfoObj -\n * @param isFatal -\n */\n setError(errorInfoObj: StatusErrorInfoObject, isFatal: boolean) {\n this.setState({ status: 'error', errorInfo: errorInfoObj.errorInfo });\n\n // Decide whether to call this.props.onError\n if (isFatal) {\n this.props.onError(new AdyenCheckoutError(ERROR, errorInfoObj.errorInfo, { cause: errorInfoObj.errorObj }));\n }\n }\n\n render(_, { challengeData }) {\n const getImage = useImage();\n if (this.state.status === 'performingChallenge') {\n return (\n <DoChallenge3DS2\n onCompleteChallenge={(challenge: ThreeDS2FlowObject) => {\n let errorCodeObject: ErrorCodeObject = null;\n\n // Challenge has resulted in an error (no transStatus could be retrieved) - but we still treat this as a valid scenario\n if (hasOwnProperty(challenge.result, 'errorCode') && challenge.result.errorCode.length) {\n // Tell the merchant there's been an error\n errorCodeObject = {\n errorCode: challenge.result.errorCode,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription ? challenge.result.errorDescription : 'no transStatus could be retrieved'\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 this.props.onError(\n new AdyenCheckoutError(\n ERROR,\n `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription\n ? challenge.result.errorDescription\n : 'no transStatus could be retrieved'\n }`,\n { cause: challenge.result.errorCode }\n )\n );\n }\n }\n\n /**\n * An object has been returned, parsed & accepted as legit (according to the rules in getProcessMessageHandler),\n * but the result prop on that object is missing\n */\n if (!challenge.result) {\n this.setError(\n {\n errorInfo: `${THREEDS2_CHALLENGE_ERROR}: ${this.props.i18n.get('3ds.chal.805', {\n values: { result: '\"result\"' }\n })}`,\n errorObj: challenge as unknown as ErrorObject\n },\n true\n );\n\n // Send error to analytics endpoint\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: challenge resolved without a \"result\" object`\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: challenge resolved without a \"result\" object');\n\n return;\n }\n\n // Proceed with call to onAdditionalDetails (except for in 3DS2InMDFlow)\n this.setStatusComplete(challenge.result, errorCodeObject);\n }}\n onErrorChallenge={(challenge: ThreeDS2FlowObject) => {\n /**\n * Called when challenge times-out (which is still a valid scenario)...\n */\n if (hasOwnProperty(challenge, 'errorCode')) {\n const timeoutObject: ErrorCodeObject = {\n errorCode: challenge.errorCode,\n message: `${THREEDS2_CHALLENGE}: ${challenge.errorCode}`\n };\n\n // see comment in onCompleteChallenge code block\n if (this.props.isMDFlow) {\n this.props.onError(\n new AdyenCheckoutError(ERROR, `${THREEDS2_CHALLENGE_ERROR}: '3DS2 challenge timed out'`, {\n cause: challenge.errorCode\n })\n );\n }\n\n this.setStatusComplete(challenge.result, timeoutObject);\n return;\n }\n }}\n {...challengeData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n if (this.state.status === 'error') {\n return (\n <div className=\"adyen-checkout__threeds2-challenge-error\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({\n imageFolder: 'components/'\n })('error')}\n alt={''}\n />\n <div className=\"adyen-checkout__status__text\">\n {this.state.errorInfo ? this.state.errorInfo : this.props.i18n.get('error.message.unknown')}\n </div>\n </div>\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareChallenge3DS2;\n"],"names":["PrepareChallenge3DS2","Component","componentDidMount","isErrorObject","this","state","challengeData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","acsURL","isValidHttpUrl","setError","errorInfo","Analytics3DS2Errors","TOKEN_IS_MISSING_ACSURL","i18n","get","event","AnalyticsErrorEvent","code","errorType","ANALYTICS_ERROR_TYPE","apiError","message","THREEDS2_CHALLENGE_ERROR","onSubmitAnalytics","console","debug","acsTransID","messageVersion","threeDSServerTransID","cReqData","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","errorCode","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","setStatusComplete","resultObj","errorCodeObject","data","isMDFlow","createOldChallengeResolveData","createChallengeResolveData","dataKey","transStatus","paymentData","finalResObject","errorTypeAndCode","THREEDS2_TIMEOUT","NO_TRANSSTATUS","network","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","CHALLENGE_COMPLETED","onComplete","errorInfoObj","isFatal","onError","AdyenCheckoutError","ERROR","cause","errorObj","render","_","getImage","useImage","h","DoChallenge3DS2","onCompleteChallenge","challenge","hasOwnProperty","length","errorDescription","values","CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP","onErrorChallenge","timeoutObject","THREEDS2_CHALLENGE","onActionHandled","onFormSubmit","div","className","Img","src","imageFolder","alt","constructor","super","_define_property","msg","CHALLENGE_DATA_SENT","token","prepareChallengeData","size","challengeWindowSize","success","defaultProps"],"mappings":"unCAmBA,MAAMA,UAA6BC,EAsC/BC,iBAAAA,GAGI,IAF0BC,EAAcC,KAAKC,MAAMC,eAE7B,CAClB,MAAMC,EAO0B,SAA3BH,KAAKI,MAAMC,aAA0BL,KAAKI,MAAME,kBAAkBC,KAAKC,SAAS,0BAK/EC,OAAEA,GAAWT,KAAKC,MAAMC,cAI9B,IAHuBQ,EAAeD,EAAQN,GAGzB,CAE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AAAA,CACGD,UAAU,mEACVE,IAAKnB,EAAS,CACVoB,YAAa,eADZpB,CAEF,SACHqB,IAAK,KAETnB,EAACc,MAAAA,CAAIC,UAAU,gCACV5F,KAAKC,MAAMW,UAAYZ,KAAKC,MAAMW,UAAYZ,KAAKI,MAAMW,KAAKC,IAAI,2BAM5E,IACX,CAtVA,WAAAiF,CAAY7F,GAGR,GAFA8F,MAAM9F,GAoBV+F,EAAAnG,KAAO0F,eAAgBU,IACnB,MAAMnF,EAAQ,IAAIyC,EAAkB,CAChCC,KAAMC,EACNrC,QAAS6E,EACTtC,QAASC,EAAoBsC,sBAGjCrG,KAAKI,MAAMqB,kBAAkBR,KAzBzBjB,KAAKI,MAAMkG,MAAO,CAClB,MAAMpG,EAA6CqG,EAAqB,CACpED,MAAOtG,KAAKI,MAAMkG,MAClBE,KAAMxG,KAAKI,MAAMqG,qBAAuBzG,KAAKI,MAAMoG,OAGvDxG,KAAKC,MAAQ,CACTiC,OAAQ,OACRhC,cAAeA,EAEvB,MAEIF,KAAKC,MAAQ,CAAEC,cAAe,CAAEwG,SAAS,EAAOtE,MAAOG,IAEvDb,QAAQC,MAAM,GAAGH,MAA6Be,IAEtD,EAzBA4D,EADEvG,EACY+G,eAAe,CACzB1C,WAAY,OACZG,QAAS,OACTtB,UAAU"}
|
|
1
|
+
{"version":3,"file":"PrepareChallenge3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoChallenge3DS2 from './DoChallenge3DS2';\nimport { createChallengeResolveData, prepareChallengeData, createOldChallengeResolveData, isErrorObject } from '../utils';\nimport { PrepareChallenge3DS2Props, PrepareChallenge3DS2State, StatusErrorInfoObject } from './types';\nimport { ChallengeData, ResultObject, ThreeDS2FlowObject, ErrorCodeObject, LegacyChallengeResolveData, ChallengeResolveData } from '../../types';\nimport '../../ThreeDS2.scss';\nimport Img from '../../../internal/Img';\nimport './challenge.scss';\nimport { hasOwnProperty } from '../../../../utils/hasOwnProperty';\nimport useImage from '../../../../core/Context/useImage';\nimport AdyenCheckoutError, { ERROR } from '../../../../core/Errors/AdyenCheckoutError';\nimport { THREEDS2_CHALLENGE, THREEDS2_CHALLENGE_ERROR, THREEDS2_FULL, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG } from '../../constants';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\n\nclass PrepareChallenge3DS2 extends Component<PrepareChallenge3DS2Props, PrepareChallenge3DS2State> {\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n if (this.props.token) {\n const challengeData: ChallengeData | ErrorObject = prepareChallengeData({\n token: this.props.token,\n size: this.props.challengeWindowSize || this.props.size // TODO confirm that this.props.size is legacy and can be removed\n });\n\n this.state = {\n status: 'init',\n challengeData: challengeData as ChallengeData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { challengeData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_CHALLENGE_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.CHALLENGE_DATA_SENT\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasChallengeData = !isErrorObject(this.state.challengeData);\n\n if (hasChallengeData) {\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 challengeData\n */\n const { acsURL } = this.state.challengeData as ChallengeData;\n const hasValidAcsURL = isValidHttpUrl(acsURL, shouldAllowHttpDomains);\n\n // Only render component if we have an acsURL.\n if (!hasValidAcsURL) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL}: ${this.props.i18n.get('err.gen.9102')}` //\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing a valid acsURL property`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no valid acsURL');\n return;\n }\n\n const { acsTransID, messageVersion, threeDSServerTransID } = (this.state.challengeData as ChallengeData).cReqData;\n\n // Only render component if we have a acsTransID, messageVersion & threeDSServerTransID\n if (!acsTransID || !messageVersion || !threeDSServerTransID) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug(\n '### PrepareChallenge3DS2::exiting:: missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)'\n );\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'performingChallenge' });\n //\n } else {\n const errorMsg: string = (this.state.challengeData as ErrorObject).error;\n\n const errorCode =\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED;\n\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo:\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? `${Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN}: ${this.props.i18n.get('err.gen.9102')}`\n : `${Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if the base64 decoding errors *ever* happen\n const event = new AnalyticsErrorEvent({\n code: errorCode,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no challengeData');\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 ? createOldChallengeResolveData : createChallengeResolveData;\n const data: LegacyChallengeResolveData | ChallengeResolveData = resolveDataFunction(\n this.props.dataKey,\n resultObj.transStatus,\n this.props.paymentData\n );\n\n if (errorCodeObject) {\n console.debug('### PrepareChallenge3DS2::errorCodeObject::', errorCodeObject);\n }\n\n let event: AnalyticsEvent;\n\n /** Are we in an \"error\" i.e. timeout or no transStatus, 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' ? Analytics3DS2Errors.THREEDS2_TIMEOUT : Analytics3DS2Errors.NO_TRANSSTATUS,\n errorType: finalResObject.errorCode === 'timeout' ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\n };\n\n // Challenge process has timed out,\n // or, It's an error reported by the backend 'cos no transStatus could be retrieved // TODO - check logs to see if this *ever* happens\n\n event = new AnalyticsErrorEvent({\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?.transStatus) {\n case 'Y':\n result = 'success';\n break;\n case 'N':\n result = 'failed';\n break;\n case 'U':\n result = !errorCodeObject ? 'cancelled' : 'timeout';\n break;\n default:\n }\n if (resultObj?.errorCode) {\n result = 'noTransStatus';\n }\n\n /** Create log object - the process is completed, one way or another */\n\n event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} challenge has completed`,\n subType: Analytics3DS2Events.CHALLENGE_COMPLETED,\n result\n });\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to onAdditionalDetails (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n /**\n * Display error in the UI,\n * and, optionally, decide whether to send any of these errors to the merchant defined onError callback\n *\n * @param errorInfoObj -\n * @param isFatal -\n */\n setError(errorInfoObj: StatusErrorInfoObject, isFatal: boolean) {\n this.setState({ status: 'error', errorInfo: errorInfoObj.errorInfo });\n\n // Decide whether to call this.props.onError\n if (isFatal) {\n this.props.onError(new AdyenCheckoutError(ERROR, errorInfoObj.errorInfo, { cause: errorInfoObj.errorObj }));\n }\n }\n\n render(_, { challengeData }) {\n const getImage = useImage();\n if (this.state.status === 'performingChallenge') {\n return (\n <DoChallenge3DS2\n onCompleteChallenge={(challenge: ThreeDS2FlowObject) => {\n let errorCodeObject: ErrorCodeObject = null;\n\n // Challenge has resulted in an error (no transStatus could be retrieved) - but we still treat this as a valid scenario\n if (hasOwnProperty(challenge.result, 'errorCode') && challenge.result.errorCode.length) {\n // Tell the merchant there's been an error\n errorCodeObject = {\n errorCode: challenge.result.errorCode,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription ? challenge.result.errorDescription : 'no transStatus could be retrieved'\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 this.props.onError(\n new AdyenCheckoutError(\n ERROR,\n `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription\n ? challenge.result.errorDescription\n : 'no transStatus could be retrieved'\n }`,\n { cause: challenge.result.errorCode }\n )\n );\n }\n }\n\n /**\n * An object has been returned, parsed & accepted as legit (according to the rules in getProcessMessageHandler),\n * but the result prop on that object is missing\n */\n if (!challenge.result) {\n this.setError(\n {\n errorInfo: `${THREEDS2_CHALLENGE_ERROR}: ${this.props.i18n.get('3ds.chal.805', {\n values: { result: '\"result\"' }\n })}`,\n errorObj: challenge as unknown as ErrorObject\n },\n true\n );\n\n // Send error to analytics endpoint\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: challenge resolved without a \"result\" object`\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: challenge resolved without a \"result\" object');\n\n return;\n }\n\n // Proceed with call to onAdditionalDetails (except for in 3DS2InMDFlow)\n this.setStatusComplete(challenge.result, errorCodeObject);\n }}\n onErrorChallenge={(challenge: ThreeDS2FlowObject) => {\n /**\n * Called when challenge times-out (which is still a valid scenario)...\n */\n if (hasOwnProperty(challenge, 'errorCode')) {\n const timeoutObject: ErrorCodeObject = {\n errorCode: challenge.errorCode,\n message: `${THREEDS2_CHALLENGE}: ${challenge.errorCode}`\n };\n\n // see comment in onCompleteChallenge code block\n if (this.props.isMDFlow) {\n this.props.onError(\n new AdyenCheckoutError(ERROR, `${THREEDS2_CHALLENGE_ERROR}: '3DS2 challenge timed out'`, {\n cause: challenge.errorCode\n })\n );\n }\n\n this.setStatusComplete(challenge.result, timeoutObject);\n return;\n }\n }}\n {...challengeData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n if (this.state.status === 'error') {\n return (\n <div className=\"adyen-checkout__threeds2-challenge-error\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({\n imageFolder: 'components/'\n })('error')}\n alt={''}\n />\n <div className=\"adyen-checkout__status__text\">\n {this.state.errorInfo ? this.state.errorInfo : this.props.i18n.get('error.message.unknown')}\n </div>\n </div>\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareChallenge3DS2;\n"],"names":["PrepareChallenge3DS2","Component","componentDidMount","isErrorObject","this","state","challengeData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","acsURL","isValidHttpUrl","setError","errorInfo","Analytics3DS2Errors","TOKEN_IS_MISSING_ACSURL","i18n","get","event","AnalyticsErrorEvent","code","errorType","ANALYTICS_ERROR_TYPE","apiError","message","THREEDS2_CHALLENGE_ERROR","onSubmitAnalytics","console","debug","acsTransID","messageVersion","threeDSServerTransID","cReqData","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","errorCode","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","setStatusComplete","resultObj","errorCodeObject","data","isMDFlow","createOldChallengeResolveData","createChallengeResolveData","dataKey","transStatus","paymentData","finalResObject","errorTypeAndCode","THREEDS2_TIMEOUT","NO_TRANSSTATUS","network","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","CHALLENGE_COMPLETED","onComplete","errorInfoObj","isFatal","onError","AdyenCheckoutError","ERROR","cause","errorObj","render","_","getImage","useImage","h","DoChallenge3DS2","onCompleteChallenge","challenge","hasOwnProperty","length","errorDescription","values","CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP","onErrorChallenge","timeoutObject","THREEDS2_CHALLENGE","onActionHandled","onFormSubmit","div","className","Img","src","imageFolder","alt","constructor","super","_define_property","msg","CHALLENGE_DATA_SENT","token","prepareChallengeData","size","challengeWindowSize","success","defaultProps"],"mappings":"unCAmBA,MAAMA,UAA6BC,EAsC/BC,iBAAAA,GAGI,IAF0BC,EAAcC,KAAKC,MAAMC,eAE7B,CAClB,MAAMC,EAO0B,SAA3BH,KAAKI,MAAMC,aAA0BL,KAAKI,MAAME,kBAAkBC,KAAKC,SAAS,0BAK/EC,OAAEA,GAAWT,KAAKC,MAAMC,cAI9B,IAHuBQ,EAAeD,EAAQN,GAGzB,CAEjBH,KAAKW,SACD,CACIC,UAAW,GAAGC,EAAoBC,4BAA4Bd,KAAKI,MAAMW,KAAKC,IAAI,oBAEtF,GAIJ,MAAMC,EAAQ,IAAIC,EAAoB,CAClCC,KAAMN,EAAoBC,wBAC1BM,UAAWC,EAAqBC,SAChCC,QAAS,GAAGC,wDAKhB,OAHAxB,KAAKI,MAAMqB,kBAAkBR,QAE7BS,QAAQC,MAAM,sDAElB,CAEA,MAAMC,WAA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AgBU,IACnB,MAAMnF,EAAQ,IAAIyC,EAAkB,CAChCC,KAAMC,EACNrC,QAAS6E,EACTtC,QAASC,EAAoBsC,sBAGjCrG,KAAKI,MAAMqB,kBAAkBR,KAzBzBjB,KAAKI,MAAMkG,MAAO,CAClB,MAAMpG,EAA6CqG,EAAqB,CACpED,MAAOtG,KAAKI,MAAMkG,MAClBE,KAAMxG,KAAKI,MAAMqG,qBAAuBzG,KAAKI,MAAMoG,OAGvDxG,KAAKC,MAAQ,CACTiC,OAAQ,OACRhC,cAAeA,EAEvB,MAEIF,KAAKC,MAAQ,CAAEC,cAAe,CAAEwG,SAAS,EAAOtE,MAAOG,IAEvDb,QAAQC,MAAM,GAAGH,MAA6Be,IAEtD,EAzBA4D,EADEvG,EACY+G,eAAe,CACzB1C,WAAY,OACZG,QAAS,OACTtB,UAAU"}
|
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 } from '../../types';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { THREEDS2_FULL, THREEDS2_FINGERPRINT, THREEDS2_FINGERPRINT_ERROR, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG, TIMEOUT } from '../../constants';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static type = 'scheme';\n\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\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 type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.FINGERPRINT_DATA_SENT\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: Analytics3DS2Errors.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: Analytics3DS2Errors.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 ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.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 = resolveDataFunction(this.props.dataKey, resultObj, this.props.paymentData);\n\n let event: AnalyticsEvent;\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 ? Analytics3DS2Errors.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: finalResObject.errorCode === TIMEOUT ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\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 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 type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n subType: Analytics3DS2Events.FINGERPRINT_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","Analytics3DS2Errors","TOKEN_IS_MISSING_THREEDSMETHODURL","message","THREEDS2_FINGERPRINT_ERROR","console","debug","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","isMDFlow","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","paymentData","event","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ANALYTICS_ERROR_TYPE","network","apiError","AnalyticsErrorEvent","onSubmitAnalytics","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","FINGERPRINT_COMPLETED","onComplete","render","showSpinner","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT","onActionHandled","onFormSubmit","constructor","super","_define_property","msg","FINGERPRINT_DATA_SENT","token","notificationURL","prepareFingerPrintData","success","defaultProps","onError"],"mappings":"k6BAaA,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,GAAy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ba,IAExD,EA5BA6C,EADElF,EACY8D,OAAO,UAErBoB,EAHElF,EAGYyF,eAAe,CACzBrB,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_FULL, THREEDS2_FINGERPRINT, THREEDS2_FINGERPRINT_ERROR, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG, TIMEOUT } from '../../constants';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static type = 'scheme';\n\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\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 type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.FINGERPRINT_DATA_SENT\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: Analytics3DS2Errors.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: Analytics3DS2Errors.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 ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.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: AnalyticsEvent;\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 ? Analytics3DS2Errors.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: finalResObject.errorCode === TIMEOUT ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\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 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 type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n subType: Analytics3DS2Events.FINGERPRINT_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","Analytics3DS2Errors","TOKEN_IS_MISSING_THREEDSMETHODURL","message","THREEDS2_FINGERPRINT_ERROR","console","debug","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","isMDFlow","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","paymentData","event","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ANALYTICS_ERROR_TYPE","network","apiError","AnalyticsErrorEvent","onSubmitAnalytics","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","FINGERPRINT_COMPLETED","onComplete","render","showSpinner","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT","onActionHandled","onFormSubmit","constructor","super","_define_property","msg","FINGERPRINT_DATA_SENT","token","notificationURL","prepareFingerPrintData","success","defaultProps","onError"],"mappings":"k6BAaA,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,EAAoBC,kCAC/BC,QAAS,GAAGC,uEAWpBC,QAAQC,MAAM,mEAIlB,MAAMC,EAAmCV,EAAeH,EAA8BP,GAChFqB,EAA4BX,EAAeF,EAAmBR,GAC9DsB,EAAmBb,GAAsBc,OAE/C,IAAKH,IAAqCC,IAA8BC,EAiBpE,OAZAzB,KAAKc,kBACD,CAAEC,eAAgB,KAClB,CACIC,UAAWC,EAAoBU,6BAC/BR,QAAS,GAAGC,uJAIpBC,Q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AEA,IAC9B,MAAe,0BAAX2B,EAEIsC,EAACC,EAAAA,CACGC,sBAAuBC,IACnBtE,KAAKc,kBAAkBwD,EAAYd,SAEvCe,mBAAoBD,IAIhB,MAAME,EAAiC,CACnCxD,UAAWsD,EAAYtD,UACvBG,QAAS,GAAGsD,MAAyBH,EAAYtD,aAGrDhB,KAAKc,kBAAkBwD,EAAYd,OAAQgB,IAE/CN,YAAaA,KACThE,EACJwE,gBAAiB1E,KAAKI,MAAMsE,gBAC5BC,aAAc3E,KAAK2E,eAKxB,IACX,CA5OA,WAAAC,CAAYxE,GACRyE,MAAMzE,GAmBV0E,EAAA9E,KAAO2E,eAAgBI,IACnB,MAAMnC,EAAQ,IAAIa,EAAkB,CAChCC,KAAMC,EACNxC,QAAS4D,EACTlB,QAASC,EAAoBkB,wBAGjChF,KAAKI,MAAMmD,kBAAkBX,KAxB7B,MAAMqC,MAAEA,EAAKC,gBAAEA,GAAoBlF,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,EA5BA6C,EADElF,EACY8D,OAAO,UAErBoB,EAHElF,EAGYyF,eAAe,CACzBrB,WAAY,OACZsB,QAAS,OACT3C,YAAa,GACbuB,aAAa,EACb3B,UAAU"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CHALLENGE_WINDOW_SIZES as e,DEFAULT_CHALLENGE_WINDOW_SIZE as t}from"../constants.js";import{getOrigin as r}from"../../../utils/getOrigin.js";import
|
|
1
|
+
import{CHALLENGE_WINDOW_SIZES as e,DEFAULT_CHALLENGE_WINDOW_SIZE as t}from"../constants.js";import{getOrigin as r}from"../../../utils/getOrigin.js";import n from"../../../utils/base64.js";import{pick as s}from"../../../utils/commonUtils.js";const a=e=>"success"in e&&!e.success,o=e=>{const t=n.decode(e);if(t.success)try{return JSON.parse(t.data)}catch(e){return{success:!1,error:"Could not JSON parse token"}}return t},i=e=>{if(!e||!Object.keys(e).length)throw new Error("No (populated) data object to encode");return n.encode(JSON.stringify(e))},c=r=>{const n=1===r.length?`0${r}`:r;return Object.prototype.hasOwnProperty.call(e,n)?n:t},l=t=>e[c(t)],p=({token:e,size:t})=>{const n=o(e);if(a(n))return n;const{acsTransID:s,acsURL:i,messageVersion:p,threeDSNotificationURL:d,threeDSServerTransID:m}=n,u=r(d);return{acsURL:i,cReqData:{acsTransID:s,messageVersion:p,threeDSServerTransID:m,messageType:"CReq",challengeWindowSize:c(t)},iframeSizeArr:l(t),postMessageDomain:u}},d=({token:e,notificationURL:t})=>{const n=o(e);if(a(n))return n;const{threeDSMethodNotificationURL:s,threeDSMethodUrl:i,threeDSServerTransID:c}=n,l=t||s;return{threeDSServerTransID:c,threeDSMethodURL:i,threeDSMethodNotificationURL:l,postMessageDomain:r(l)}},m=(e,t,r)=>({data:{[e]:i({threeDSCompInd:t.threeDSCompInd}),paymentData:r}}),u=(e,t,r)=>({data:{details:{"threeds2.fingerprint":i(t)},paymentData:r}}),h=(e,t,r)=>({data:{details:{[e]:i({transStatus:t,authorisationToken:r})}}}),D=(e,t,r)=>({data:{details:{"threeds2.challengeResult":i({transStatus:t})},paymentData:r}}),S=e=>{let t=window.btoa(e).split("=")[0];return t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_"),t},f=["elementRef"],g=["createFromAction","onAdditionalDetails"],R=(e,t)=>{if("fingerprint"===e){const e=t.elementRef?f:g,r=s(e).from(t);return r.showSpinner=!t.isDropin,r.statusType="loading",r}return{statusType:"custom",i18n:t.i18n,elementRef:t.elementRef}};export{h as createChallengeResolveData,m as createFingerprintResolveData,D as createOldChallengeResolveData,u as createOldFingerprintResolveData,o as decodeAndParseToken,S as encodeBase64URL,i as encodeObject,R as get3DS2FlowProps,l as getChallengeWindowSize,a as isErrorObject,p as prepareChallengeData,d as prepareFingerPrintData,c as validateChallengeWindowSize};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../src/components/ThreeDS2/components/utils.ts"],"sourcesContent":["import { CHALLENGE_WINDOW_SIZES, DEFAULT_CHALLENGE_WINDOW_SIZE } from '../constants';\nimport { getOrigin } from '../../../utils/getOrigin';\nimport base64 from '../../../utils/base64';\nimport { ChallengeData, ThreeDS2Token, FingerPrintData, ResultObject, FingerprintResolveData, ChallengeResolveData } from '../types';\nimport { pick } from '../../../utils/commonUtils';\nimport { DecodeObject } from '../../../types/global-types';\nimport { ErrorObject } from '../../../core/Errors/types';\n\n/**\n * Check if we have been passed an ErrorObject because either base64 decoding or JSON.parse failed\n * @param obj -\n */\nexport const isErrorObject = (obj: ErrorObject | ThreeDS2Token): boolean => {\n return 'success' in obj && !obj.success;\n};\n\nexport const decodeAndParseToken = (token: string): ThreeDS2Token | ErrorObject => {\n const decodedToken: DecodeObject = base64.decode(token);\n if (decodedToken.success) {\n try {\n return JSON.parse(decodedToken.data) as ThreeDS2Token;\n } catch (e) {\n return {\n success: false,\n error: 'Could not JSON parse token'\n };\n }\n }\n\n // base64.decode failed - object will contain error msg: 'not base64' or 'malformed URI sequence'\n return decodedToken as ErrorObject;\n};\n\n/**\n * Performs JSON.stringify on passed object & and base64 encodes result\n * @param obj -\n * @returns encoded result\n */\nexport const encodeObject = obj => {\n if (!obj || !Object.keys(obj).length) {\n throw new Error('No (populated) data object to encode');\n }\n return base64.encode(JSON.stringify(obj));\n};\n\n/**\n * Accepts a size string for the challenge window & returns it if it is valid else returns a default value\n * @param sizeStr - the size string to check the validity of\n * @returns a valid size string\n */\nexport const validateChallengeWindowSize = (sizeStr: string): string => {\n const sizeString = sizeStr.length === 1 ? `0${sizeStr}` : sizeStr;\n const hasSize = Object.prototype.hasOwnProperty.call(CHALLENGE_WINDOW_SIZES, sizeString);\n return hasSize ? sizeString : DEFAULT_CHALLENGE_WINDOW_SIZE;\n};\n\n/**\n * Accepts a size string for the challenge window & returns the corresponding array of w/h values\n * @param sizeStr -\n */\nexport const getChallengeWindowSize = (sizeStr: string): string[] => CHALLENGE_WINDOW_SIZES[validateChallengeWindowSize(sizeStr)];\n\n/**\n * prepareChallengeData\n *\n * Requires an object containing the challenge parameters:\n * @param token - challengeToken string received from /submitThreeDS2Fingerprint, /details or /payments call: contains acsTransID, acsURL, messageVersion,\n * threeDSNotificationURL and threeDSServerTransID\n * @param size - one of five possible challenge window sizes\n */\nexport const prepareChallengeData = ({ token, size }): ChallengeData | ErrorObject => {\n const decodedChallengeToken = decodeAndParseToken(token);\n\n if (isErrorObject(decodedChallengeToken)) {\n return decodedChallengeToken as ErrorObject;\n }\n\n const { acsTransID, acsURL, messageVersion, threeDSNotificationURL, threeDSServerTransID } = decodedChallengeToken as ThreeDS2Token;\n const notificationURLOrigin = getOrigin(threeDSNotificationURL);\n\n return {\n acsURL,\n cReqData: {\n acsTransID,\n messageVersion,\n threeDSServerTransID,\n messageType: 'CReq',\n challengeWindowSize: validateChallengeWindowSize(size)\n },\n iframeSizeArr: getChallengeWindowSize(size),\n postMessageDomain: notificationURLOrigin\n } as ChallengeData;\n};\n\n/**\n * prepareFingerPrintData\n *\n * Requires an object containing the fingerprint parameters:\n * @param token - fingerprintToken string received from /payments call: contains threeDSMethodNotificationURL, threeDSMethodUrl and\n * threeDSServerTransID\n * @param notificationURL - the URL that the final notification is expected to be postMessaged from.\n *\n * NOTE: we don't expect merchants to alter the default by passing in a notificationURL of their own via props;\n * and if 3DS2 is being done via createFromAction or handleAction we won't accept it.\n * But if the merchant is using checkout.create('threeDS2DeviceFingerprint') we still support the fact that they might want to set their own\n * notificationURL (aka threeDSMethodNotificationURL)\n */\nexport const prepareFingerPrintData = ({ token, notificationURL }): FingerPrintData | ErrorObject => {\n const decodedFingerPrintToken = decodeAndParseToken(token);\n\n if (isErrorObject(decodedFingerPrintToken)) {\n return decodedFingerPrintToken as ErrorObject;\n }\n\n const { threeDSMethodNotificationURL, threeDSMethodUrl: threeDSMethodURL, threeDSServerTransID } = decodedFingerPrintToken as ThreeDS2Token;\n const receivedNotificationURL = notificationURL || threeDSMethodNotificationURL;\n const notificationURLOrigin = getOrigin(receivedNotificationURL);\n\n return {\n threeDSServerTransID,\n threeDSMethodURL,\n threeDSMethodNotificationURL: receivedNotificationURL,\n postMessageDomain: notificationURLOrigin\n } as FingerPrintData;\n};\n\nexport const createFingerprintResolveData = (dataKey: string, resultObj: ResultObject, paymentData: string): FingerprintResolveData => ({\n data: {\n [dataKey]: encodeObject({ threeDSCompInd: resultObj.threeDSCompInd }),\n paymentData\n }\n});\n\n// Old 3DS2 flow\nexport const createOldFingerprintResolveData = (dataKey: string, resultObj: ResultObject, paymentData: string): any => ({\n data: {\n details: { 'threeds2.fingerprint': encodeObject(resultObj) },\n paymentData\n }\n});\n\nexport const createChallengeResolveData = (dataKey: string, transStatus: string, authorisationToken: string): ChallengeResolveData => ({\n data: {\n details: { [dataKey]: encodeObject({ transStatus, authorisationToken }) }\n }\n});\n\n// Needed for old 3DS2 flow & threeds2InMDFlow\nexport const createOldChallengeResolveData = (dataKey: string, transStatus: string, authorisationToken: string): any => ({\n data: {\n details: { 'threeds2.challengeResult': encodeObject({ transStatus }) },\n paymentData: authorisationToken\n }\n});\n\n/**\n *\n * Takes a string and encodes it as a base64url string\n * (https://en.wikipedia.org/wiki/Base64#URL_applications)\n * (See also https://tools.ietf.org/html/rfc7515)\n *\n * @example\n * ```\n * const jsonStr = JSON.stringify( {name:'john', surname:'smith'} );\n * const base64url = encodeBase64URL(jsonStr);\n * ```\n *\n * @param dataStr - data, as a string, to be encoded\n *\n * @returns base64URL - a base64url encoded string\n */\nexport const encodeBase64URL = (dataStr: string): string => {\n const base64Data = window.btoa(dataStr);\n let base64url = base64Data.split('=')[0]; // Remove any trailing '='s\n\n base64url = base64url.replace(/\\+/g, '-'); // 62nd char of encoding\n base64url = base64url.replace(/\\//g, '_'); // 63rd char of encoding\n\n return base64url;\n};\n\nconst fingerprintFlowPropsDropin = ['elementRef'];\n\n/**\n * Must contain all props needed for the challenge stage since, in the new 3DS2 flow, the fingerprint component will be the \"component\" reference\n * if the /submitThreeDS2Fingerprint response dictates we \"handleAction\" to create a challenge\n */\nconst fingerprintFlowProps = ['createFromAction', 'onAdditionalDetails'];\n\n/**\n * Add props specifically needed for the type of 3DS2 flow: fingerprint or challenge\n *\n * @param actionSubtype - 3DS2 flow type: fingerprint or challenge\n * @param props - object from which to extract particular properties\n */\nexport const get3DS2FlowProps = (actionSubtype, props) => {\n if (actionSubtype === 'fingerprint') {\n // elementRef exists when the fingerprint component is created from the Dropin\n const fingerprintProps = props.elementRef ? fingerprintFlowPropsDropin : fingerprintFlowProps;\n const rtnObj = pick(fingerprintProps).from(props);\n rtnObj.showSpinner = !props.isDropin;\n rtnObj.statusType = 'loading';\n return rtnObj;\n }\n\n // Challenge\n return {\n statusType: 'custom',\n i18n: props.i18n\n };\n};\n"],"names":["isErrorObject","obj","success","decodeAndParseToken","token","decodedToken","base64","decode","JSON","parse","data","e","error","encodeObject","Object","keys","length","Error","encode","stringify","validateChallengeWindowSize","sizeStr","sizeString","prototype","hasOwnProperty","call","CHALLENGE_WINDOW_SIZES","DEFAULT_CHALLENGE_WINDOW_SIZE","getChallengeWindowSize","prepareChallengeData","size","decodedChallengeToken","acsTransID","acsURL","messageVersion","threeDSNotificationURL","threeDSServerTransID","notificationURLOrigin","getOrigin","cReqData","messageType","challengeWindowSize","iframeSizeArr","postMessageDomain","prepareFingerPrintData","notificationURL","decodedFingerPrintToken","threeDSMethodNotificationURL","threeDSMethodUrl","threeDSMethodURL","receivedNotificationURL","createFingerprintResolveData","dataKey","resultObj","paymentData","threeDSCompInd","createOldFingerprintResolveData","details","createChallengeResolveData","transStatus","authorisationToken","createOldChallengeResolveData","encodeBase64URL","dataStr","base64url","window","btoa","split","replace","fingerprintFlowPropsDropin","fingerprintFlowProps","get3DS2FlowProps","actionSubtype","props","fingerprintProps","elementRef","rtnObj","pick","from","showSpinner","isDropin","statusType","i18n"],"mappings":"iPAYO,MAAMA,EAAiBC,GACnB,YAAaA,IAAQA,EAAIC,QAGvBC,EAAuBC,IAChC,MAAMC,EAA6BC,EAAOC,OAAOH,GACjD,GAAIC,EAAaH,QACb,IACI,OAAOM,KAAKC,MAAMJ,EAAaK,KACnC,CAAE,MAAOC,GACL,MAAO,CACHT,SAAS,EACTU,MAAO,6BAEf,CAIJ,OAAOP,GAQEQ,EAAeZ,IACxB,IAAKA,IAAQa,OAAOC,KAAKd,GAAKe,OAC1B,MAAM,IAAIC,MAAM,wCAEpB,OAAOX,EAAOY,OAAOV,KAAKW,UAAUlB,KAQ3BmB,EAA+BC,IACxC,MAAMC,EAAgC,IAAnBD,EAAQL,OAAe,IAAIK,IAAYA,EAE1D,OADgBP,OAAOS,UAAUC,eAAeC,KAAKC,EAAwBJ,GAC5DA,EAAaK,GAOrBC,EAA0BP,GAA8BK,EAAuBN,EAA4BC,IAU3GQ,EAAuB,EAAGzB,QAAO0B,WAC1C,MAAMC,EAAwB5B,EAAoBC,GAElD,GAAIJ,EAAc+B,GACd,OAAOA,EAGX,MAAMC,WAAEA,EAAUC,OAAEA,EAAMC,eAAEA,EAAcC,uBAAEA,EAAsBC,qBAAEA,GAAyBL,EACvFM,EAAwBC,EAAUH,GAExC,MAAO,CACHF,SACAM,SAAU,CACNP,aACAE,iBACAE,uBACAI,YAAa,OACbC,oBAAqBrB,EAA4BU,IAErDY,cAAed,EAAuBE,GACtCa,kBAAmBN,IAiBdO,EAAyB,EAAGxC,QAAOyC,sBAC5C,MAAMC,EAA0B3C,EAAoBC,GAEpD,GAAIJ,EAAc8C,GACd,OAAOA,EAGX,MAAMC,6BAAEA,EAA8BC,iBAAkBC,EAAgBb,qBAAEA,GAAyBU,EAC7FI,EAA0BL,GAAmBE,EAGnD,MAAO,CACHX,uBACAa,mBACAF,6BAA8BG,EAC9BP,kBAN0BL,EAAUY,KAU/BC,EAA+B,CAACC,EAAiBC,EAAyBC,MACnF5C,KAAM,CACF0C,CAACA,GAAUvC,EAAa,CAAE0C,eAAgBF,EAAUE,iBACpDD,iBAKKE,EAAkC,CAACJ,EAAiBC,EAAyBC,MACtF5C,KAAM,CACF+C,QAAS,CAAE,uBAAwB5C,EAAawC,IAChDC,iBAIKI,EAA6B,CAACN,EAAiBO,EAAqBC,MAC7ElD,KAAM,CACF+C,QAAS,CAAEL,CAACA,GAAUvC,EAAa,CAAE8C,cAAaC,2BAK7CC,EAAgC,CAACT,EAAiBO,EAAqBC,MAChFlD,KAAM,CACF+C,QAAS,CAAE,2BAA4B5C,EAAa,CAAE8C,iBACtDL,YAAaM,KAoBRE,EAAmBC,IAE5B,IAAIC,EADeC,OAAOC,KAAKH,GACJI,MAAM,KAAK,GAKtC,OAHAH,EAAYA,EAAUI,QAAQ,MAAO,KACrCJ,EAAYA,EAAUI,QAAQ,MAAO,KAE9BJ,GAGLK,EAA6B,CAAC,cAM9BC,EAAuB,CAAC,mBAAoB,uBAQrCC,EAAmB,CAACC,EAAeC,KAC5C,GAAsB,gBAAlBD,EAAiC,CAEjC,MAAME,EAAmBD,EAAME,WAAaN,EAA6BC,EACnEM,EAASC,EAAKH,GAAkBI,KAAKL,GAG3C,OAFAG,EAAOG,aAAeN,EAAMO,SAC5BJ,EAAOK,WAAa,UACbL,CACX,CAGA,MAAO,CACHK,WAAY,SACZC,KAAMT,EAAMS"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../src/components/ThreeDS2/components/utils.ts"],"sourcesContent":["import { CHALLENGE_WINDOW_SIZES, DEFAULT_CHALLENGE_WINDOW_SIZE } from '../constants';\nimport { getOrigin } from '../../../utils/getOrigin';\nimport base64 from '../../../utils/base64';\nimport { ChallengeData, ThreeDS2Token, FingerPrintData, ResultObject, FingerprintResolveData, ChallengeResolveData } from '../types';\nimport { pick } from '../../../utils/commonUtils';\nimport { DecodeObject } from '../../../types/global-types';\nimport { ErrorObject } from '../../../core/Errors/types';\n\n/**\n * Check if we have been passed an ErrorObject because either base64 decoding or JSON.parse failed\n * @param obj -\n */\nexport const isErrorObject = (obj: ErrorObject | ThreeDS2Token): boolean => {\n return 'success' in obj && !obj.success;\n};\n\nexport const decodeAndParseToken = (token: string): ThreeDS2Token | ErrorObject => {\n const decodedToken: DecodeObject = base64.decode(token);\n if (decodedToken.success) {\n try {\n return JSON.parse(decodedToken.data) as ThreeDS2Token;\n } catch (e) {\n return {\n success: false,\n error: 'Could not JSON parse token'\n };\n }\n }\n\n // base64.decode failed - object will contain error msg: 'not base64' or 'malformed URI sequence'\n return decodedToken as ErrorObject;\n};\n\n/**\n * Performs JSON.stringify on passed object & and base64 encodes result\n * @param obj -\n * @returns encoded result\n */\nexport const encodeObject = obj => {\n if (!obj || !Object.keys(obj).length) {\n throw new Error('No (populated) data object to encode');\n }\n return base64.encode(JSON.stringify(obj));\n};\n\n/**\n * Accepts a size string for the challenge window & returns it if it is valid else returns a default value\n * @param sizeStr - the size string to check the validity of\n * @returns a valid size string\n */\nexport const validateChallengeWindowSize = (sizeStr: string): string => {\n const sizeString = sizeStr.length === 1 ? `0${sizeStr}` : sizeStr;\n const hasSize = Object.prototype.hasOwnProperty.call(CHALLENGE_WINDOW_SIZES, sizeString);\n return hasSize ? sizeString : DEFAULT_CHALLENGE_WINDOW_SIZE;\n};\n\n/**\n * Accepts a size string for the challenge window & returns the corresponding array of w/h values\n * @param sizeStr -\n */\nexport const getChallengeWindowSize = (sizeStr: string): string[] => CHALLENGE_WINDOW_SIZES[validateChallengeWindowSize(sizeStr)];\n\n/**\n * prepareChallengeData\n *\n * Requires an object containing the challenge parameters:\n * @param token - challengeToken string received from /submitThreeDS2Fingerprint, /details or /payments call: contains acsTransID, acsURL, messageVersion,\n * threeDSNotificationURL and threeDSServerTransID\n * @param size - one of five possible challenge window sizes\n */\nexport const prepareChallengeData = ({ token, size }): ChallengeData | ErrorObject => {\n const decodedChallengeToken = decodeAndParseToken(token);\n\n if (isErrorObject(decodedChallengeToken)) {\n return decodedChallengeToken as ErrorObject;\n }\n\n const { acsTransID, acsURL, messageVersion, threeDSNotificationURL, threeDSServerTransID } = decodedChallengeToken as ThreeDS2Token;\n const notificationURLOrigin = getOrigin(threeDSNotificationURL);\n\n return {\n acsURL,\n cReqData: {\n acsTransID,\n messageVersion,\n threeDSServerTransID,\n messageType: 'CReq',\n challengeWindowSize: validateChallengeWindowSize(size)\n },\n iframeSizeArr: getChallengeWindowSize(size),\n postMessageDomain: notificationURLOrigin\n } as ChallengeData;\n};\n\n/**\n * prepareFingerPrintData\n *\n * Requires an object containing the fingerprint parameters:\n * @param token - fingerprintToken string received from /payments call: contains threeDSMethodNotificationURL, threeDSMethodUrl and\n * threeDSServerTransID\n * @param notificationURL - the URL that the final notification is expected to be postMessaged from.\n *\n * NOTE: we don't expect merchants to alter the default by passing in a notificationURL of their own via props;\n * and if 3DS2 is being done via createFromAction or handleAction we won't accept it.\n * But if the merchant is using checkout.create('threeDS2DeviceFingerprint') we still support the fact that they might want to set their own\n * notificationURL (aka threeDSMethodNotificationURL)\n */\nexport const prepareFingerPrintData = ({ token, notificationURL }): FingerPrintData | ErrorObject => {\n const decodedFingerPrintToken = decodeAndParseToken(token);\n\n if (isErrorObject(decodedFingerPrintToken)) {\n return decodedFingerPrintToken as ErrorObject;\n }\n\n const { threeDSMethodNotificationURL, threeDSMethodUrl: threeDSMethodURL, threeDSServerTransID } = decodedFingerPrintToken as ThreeDS2Token;\n const receivedNotificationURL = notificationURL || threeDSMethodNotificationURL;\n const notificationURLOrigin = getOrigin(receivedNotificationURL);\n\n return {\n threeDSServerTransID,\n threeDSMethodURL,\n threeDSMethodNotificationURL: receivedNotificationURL,\n postMessageDomain: notificationURLOrigin\n } as FingerPrintData;\n};\n\nexport const createFingerprintResolveData = (dataKey: string, resultObj: ResultObject, paymentData: string): FingerprintResolveData => ({\n data: {\n [dataKey]: encodeObject({ threeDSCompInd: resultObj.threeDSCompInd }),\n paymentData\n }\n});\n\n// Old 3DS2 flow\nexport const createOldFingerprintResolveData = (dataKey: string, resultObj: ResultObject, paymentData: string): any => ({\n data: {\n details: { 'threeds2.fingerprint': encodeObject(resultObj) },\n paymentData\n }\n});\n\nexport const createChallengeResolveData = (dataKey: string, transStatus: string, authorisationToken: string): ChallengeResolveData => ({\n data: {\n details: { [dataKey]: encodeObject({ transStatus, authorisationToken }) }\n }\n});\n\n// Needed for old 3DS2 flow & threeds2InMDFlow\nexport const createOldChallengeResolveData = (dataKey: string, transStatus: string, authorisationToken: string): any => ({\n data: {\n details: { 'threeds2.challengeResult': encodeObject({ transStatus }) },\n paymentData: authorisationToken\n }\n});\n\n/**\n *\n * Takes a string and encodes it as a base64url string\n * (https://en.wikipedia.org/wiki/Base64#URL_applications)\n * (See also https://tools.ietf.org/html/rfc7515)\n *\n * @example\n * ```\n * const jsonStr = JSON.stringify( {name:'john', surname:'smith'} );\n * const base64url = encodeBase64URL(jsonStr);\n * ```\n *\n * @param dataStr - data, as a string, to be encoded\n *\n * @returns base64URL - a base64url encoded string\n */\nexport const encodeBase64URL = (dataStr: string): string => {\n const base64Data = window.btoa(dataStr);\n let base64url = base64Data.split('=')[0]; // Remove any trailing '='s\n\n base64url = base64url.replace(/\\+/g, '-'); // 62nd char of encoding\n base64url = base64url.replace(/\\//g, '_'); // 63rd char of encoding\n\n return base64url;\n};\n\nconst fingerprintFlowPropsDropin = ['elementRef'];\n\n/**\n * Must contain all props needed for the challenge stage since, in the new 3DS2 flow, the fingerprint component will be the \"component\" reference\n * if the /submitThreeDS2Fingerprint response dictates we \"handleAction\" to create a challenge\n */\nconst fingerprintFlowProps = ['createFromAction', 'onAdditionalDetails'];\n\n/**\n * Add props specifically needed for the type of 3DS2 flow: fingerprint or challenge\n *\n * @param actionSubtype - 3DS2 flow type: fingerprint or challenge\n * @param props - object from which to extract particular properties\n */\nexport const get3DS2FlowProps = (actionSubtype, props) => {\n if (actionSubtype === 'fingerprint') {\n // elementRef exists when the fingerprint component is created from the Dropin\n const fingerprintProps = props.elementRef ? fingerprintFlowPropsDropin : fingerprintFlowProps;\n const rtnObj = pick(fingerprintProps).from(props);\n rtnObj.showSpinner = !props.isDropin;\n rtnObj.statusType = 'loading';\n return rtnObj;\n }\n\n // Challenge\n return {\n statusType: 'custom',\n i18n: props.i18n,\n elementRef: props.elementRef\n };\n};\n"],"names":["isErrorObject","obj","success","decodeAndParseToken","token","decodedToken","base64","decode","JSON","parse","data","e","error","encodeObject","Object","keys","length","Error","encode","stringify","validateChallengeWindowSize","sizeStr","sizeString","prototype","hasOwnProperty","call","CHALLENGE_WINDOW_SIZES","DEFAULT_CHALLENGE_WINDOW_SIZE","getChallengeWindowSize","prepareChallengeData","size","decodedChallengeToken","acsTransID","acsURL","messageVersion","threeDSNotificationURL","threeDSServerTransID","notificationURLOrigin","getOrigin","cReqData","messageType","challengeWindowSize","iframeSizeArr","postMessageDomain","prepareFingerPrintData","notificationURL","decodedFingerPrintToken","threeDSMethodNotificationURL","threeDSMethodUrl","threeDSMethodURL","receivedNotificationURL","createFingerprintResolveData","dataKey","resultObj","paymentData","threeDSCompInd","createOldFingerprintResolveData","details","createChallengeResolveData","transStatus","authorisationToken","createOldChallengeResolveData","encodeBase64URL","dataStr","base64url","window","btoa","split","replace","fingerprintFlowPropsDropin","fingerprintFlowProps","get3DS2FlowProps","actionSubtype","props","fingerprintProps","elementRef","rtnObj","pick","from","showSpinner","isDropin","statusType","i18n"],"mappings":"iPAYO,MAAMA,EAAiBC,GACnB,YAAaA,IAAQA,EAAIC,QAGvBC,EAAuBC,IAChC,MAAMC,EAA6BC,EAAOC,OAAOH,GACjD,GAAIC,EAAaH,QACb,IACI,OAAOM,KAAKC,MAAMJ,EAAaK,KACnC,CAAE,MAAOC,GACL,MAAO,CACHT,SAAS,EACTU,MAAO,6BAEf,CAIJ,OAAOP,GAQEQ,EAAeZ,IACxB,IAAKA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ACT,EAAiBO,EAAqBC,MAChFlD,KAAM,CACF+C,QAAS,CAAE,2BAA4B5C,EAAa,CAAE8C,iBACtDL,YAAaM,KAoBRE,EAAmBC,IAE5B,IAAIC,EADeC,OAAOC,KAAKH,GACJI,MAAM,KAAK,GAKtC,OAHAH,EAAYA,EAAUI,QAAQ,MAAO,KACrCJ,EAAYA,EAAUI,QAAQ,MAAO,KAE9BJ,GAGLK,EAA6B,CAAC,cAM9BC,EAAuB,CAAC,mBAAoB,uBAQrCC,EAAmB,CAACC,EAAeC,KAC5C,GAAsB,gBAAlBD,EAAiC,CAEjC,MAAME,EAAmBD,EAAME,WAAaN,EAA6BC,EACnEM,EAASC,EAAKH,GAAkBI,KAAKL,GAG3C,OAFAG,EAAOG,aAAeN,EAAMO,SAC5BJ,EAAOK,WAAa,UACbL,CACX,CAGA,MAAO,CACHK,WAAY,SACZC,KAAMT,EAAMS,KACZP,WAAYF,EAAME"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../../external/preact/dist/preact.js";import{UIElement as e}from"../../internal/UIElement/UIElement.js";import{CoreProvider as o}from"../../../core/Context/CoreProvider.js";import"../../../external/preact/hooks/dist/hooks.js";import"../../../core/Errors/AdyenCheckoutError.js";import"../../../core/Errors/SRPanelContext.js";import"../../internal/Button/Button.js";import r from"../../internal/QRLoader/QRLoader.js";import"../../internal/QRLoader/QRLoaderDetailsProvider.js";import
|
|
1
|
+
import{createElement as t}from"../../../external/preact/dist/preact.js";import{UIElement as e}from"../../internal/UIElement/UIElement.js";import{CoreProvider as o}from"../../../core/Context/CoreProvider.js";import"../../../external/preact/hooks/dist/hooks.js";import"../../../core/Errors/AdyenCheckoutError.js";import"../../../core/Errors/SRPanelContext.js";import"../../internal/Button/Button.js";import r from"../../internal/QRLoader/QRLoader.js";import"../../internal/QRLoader/QRLoaderDetailsProvider.js";import s from"../../internal/RedirectButton/RedirectButton.js";import n from"../../../core/Errors/SRPanelProvider.js";class i extends e{formatData(){return{paymentMethod:{type:this.type,...this.state.data}}}get isValid(){return!0}renderQRCode(){return t(o,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(n,{srPanel:this.props.modules.srPanel},t(r,{ref:t=>{this.componentRef=t},...this.props,delay:this.props.delay,countdownTime:this.props.countdownTime,instructions:this.props.instructions,type:this.constructor.type,brandLogo:this.props.brandLogo||this.icon,onComplete:this.onComplete,onActionHandled:this.onActionHandled,brandName:this.displayName,onSubmitAnalytics:this.submitAnalytics})))}render(){return this.props.paymentData?this.renderQRCode():this.props.showPayButton?t(o,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(s,{showPayButton:this.props.showPayButton,name:this.displayName,onSubmit:this.submit,payButton:this.payButton,ref:t=>{this.componentRef=t}})):null}}var a,p,l;l={qrCodeImage:"",amount:null,paymentData:null,onError:()=>{}},(p="defaultProps")in(a=i)?Object.defineProperty(a,p,{value:l,enumerable:!0,configurable:!0,writable:!0}):a[p]=l;export{i as default};
|
|
2
2
|
//# sourceMappingURL=QRLoaderContainer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QRLoaderContainer.js","sources":["../../../../../src/components/helpers/QRLoaderContainer/QRLoaderContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport QRLoader from '../../internal/QRLoader';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport RedirectButton from '../../internal/RedirectButton';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { QRLoaderConfiguration } from './types';\n\nclass QRLoaderContainer<T extends QRLoaderConfiguration = QRLoaderConfiguration> extends UIElement<T> {\n // Using the generic here allow to fully extend the QRLoaderContainer (including it's props)\n protected static defaultProps = {\n qrCodeImage: '',\n amount: null,\n paymentData: null,\n onError: () => {}
|
|
1
|
+
{"version":3,"file":"QRLoaderContainer.js","sources":["../../../../../src/components/helpers/QRLoaderContainer/QRLoaderContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport QRLoader from '../../internal/QRLoader';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport RedirectButton from '../../internal/RedirectButton';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { QRLoaderConfiguration } from './types';\n\nclass QRLoaderContainer<T extends QRLoaderConfiguration = QRLoaderConfiguration> extends UIElement<T> {\n // Using the generic here allow to fully extend the QRLoaderContainer (including it's props)\n protected static defaultProps = {\n qrCodeImage: '',\n amount: null,\n paymentData: null,\n onError: () => {}\n };\n\n formatData() {\n return {\n paymentMethod: {\n type: this.type,\n ...this.state.data\n }\n };\n }\n\n get isValid() {\n return true;\n }\n\n // Makes possible to extend the final QR code step\n public renderQRCode() {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <QRLoader\n ref={ref => {\n this.componentRef = ref;\n }}\n {...this.props}\n delay={this.props.delay}\n countdownTime={this.props.countdownTime}\n instructions={this.props.instructions}\n type={this.constructor['type']}\n brandLogo={this.props.brandLogo || this.icon}\n onComplete={this.onComplete}\n onActionHandled={this.onActionHandled}\n brandName={this.displayName}\n onSubmitAnalytics={this.submitAnalytics}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n\n render() {\n if (this.props.paymentData) {\n return this.renderQRCode();\n }\n\n if (this.props.showPayButton) {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <RedirectButton\n showPayButton={this.props.showPayButton}\n name={this.displayName}\n onSubmit={this.submit}\n payButton={this.payButton}\n ref={ref => {\n this.componentRef = ref;\n }}\n />\n </CoreProvider>\n );\n }\n\n return null;\n }\n}\n\nexport default QRLoaderContainer;\n"],"names":["QRLoaderContainer","UIElement","formatData","paymentMethod","type","this","state","data","isValid","renderQRCode","h","CoreProvider","i18n","props","loadingContext","resources","SRPanelProvider","srPanel","modules","QRLoader","ref","componentRef","delay","countdownTime","instructions","constructor","brandLogo","icon","onComplete","onActionHandled","brandName","displayName","onSubmitAnalytics","submitAnalytics","render","paymentData","showPayButton","RedirectButton","name","onSubmit","submit","payButton","qrCodeImage","amount","onError","defaultProps"],"mappings":"knBAQA,MAAMA,UAAmFC,EASrFC,UAAAA,GACI,MAAO,CACHC,cAAe,CACXC,KAAMC,KAAKD,QACRC,KAAKC,MAAMC,MAG1B,CAEA,WAAIC,GACA,OAAO,CACX,CAGOC,YAAAA,GACH,OACIC,EAACC,EAAAA,CAAaC,KAAMP,KAAKQ,MAAMD,KAAME,eAAgBT,KAAKQ,MAAMC,eAAgBC,UAAWV,KAAKU,WAC5FL,EAACM,EAAAA,CAAgBC,QAASZ,KAAKQ,MAAMK,QAAQD,SACzCP,EAACS,EAAAA,CACGC,IAAKA,IACDf,KAAKgB,aAAeD,MAEpBf,KAAKQ,MACTS,MAAOjB,KAAKQ,MAAMS,MAClBC,cAAelB,KAAKQ,MAAMU,cAC1BC,aAAcnB,KAAKQ,MAAMW,aACzBpB,KAAMC,KAAKoB,YAAY,KACvBC,UAAWrB,KAAKQ,MAAMa,WAAarB,KAAKsB,KACxCC,WAAYvB,KAAKuB,WACjBC,gBAAiBxB,KAAKwB,gBACtBC,UAAWzB,KAAK0B,YAChBC,kBAAmB3B,KAAK4B,mBAK5C,CAEAC,MAAAA,GACI,OAAI7B,KAAKQ,MAAMsB,YACJ9B,KAAKI,eAGZJ,KAAKQ,MAAMuB,cAEP1B,EAACC,EAAAA,CAAaC,KAAMP,KAAKQ,MAAMD,KAAME,eAAgBT,KAAKQ,MAAMC,eAAgBC,UAAWV,KAAKU,WAC5FL,EAAC2B,EAAAA,CACGD,cAAe/B,KAAKQ,MAAMuB,cAC1BE,KAAMjC,KAAK0B,YACXQ,SAAUlC,KAAKmC,OACfC,UAAWpC,KAAKoC,UAChBrB,IAAKA,IACDf,KAAKgB,aAAeD,MAOjC,IACX,cAnEgC,CAC5BsB,YAAa,GACbC,OAAQ,KACRR,YAAa,KACbS,QAAS,WAJIC,oBAFf7C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e,Fragment as t}from"../../../external/preact/dist/preact.js";import{useRef as s,useMemo as o,useState as r,useCallback as a,useEffect as n}from"../../../external/preact/hooks/dist/hooks.js";import i from"../FormFields/Fieldset/Fieldset.js";import l from"./components/ReadOnlyAddress.js";import{getAddressValidationRules as d}from"./validate.js";import{countrySpecificFormatters as c,addressFormatters as u}from"./validate.formats.js";import m from"./components/FieldContainer.js";import p from"../../../utils/useForm/useForm.js";import f from"./Specifications.js";import{ADDRESS_SCHEMA as y,FALLBACK_VALUE as F}from"./constants.js";import{getMaxLengthByFieldAndCountry as h}from"../../../utils/validator-utils.js";import{useCoreContext as C}from"../../../core/Context/CoreProvider.js";import g from"./components/AddressSearch.js";function A(A){const{i18n:v}=C(),{label:b="",requiredFields:j,visibility:x,iOSFocusedField:S=null,showContextualElement:k}=A,M=s({});Object.keys(M.current).length||A.setComponentRef?.(M.current);const O=o(()=>new f(A.specifications),[A.specifications]),D=O.getAddressSchemaForCountryFlat(A.countryCode).filter(e=>j.includes(e)),[w,B]=r(!1),[E,N]=r(!1),[P,L]=r(""),R=!!A.onAddressLookup,[V,q]=r(!1),H=!A.onAddressLookup||(w||E),{data:T,errors:_,valid:I,isValid:$,handleChangeFor:z,triggerValidation:G,setData:J,mergeData:K}=p({schema:D,defaultData:A.data,rules:{...d(O),...A.validationRules},formatters:u}),Q=a(e=>{const t=y.reduce((t,s)=>{const o=e[s];return null!=o&&(t[s]=String(o)),t},{});K(t),q(!0),G(),B(!0)},[B,G,J]),U=a(()=>{N(!0)},[]);M.current.showValidation=()=>{G(),L(!R||H||$?"":v.get("address.errors.incomplete"))};const W=D.filter(e=>!S||e===S);if(n(()=>{if(V)return void q(!1);const e=O.countryHasDataset(T.country)?"":F,t={...T,stateOrProvince:e};j.forEach(e=>{z(e,"input")(t[e]??"")}),t.postalCode&&z("postalCode","blur")(T.postalCode)},[T.country]),n(()=>{const e=j.includes("stateOrProvince"),t=T.country&&O.countryHasDataset(T.country),s=e&&t,o=T.stateOrProvince||(s?"":F);z("stateOrProvince","input")(o)},[]),n(()=>{const e=O.getOptionalFieldsForCountry(T.country),t=y.reduce((t,s)=>{const o=e.includes(s),r=j.includes(s),a=T[s],n=A.data[s],i=o&&!a||!r?r||a||!n?F:n:a;return i?.length&&(t[s]=i),t},{});A.onChange({data:t,valid:I,errors:_,isValid:$})},[T,I,_,$]),"hidden"===x)return null;if("readOnly"===x)return e(l,{data:T,label:b});const X=(t,{classNameModifiers:s=[]})=>j.includes(t)?e(m,{key:t,allowedCountries:A.allowedCountries,classNameModifiers:[...s,t],data:T,errors:_,valid:I,fieldName:t,onInput:z(t,"input"),onBlur:z(t,"blur"),onDropdownChange:z(t,"blur"),specifications:O,maxLength:h(c,t,T.country),trimOnBlur:!0,disabled:!W.includes(t),onFieldFocusAnalytics:A.onFieldFocusAnalytics,onFieldBlurAnalytics:A.onFieldBlurAnalytics}):null,Y=O.getAddressSchemaForCountry(T.country);return e(t,null,e(i,{classNameModifiers:[b
|
|
1
|
+
import{createElement as e,Fragment as t}from"../../../external/preact/dist/preact.js";import{useRef as s,useMemo as o,useState as r,useCallback as a,useEffect as n}from"../../../external/preact/hooks/dist/hooks.js";import i from"../FormFields/Fieldset/Fieldset.js";import l from"./components/ReadOnlyAddress.js";import{getAddressValidationRules as d}from"./validate.js";import{countrySpecificFormatters as c,addressFormatters as u}from"./validate.formats.js";import m from"./components/FieldContainer.js";import p from"../../../utils/useForm/useForm.js";import f from"./Specifications.js";import{ADDRESS_SCHEMA as y,FALLBACK_VALUE as F}from"./constants.js";import{getMaxLengthByFieldAndCountry as h}from"../../../utils/validator-utils.js";import{useCoreContext as C}from"../../../core/Context/CoreProvider.js";import g from"./components/AddressSearch.js";function A(A){const{i18n:v}=C(),{label:b="",requiredFields:j,visibility:x,iOSFocusedField:S=null,showContextualElement:k}=A,M=s({});Object.keys(M.current).length||A.setComponentRef?.(M.current);const O=o(()=>new f(A.specifications),[A.specifications]),D=O.getAddressSchemaForCountryFlat(A.countryCode).filter(e=>j.includes(e)),[w,B]=r(!1),[E,N]=r(!1),[P,L]=r(""),R=!!A.onAddressLookup,[V,q]=r(!1),H=!A.onAddressLookup||(w||E),{data:T,errors:_,valid:I,isValid:$,handleChangeFor:z,triggerValidation:G,setData:J,mergeData:K}=p({schema:D,defaultData:A.data,rules:{...d(O),...A.validationRules},formatters:u}),Q=a(e=>{const t=y.reduce((t,s)=>{const o=e[s];return null!=o&&(t[s]=String(o)),t},{});K(t),q(!0),G(),B(!0)},[B,G,J]),U=a(()=>{N(!0)},[]);M.current.showValidation=()=>{G(),L(!R||H||$?"":v.get("address.errors.incomplete"))};const W=D.filter(e=>!S||e===S);if(n(()=>{if(V)return void q(!1);const e=O.countryHasDataset(T.country)?"":F,t={...T,stateOrProvince:e};j.forEach(e=>{z(e,"input")(t[e]??"")}),t.postalCode&&z("postalCode","blur")(T.postalCode)},[T.country]),n(()=>{const e=j.includes("stateOrProvince"),t=T.country&&O.countryHasDataset(T.country),s=e&&t,o=T.stateOrProvince||(s?"":F);z("stateOrProvince","input")(o)},[]),n(()=>{const e=O.getOptionalFieldsForCountry(T.country),t=y.reduce((t,s)=>{const o=e.includes(s),r=j.includes(s),a=T[s],n=A.data[s],i=o&&!a||!r?r||a||!n?F:n:a;return i?.length&&(t[s]=i),t},{});A.onChange({data:t,valid:I,errors:_,isValid:$})},[T,I,_,$]),"hidden"===x)return null;if("readOnly"===x)return e(l,{data:T,label:b});const X=(t,{classNameModifiers:s=[]})=>j.includes(t)?e(m,{key:t,allowedCountries:A.allowedCountries,classNameModifiers:[...s,t],data:T,errors:_,valid:I,fieldName:t,onInput:z(t,"input"),onBlur:z(t,"blur"),onDropdownChange:z(t,"blur"),specifications:O,maxLength:h(c,t,T.country),trimOnBlur:!0,disabled:!W.includes(t),onFieldFocusAnalytics:A.onFieldFocusAnalytics,onFieldBlurAnalytics:A.onFieldBlurAnalytics}):null,Y=O.getAddressSchemaForCountry(T.country);return e(t,null,e(i,{classNameModifiers:[b,"address"],label:b},R&&e(g,{onAddressLookup:A.onAddressLookup,onAddressSelected:A.onAddressSelected,onSelect:Q,onManualAddress:U,externalErrorMessage:P,hideManualButton:H,showContextualElement:k,contextualText:v.get("address.search.contextualText"),addressSearchDebounceMs:A.addressSearchDebounceMs}),H&&e(t,null,Y.map(t=>t instanceof Array?e("div",{className:"adyen-checkout__field-group"},t.map(([e,t])=>X(e,{classNameModifiers:[`col-${t}`]}))):X(t,{})))))}A.defaultProps={countryCode:null,validationRules:null,data:{},onChange:()=>{},visibility:"editable",requiredFields:y,specifications:{},onFieldFocusAnalytics:()=>{},onFieldBlurAnalytics:()=>{}};export{A as default};
|
|
2
2
|
//# sourceMappingURL=Address.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Address.js","sources":["../../../../../src/components/internal/Address/Address.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';\nimport Fieldset from '../FormFields/Fieldset';\nimport ReadOnlyAddress from './components/ReadOnlyAddress';\nimport { getAddressValidationRules } from './validate';\nimport { addressFormatters, countrySpecificFormatters } from './validate.formats';\nimport { AddressProps } from './types';\nimport { AddressData } from '../../../types/global-types';\nimport FieldContainer from './components/FieldContainer';\nimport useForm from '../../../utils/useForm';\nimport Specifications from './Specifications';\nimport { ADDRESS_SCHEMA, FALLBACK_VALUE } from './constants';\nimport { getMaxLengthByFieldAndCountry } from '../../../utils/validator-utils';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport AddressSearch from './components/AddressSearch';\nimport { ComponentMethodsRef } from '../UIElement/types';\n\nexport default function Address(props: AddressProps) {\n const { i18n } = useCoreContext();\n\n const { label = '', requiredFields, visibility, iOSFocusedField = null, showContextualElement } = props;\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const addressRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(addressRef.current).length) {\n props.setComponentRef?.(addressRef.current);\n }\n\n const specifications = useMemo(() => new Specifications(props.specifications), [props.specifications]);\n\n const requiredFieldsSchema = specifications.getAddressSchemaForCountryFlat(props.countryCode).filter(field => requiredFields.includes(field));\n\n const [hasSelectedAddress, setHasSelectedAddress] = useState(false);\n\n const [useManualAddress, setUseManualAddress] = useState(false);\n\n const [searchErrorMessage, setSearchErrorMessage] = useState('');\n\n const showAddressSearch = !!props.onAddressLookup;\n\n const [ignoreCountryChange, setIgnoreCountryChange] = useState(false);\n\n const showAddressFields = props.onAddressLookup ? hasSelectedAddress || useManualAddress : true;\n\n const { data, errors, valid, isValid, handleChangeFor, triggerValidation, setData, mergeData } = useForm<AddressData>({\n schema: requiredFieldsSchema,\n defaultData: props.data,\n // Ensure any passed validation rules are merged with the default ones\n rules: { ...getAddressValidationRules(specifications), ...props.validationRules },\n formatters: addressFormatters\n });\n\n const setSearchData = useCallback(\n (selectedAddress: AddressData) => {\n const propsKeysToProcess = ADDRESS_SCHEMA;\n const newStateData = propsKeysToProcess.reduce((acc: AddressData, propKey) => {\n // Make sure the data provided by the merchant is always strings\n const providedValue = selectedAddress[propKey];\n if (providedValue !== null && providedValue !== undefined) {\n // Cast everything to string\n acc[propKey] = String(providedValue);\n }\n return acc;\n }, {});\n mergeData(newStateData);\n setIgnoreCountryChange(true);\n triggerValidation();\n setHasSelectedAddress(true);\n },\n [setHasSelectedAddress, triggerValidation, setData]\n );\n\n const onManualAddress = useCallback(() => {\n setUseManualAddress(true);\n }, []);\n\n // Expose method expected by (parent) Address.tsx\n addressRef.current.showValidation = () => {\n triggerValidation();\n if (showAddressSearch && !showAddressFields && !isValid) {\n setSearchErrorMessage(i18n.get('address.errors.incomplete'));\n } else {\n setSearchErrorMessage('');\n }\n };\n\n /**\n * For iOS: iOSFocusedField is the name of the element calling for other elements to be disabled\n * - so if it is set (meaning we are in iOS *and* an input has been focussed) only enable the field that corresponds to this element\n */\n const enabledFields: string[] = requiredFieldsSchema.filter(item => {\n return !iOSFocusedField ? true : item === iOSFocusedField;\n });\n\n /**\n * Effect that:\n * - Resets validation for all fields by triggering handleChangeFor(fieldName, 'input')\n * - Applies validation on postalCode field in case it has any value\n */\n useEffect((): void => {\n // if the country was set via setSearchData we don't want to trigger this\n if (ignoreCountryChange) {\n setIgnoreCountryChange(false);\n return;\n }\n\n const stateOrProvince = specifications.countryHasDataset(data.country) ? '' : FALLBACK_VALUE;\n const newData = { ...data, stateOrProvince };\n\n requiredFields.forEach(fieldName => {\n handleChangeFor(fieldName, 'input')(newData[fieldName] ?? '');\n });\n\n if (newData.postalCode) {\n handleChangeFor('postalCode', 'blur')(data.postalCode);\n }\n }, [data.country]);\n\n /**\n * Set the value of 'stateOrProvince' during the initial render if\n * property is provided during the creation of the payment method\n */\n useEffect((): void => {\n const stateFieldIsRequired = requiredFields.includes('stateOrProvince');\n const countryHasStatesDataset = data.country && specifications.countryHasDataset(data.country);\n const addressShouldHaveState = stateFieldIsRequired && countryHasStatesDataset;\n const stateOrProvince = data.stateOrProvince || (addressShouldHaveState ? '' : FALLBACK_VALUE);\n\n handleChangeFor('stateOrProvince', 'input')(stateOrProvince);\n }, []);\n\n useEffect((): void => {\n const optionalFields = specifications.getOptionalFieldsForCountry(data.country);\n const processedData = ADDRESS_SCHEMA.reduce((acc, cur) => {\n const isOptional = optionalFields.includes(cur);\n const isRequired = requiredFields.includes(cur);\n const newValue = data[cur];\n const initialValue = props.data[cur];\n // recover default data values which are not requiredFields, or prefill with 'N/A'\n const fallbackValue = !isRequired && !newValue && !!initialValue ? initialValue : FALLBACK_VALUE;\n const value = (isOptional && !newValue) || !isRequired ? fallbackValue : newValue;\n if (value?.length) acc[cur] = value;\n return acc;\n }, {});\n\n props.onChange({ data: processedData, valid, errors, isValid });\n }, [data, valid, errors, isValid]);\n\n if (visibility === 'hidden') return null;\n if (visibility === 'readOnly') return <ReadOnlyAddress data={data} label={label} />;\n\n const getComponent = (fieldName: string, { classNameModifiers = [] }) => {\n if (!requiredFields.includes(fieldName)) return null;\n\n return (\n <FieldContainer\n key={fieldName}\n allowedCountries={props.allowedCountries}\n classNameModifiers={[...classNameModifiers, fieldName]}\n data={data}\n errors={errors}\n valid={valid}\n fieldName={fieldName}\n onInput={handleChangeFor(fieldName, 'input')}\n onBlur={handleChangeFor(fieldName, 'blur')}\n onDropdownChange={handleChangeFor(fieldName, 'blur')}\n specifications={specifications}\n maxLength={getMaxLengthByFieldAndCountry(countrySpecificFormatters, fieldName, data.country, true)}\n trimOnBlur={true}\n disabled={!enabledFields.includes(fieldName)}\n onFieldFocusAnalytics={props.onFieldFocusAnalytics}\n onFieldBlurAnalytics={props.onFieldBlurAnalytics}\n />\n );\n };\n\n const getWrapper = group => (\n <div className=\"adyen-checkout__field-group\">\n {group.map(([field, size]) => getComponent(field, { classNameModifiers: [`col-${size}`] }))}\n </div>\n );\n\n const addressSchema = specifications.getAddressSchemaForCountry(data.country);\n\n return (\n <Fragment>\n <Fieldset classNameModifiers={[label || 'address']} label={label}>\n {showAddressSearch && (\n <AddressSearch\n onAddressLookup={props.onAddressLookup}\n onAddressSelected={props.onAddressSelected}\n onSelect={setSearchData}\n onManualAddress={onManualAddress}\n externalErrorMessage={searchErrorMessage}\n hideManualButton={showAddressFields}\n showContextualElement={showContextualElement}\n contextualText={i18n.get('address.search.contextualText')}\n addressSearchDebounceMs={props.addressSearchDebounceMs}\n />\n )}\n {showAddressFields && (\n <Fragment>{addressSchema.map(field => (field instanceof Array ? getWrapper(field) : getComponent(field, {})))}</Fragment>\n )}\n </Fieldset>\n </Fragment>\n );\n}\n\nAddress.defaultProps = {\n countryCode: null,\n validationRules: null,\n data: {},\n onChange: () => {},\n visibility: 'editable',\n requiredFields: ADDRESS_SCHEMA,\n specifications: {},\n onFieldFocusAnalytics: () => {},\n onFieldBlurAnalytics: () => {}\n};\n"],"names":["Address","props","i18n","useCoreContext","label","requiredFields","visibility","iOSFocusedField","showContextualElement","addressRef","useRef","Object","keys","current","length","setComponentRef","specifications","useMemo","Specifications","requiredFieldsSchema","getAddressSchemaForCountryFlat","countryCode","filter","field","includes","hasSelectedAddress","setHasSelectedAddress","useState","useManualAddress","setUseManualAddress","searchErrorMessage","setSearchErrorMessage","showAddressSearch","onAddressLookup","ignoreCountryChange","setIgnoreCountryChange","showAddressFields","data","errors","valid","isValid","handleChangeFor","triggerValidation","setData","mergeData","useForm","schema","defaultData","rules","getAddressValidationRules","validationRules","formatters","addressFormatters","setSearchData","useCallback","selectedAddress","newStateData","ADDRESS_SCHEMA","reduce","acc","propKey","providedValue","String","onManualAddress","showValidation","get","enabledFields","item","useEffect","stateOrProvince","countryHasDataset","country","FALLBACK_VALUE","newData","forEach","fieldName","postalCode","stateFieldIsRequired","countryHasStatesDataset","addressShouldHaveState","optionalFields","getOptionalFieldsForCountry","processedData","cur","isOptional","isRequired","newValue","initialValue","value","onChange","h","ReadOnlyAddress","getComponent","classNameModifiers","FieldContainer","key","allowedCountries","onInput","onBlur","onDropdownChange","maxLength","getMaxLengthByFieldAndCountry","countrySpecificFormatters","trimOnBlur","disabled","onFieldFocusAnalytics","onFieldBlurAnalytics","addressSchema","getAddressSchemaForCountry","Fragment","Fieldset","AddressSearch","onAddressSelected","onSelect","externalErrorMessage","hideManualButton","contextualText","addressSearchDebounceMs","map","Array","div","className","size","defaultProps"],"mappings":"u1BAiBe,SAASA,EAAQC,GAC5B,MAAMC,KAAEA,GAASC,KAEXC,MAAEA,EAAQ,GAAEC,eAAEA,EAAcC,WAAEA,EAAUC,gBAAEA,EAAkB,KAAIC,sBAAEA,GAA0BP,EAG5FQ,EAAaC,EAA4B,IAE1CC,OAAOC,KAAKH,EAAWI,SAASC,QACjCb,EAAMc,kBAAkBN,EAAWI,SAGvC,MAAMG,EAAiBC,EAAQ,IAAM,IAAIC,EAAejB,EAAMe,gBAAiB,CAACf,EAAMe,iBAEhFG,EAAuBH,EAAeI,+BAA+BnB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pFgC,YAAY,EACZC,UAAWtC,EAAc1C,SAASmD,GAClC8B,sBAAuBxG,EAAMwG,sBAC7BC,qBAAsBzG,EAAMyG,uBAnBY,KA8B9CC,EAAgB3F,EAAe4F,2BAA2BvE,EAAKkC,SAErE,OACImB,EAACmB,OACGnB,EAACoB,EAAAA,CAASjB,mBAAoB,CAACzF,GAAS,WAAYA,MAAOA,GACtD4B,GACG0D,EAACqB,EAAAA,CACG9E,gBAAiBhC,EAAMgC,gBACvB+E,kBAAmB/G,EAAM+G,kBACzBC,SAAU5D,EACVU,gBAAiBA,EACjBmD,qBAAsBpF,EACtBqF,iBAAkB/E,EAClB5B,sBAAuBA,EACvB4G,eAAgBlH,EAAK+D,IAAI,iCACzBoD,wBAAyBpH,EAAMoH,0BAGtCjF,GACGsD,EAACmB,EAAAA,KAAUF,EAAcW,IAAI/F,GAAUA,aAAiBgG,MAxBpE7B,EAAC8B,MAAAA,CAAIC,UAAU,+BAwBwElG,EAvB5E+F,IAAI,EAAE/F,EAAOmG,KAAU9B,EAAarE,EAAO,CAAEsE,mBAAoB,CAAC,OAAO6B,SAuBY9B,EAAarE,EAAO,CAAA,MAK5H,CAEAvB,EAAQ2H,aAAe,CACnBtG,YAAa,KACb6B,gBAAiB,KACjBb,KAAM,CAAA,EACNoD,SAAU,OACVnF,WAAY,WACZD,eAAgBoD,EAChBzC,eAAgB,CAAA,EAChByF,sBAAuB,OACvBC,qBAAsB"}
|
|
1
|
+
{"version":3,"file":"Address.js","sources":["../../../../../src/components/internal/Address/Address.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';\nimport Fieldset from '../FormFields/Fieldset';\nimport ReadOnlyAddress from './components/ReadOnlyAddress';\nimport { getAddressValidationRules } from './validate';\nimport { addressFormatters, countrySpecificFormatters } from './validate.formats';\nimport { AddressProps } from './types';\nimport { AddressData } from '../../../types/global-types';\nimport FieldContainer from './components/FieldContainer';\nimport useForm from '../../../utils/useForm';\nimport Specifications from './Specifications';\nimport { ADDRESS_SCHEMA, FALLBACK_VALUE } from './constants';\nimport { getMaxLengthByFieldAndCountry } from '../../../utils/validator-utils';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport AddressSearch from './components/AddressSearch';\nimport { ComponentMethodsRef } from '../UIElement/types';\nimport './Address.scss';\n\nexport default function Address(props: AddressProps) {\n const { i18n } = useCoreContext();\n\n const { label = '', requiredFields, visibility, iOSFocusedField = null, showContextualElement } = props;\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const addressRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(addressRef.current).length) {\n props.setComponentRef?.(addressRef.current);\n }\n\n const specifications = useMemo(() => new Specifications(props.specifications), [props.specifications]);\n\n const requiredFieldsSchema = specifications.getAddressSchemaForCountryFlat(props.countryCode).filter(field => requiredFields.includes(field));\n\n const [hasSelectedAddress, setHasSelectedAddress] = useState(false);\n\n const [useManualAddress, setUseManualAddress] = useState(false);\n\n const [searchErrorMessage, setSearchErrorMessage] = useState('');\n\n const showAddressSearch = !!props.onAddressLookup;\n\n const [ignoreCountryChange, setIgnoreCountryChange] = useState(false);\n\n const showAddressFields = props.onAddressLookup ? hasSelectedAddress || useManualAddress : true;\n\n const { data, errors, valid, isValid, handleChangeFor, triggerValidation, setData, mergeData } = useForm<AddressData>({\n schema: requiredFieldsSchema,\n defaultData: props.data,\n // Ensure any passed validation rules are merged with the default ones\n rules: { ...getAddressValidationRules(specifications), ...props.validationRules },\n formatters: addressFormatters\n });\n\n const setSearchData = useCallback(\n (selectedAddress: AddressData) => {\n const propsKeysToProcess = ADDRESS_SCHEMA;\n const newStateData = propsKeysToProcess.reduce((acc: AddressData, propKey) => {\n // Make sure the data provided by the merchant is always strings\n const providedValue = selectedAddress[propKey];\n if (providedValue !== null && providedValue !== undefined) {\n // Cast everything to string\n acc[propKey] = String(providedValue);\n }\n return acc;\n }, {});\n mergeData(newStateData);\n setIgnoreCountryChange(true);\n triggerValidation();\n setHasSelectedAddress(true);\n },\n [setHasSelectedAddress, triggerValidation, setData]\n );\n\n const onManualAddress = useCallback(() => {\n setUseManualAddress(true);\n }, []);\n\n // Expose method expected by (parent) Address.tsx\n addressRef.current.showValidation = () => {\n triggerValidation();\n if (showAddressSearch && !showAddressFields && !isValid) {\n setSearchErrorMessage(i18n.get('address.errors.incomplete'));\n } else {\n setSearchErrorMessage('');\n }\n };\n\n /**\n * For iOS: iOSFocusedField is the name of the element calling for other elements to be disabled\n * - so if it is set (meaning we are in iOS *and* an input has been focussed) only enable the field that corresponds to this element\n */\n const enabledFields: string[] = requiredFieldsSchema.filter(item => {\n return !iOSFocusedField ? true : item === iOSFocusedField;\n });\n\n /**\n * Effect that:\n * - Resets validation for all fields by triggering handleChangeFor(fieldName, 'input')\n * - Applies validation on postalCode field in case it has any value\n */\n useEffect((): void => {\n // if the country was set via setSearchData we don't want to trigger this\n if (ignoreCountryChange) {\n setIgnoreCountryChange(false);\n return;\n }\n\n const stateOrProvince = specifications.countryHasDataset(data.country) ? '' : FALLBACK_VALUE;\n const newData = { ...data, stateOrProvince };\n\n requiredFields.forEach(fieldName => {\n handleChangeFor(fieldName, 'input')(newData[fieldName] ?? '');\n });\n\n if (newData.postalCode) {\n handleChangeFor('postalCode', 'blur')(data.postalCode);\n }\n }, [data.country]);\n\n /**\n * Set the value of 'stateOrProvince' during the initial render if\n * property is provided during the creation of the payment method\n */\n useEffect((): void => {\n const stateFieldIsRequired = requiredFields.includes('stateOrProvince');\n const countryHasStatesDataset = data.country && specifications.countryHasDataset(data.country);\n const addressShouldHaveState = stateFieldIsRequired && countryHasStatesDataset;\n const stateOrProvince = data.stateOrProvince || (addressShouldHaveState ? '' : FALLBACK_VALUE);\n\n handleChangeFor('stateOrProvince', 'input')(stateOrProvince);\n }, []);\n\n useEffect((): void => {\n const optionalFields = specifications.getOptionalFieldsForCountry(data.country);\n const processedData = ADDRESS_SCHEMA.reduce((acc, cur) => {\n const isOptional = optionalFields.includes(cur);\n const isRequired = requiredFields.includes(cur);\n const newValue = data[cur];\n const initialValue = props.data[cur];\n // recover default data values which are not requiredFields, or prefill with 'N/A'\n const fallbackValue = !isRequired && !newValue && !!initialValue ? initialValue : FALLBACK_VALUE;\n const value = (isOptional && !newValue) || !isRequired ? fallbackValue : newValue;\n if (value?.length) acc[cur] = value;\n return acc;\n }, {});\n\n props.onChange({ data: processedData, valid, errors, isValid });\n }, [data, valid, errors, isValid]);\n\n if (visibility === 'hidden') return null;\n if (visibility === 'readOnly') return <ReadOnlyAddress data={data} label={label} />;\n\n const getComponent = (fieldName: string, { classNameModifiers = [] }) => {\n if (!requiredFields.includes(fieldName)) return null;\n\n return (\n <FieldContainer\n key={fieldName}\n allowedCountries={props.allowedCountries}\n classNameModifiers={[...classNameModifiers, fieldName]}\n data={data}\n errors={errors}\n valid={valid}\n fieldName={fieldName}\n onInput={handleChangeFor(fieldName, 'input')}\n onBlur={handleChangeFor(fieldName, 'blur')}\n onDropdownChange={handleChangeFor(fieldName, 'blur')}\n specifications={specifications}\n maxLength={getMaxLengthByFieldAndCountry(countrySpecificFormatters, fieldName, data.country, true)}\n trimOnBlur={true}\n disabled={!enabledFields.includes(fieldName)}\n onFieldFocusAnalytics={props.onFieldFocusAnalytics}\n onFieldBlurAnalytics={props.onFieldBlurAnalytics}\n />\n );\n };\n\n const getWrapper = group => (\n <div className=\"adyen-checkout__field-group\">\n {group.map(([field, size]) => getComponent(field, { classNameModifiers: [`col-${size}`] }))}\n </div>\n );\n\n const addressSchema = specifications.getAddressSchemaForCountry(data.country);\n\n return (\n <Fragment>\n <Fieldset classNameModifiers={[label, 'address']} label={label}>\n {showAddressSearch && (\n <AddressSearch\n onAddressLookup={props.onAddressLookup}\n onAddressSelected={props.onAddressSelected}\n onSelect={setSearchData}\n onManualAddress={onManualAddress}\n externalErrorMessage={searchErrorMessage}\n hideManualButton={showAddressFields}\n showContextualElement={showContextualElement}\n contextualText={i18n.get('address.search.contextualText')}\n addressSearchDebounceMs={props.addressSearchDebounceMs}\n />\n )}\n {showAddressFields && (\n <Fragment>{addressSchema.map(field => (field instanceof Array ? getWrapper(field) : getComponent(field, {})))}</Fragment>\n )}\n </Fieldset>\n </Fragment>\n );\n}\n\nAddress.defaultProps = {\n countryCode: null,\n validationRules: null,\n data: {},\n onChange: () => {},\n visibility: 'editable',\n requiredFields: ADDRESS_SCHEMA,\n specifications: {},\n onFieldFocusAnalytics: () => {},\n onFieldBlurAnalytics: () => {}\n};\n"],"names":["Address","props","i18n","useCoreContext","label","requiredFields","visibility","iOSFocusedField","showContextualElement","addressRef","useRef","Object","keys","current","length","setComponentRef","specifications","useMemo","Specifications","requiredFieldsSchema","getAddressSchemaForCountryFlat","countryCode","filter","field","includes","hasSelectedAddress","setHasSelectedAddress","useState","useManualAddress","setUseManualAddress","searchErrorMessage","setSearchErrorMessage","showAddressSearch","onAddressLookup","ignoreCountryChange","setIgnoreCountryChange","showAddressFields","data","errors","valid","isValid","handleChangeFor","triggerValidation","setData","mergeData","useForm","schema","defaultData","rules","getAddressValidationRules","validationRules","formatters","addressFormatters","setSearchData","useCallback","selectedAddress","newStateData","ADDRESS_SCHEMA","reduce","acc","propKey","providedValue","String","onManualAddress","showValidation","get","enabledFields","item","useEffect","stateOrProvince","countryHasDataset","country","FALLBACK_VALUE","newData","forEach","fieldName","postalCode","stateFieldIsRequired","countryHasStatesDataset","addressShouldHaveState","optionalFields","getOptionalFieldsForCountry","processedData","cur","isOptional","isRequired","newValue","initialValue","value","onChange","h","ReadOnlyAddress","getComponent","classNameModifiers","FieldContainer","key","allowedCountries","onInput","onBlur","onDropdownChange","maxLength","getMaxLengthByFieldAndCountry","countrySpecificFormatters","trimOnBlur","disabled","onFieldFocusAnalytics","onFieldBlurAnalytics","addressSchema","getAddressSchemaForCountry","Fragment","Fieldset","AddressSearch","onAddressSelected","onSelect","externalErrorMessage","hideManualButton","contextualText","addressSearchDebounceMs","map","Array","div","className","size","defaultProps"],"mappings":"u1BAkBe,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}
|
|
@@ -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 s}from"../../../../core/Errors/constants.js";import{useRef 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 s}from"../../../../core/Errors/constants.js";import{useRef as d,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?.length>0,U=d(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},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 d=a("span",{className:e({"adyen-checkout-contextual-text--error":!0,"adyen-checkout-contextual-text--hidden":!K}),...J&&{id:`${U.current}${r}`},"aria-hidden":J?null:"true"},N),c=a("span",{className:e({"adyen-checkout-contextual-text":!0,"adyen-checkout-contextual-text--hidden":!Q}),...J&&{id:`${U.current}${s}`},"aria-hidden":J?null:"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`,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")}))),d,c)},[k,N,R,$,j,ne,te]),oe=m(({onFocusField:n,focused:t,filled:l,disabled:i,name:o,uniqueId:r,useLabelElement:s,isSecuredField:d,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 s?a("label",{...m,...!d&&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<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 >\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`} 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 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","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,EAAyCC,IAC3C,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,gBACbA,EAAeC,iBACfA,EAAgBC,sBAChBA,EAAqBC,YACrBA,EAAWC,eACXA,EAEAC,OAAQC,EACRC,QAASC,EAAYC,KACrBA,EAAIC,6BACJA,EAA4BC,yBAC5BA,EAAwBC,sBACxBA,GACAhC,EAIEiC,EAAqBH,IAAgC,EACrDI,EAAYb,GAA4C,iBAAjBd,GAA6BA,EAAa4B,OAAS,EAC1FC,EAAcd,IAA0BY,GAAaV,GAAgBW,OAAS,EAE9EE,EAAWC,EAAOC,EAAY,kBAAkBzB,MAChD0B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EACTP,gBAAiBA,EACjBiB,SAAUA,EAASsB,QACnBsB,gBAAiBhD,EACjBF,yBAA0BA,GAEzBmB,MAEJM,OAKbzD,EAAMqF,aAAe,CACjBlF,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<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 >\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`} 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","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","data-testid","defaultProps"],"mappings":"omBAYA,MAAMA,EAAyCC,IAC3C,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,gBACbA,EAAeC,iBACfA,EAAgBC,sBAChBA,EAAqBC,YACrBA,EAAWC,eACXA,EAEAC,OAAQC,EACRC,QAASC,EAAYC,KACrBA,EAAIC,6BACJA,EAA4BC,yBAC5BA,EAAwBC,sBACxBA,GACAhC,EAIEiC,EAAqBH,IAAgC,EACrDI,EAAYb,GAA4C,iBAAjBd,GAA6BA,EAAa4B,OAAS,EAC1FC,EAAcd,IAA0BY,GAAaV,GAAgBW,OAAS,EAE9EE,EAAWC,EAAOC,EAAY,kBAAkBzB,MAChD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QA,GACRE,QAASA,EACTP,gBAAiBA,EACjBiB,SAAUA,EAASsB,QACnBsB,gBAAiBhD,EACjBF,yBAA0BA,GAEzBmB,MAEJM,OAKbzD,EAAMsF,aAAe,CACjBnF,UAAW,GACXC,mBAAoB,GACpBM,sBAAuB,GACvBW,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBS,yBAA0B,IAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../../../external/preact/dist/preact.js";import t from"../../../../_virtual/index.js";import{useCoreContext as
|
|
1
|
+
import{createElement as e}from"../../../../external/preact/dist/preact.js";import t from"../../../../_virtual/index.js";import{useCoreContext as s}from"../../../../core/Context/CoreProvider.js";import{getUniqueId as i}from"../../../../utils/idGenerator.js";import{useMemo as a}from"../../../../external/preact/hooks/dist/hooks.js";function d({children:d,classNameModifiers:o=[],classNamesFields:r=[],label:l,readonly:c=!1,description:n,id:m}){const{i18n:_}=s(),f=a(()=>i("fieldset-description"),[]);return e("fieldset",{id:m,className:t(["adyen-checkout__fieldset",...o.map(e=>`adyen-checkout__fieldset--${e}`),{"adyen-checkout__fieldset--readonly":c}]),"aria-describedby":n?f:null},l&&e("legend",{className:"adyen-checkout__fieldset__title"},_.get(l)),n&&e("p",{id:f,className:"adyen-checkout__fieldset__description"},_.get(n)),e("div",{className:t("adyen-checkout__fieldset__fields",r)},d))}export{d as default};
|
|
2
2
|
//# sourceMappingURL=Fieldset.js.map
|