@adyen/adyen-web 6.20.0 → 6.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/adyen.css +9 -10
  3. package/dist/cjs/adyen.css.map +1 -1
  4. package/dist/cjs/index.cjs +2 -2
  5. package/dist/cjs/index.cjs.map +1 -1
  6. package/dist/cjs/index.d.cts +33 -9
  7. package/dist/es/adyen.css +9 -10
  8. package/dist/es/adyen.css.map +1 -1
  9. package/dist/es/components/Ach/Ach.js +1 -1
  10. package/dist/es/components/Ach/Ach.js.map +1 -1
  11. package/dist/es/components/Ach/components/AchComponent.js +1 -1
  12. package/dist/es/components/Ach/components/AchComponent.js.map +1 -1
  13. package/dist/es/components/Card/Card.js +1 -1
  14. package/dist/es/components/Card/Card.js.map +1 -1
  15. package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
  16. package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
  17. package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
  18. package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
  19. package/dist/es/components/Card/components/CardInput/utils.js +1 -1
  20. package/dist/es/components/Card/components/CardInput/utils.js.map +1 -1
  21. package/dist/es/components/PayByBankPix/PayByBankPix.js +1 -1
  22. package/dist/es/components/PayByBankPix/PayByBankPix.js.map +1 -1
  23. package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js +1 -1
  24. package/dist/es/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -1
  25. package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +1 -1
  26. package/dist/es/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -1
  27. package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +1 -1
  28. package/dist/es/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -1
  29. package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js +1 -1
  30. package/dist/es/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -1
  31. package/dist/es/components/PayTo/components/BSBInput.js +1 -1
  32. package/dist/es/components/PayTo/components/BSBInput.js.map +1 -1
  33. package/dist/es/components/PayTo/components/PayIDInput.js +1 -1
  34. package/dist/es/components/PayTo/components/PayIDInput.js.map +1 -1
  35. package/dist/es/components/PayTo/components/PayToComponent.js +1 -1
  36. package/dist/es/components/PayTo/components/PayToComponent.js.map +1 -1
  37. package/dist/es/components/UPI/UPI.js +1 -1
  38. package/dist/es/components/UPI/UPI.js.map +1 -1
  39. package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
  40. package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
  41. package/dist/es/components/UPI/components/UPIMandate/UPIMandate.js +2 -0
  42. package/dist/es/components/UPI/components/UPIMandate/UPIMandate.js.map +1 -0
  43. package/dist/es/components/internal/Address/components/AddressSearch.js.map +1 -1
  44. package/dist/es/components/internal/Await/Await.js +1 -1
  45. package/dist/es/components/internal/Await/Await.js.map +1 -1
  46. package/dist/es/components/internal/FormFields/Fieldset/Fieldset.js +1 -1
  47. package/dist/es/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
  48. package/dist/es/components/internal/IssuerList/IssuerList.js +1 -1
  49. package/dist/es/components/internal/IssuerList/IssuerList.js.map +1 -1
  50. package/dist/es/components/internal/PayButton/PayButton.js +1 -1
  51. package/dist/es/components/internal/PayButton/PayButton.js.map +1 -1
  52. package/dist/es/components/internal/PayButton/components/SecondaryButtonLabel.js.map +1 -1
  53. package/dist/es/components/internal/QRLoader/QRLoader.js +1 -1
  54. package/dist/es/components/internal/QRLoader/QRLoader.js.map +1 -1
  55. package/dist/es/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js +1 -1
  56. package/dist/es/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js.map +1 -1
  57. package/dist/es/components/internal/SecuredFields/binLookup/extensions.js +1 -1
  58. package/dist/es/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
  59. package/dist/es/core/Analytics/Analytics.js +1 -1
  60. package/dist/es/core/Analytics/Analytics.js.map +1 -1
  61. package/dist/es/core/Analytics/utils.js +1 -1
  62. package/dist/es/core/Analytics/utils.js.map +1 -1
  63. package/dist/es/core/Services/analytics/collect-id.js +1 -1
  64. package/dist/es/core/Services/analytics/collect-id.js.map +1 -1
  65. package/dist/es/core/core.js +1 -1
  66. package/dist/es/core/core.js.map +1 -1
  67. package/dist/es/index.d.ts +33 -9
  68. package/dist/es/utils/setFocus.js +1 -1
  69. package/dist/es/utils/setFocus.js.map +1 -1
  70. package/dist/es-legacy/adyen.css +9 -10
  71. package/dist/es-legacy/adyen.css.map +1 -1
  72. package/dist/es-legacy/components/Ach/Ach.js +1 -1
  73. package/dist/es-legacy/components/Ach/Ach.js.map +1 -1
  74. package/dist/es-legacy/components/Ach/components/AchComponent.js +1 -1
  75. package/dist/es-legacy/components/Ach/components/AchComponent.js.map +1 -1
  76. package/dist/es-legacy/components/Card/Card.js +1 -1
  77. package/dist/es-legacy/components/Card/Card.js.map +1 -1
  78. package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js +1 -1
  79. package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
  80. package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
  81. package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
  82. package/dist/es-legacy/components/Card/components/CardInput/utils.js +1 -1
  83. package/dist/es-legacy/components/Card/components/CardInput/utils.js.map +1 -1
  84. package/dist/es-legacy/components/PayByBankPix/PayByBankPix.js +1 -1
  85. package/dist/es-legacy/components/PayByBankPix/PayByBankPix.js.map +1 -1
  86. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js +1 -1
  87. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/Enrollment.js.map +1 -1
  88. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js +1 -1
  89. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/components/IssuerListIntroduction.js.map +1 -1
  90. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js +1 -1
  91. package/dist/es-legacy/components/PayByBankPix/components/Enrollment/useIssuerWithLogo.js.map +1 -1
  92. package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js +1 -1
  93. package/dist/es-legacy/components/PayByBankPix/components/StoredPayment/StoredPayment.js.map +1 -1
  94. package/dist/es-legacy/components/PayTo/components/BSBInput.js +1 -1
  95. package/dist/es-legacy/components/PayTo/components/BSBInput.js.map +1 -1
  96. package/dist/es-legacy/components/PayTo/components/PayIDInput.js +1 -1
  97. package/dist/es-legacy/components/PayTo/components/PayIDInput.js.map +1 -1
  98. package/dist/es-legacy/components/PayTo/components/PayToComponent.js +1 -1
  99. package/dist/es-legacy/components/PayTo/components/PayToComponent.js.map +1 -1
  100. package/dist/es-legacy/components/UPI/UPI.js +1 -1
  101. package/dist/es-legacy/components/UPI/UPI.js.map +1 -1
  102. package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
  103. package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
  104. package/dist/es-legacy/components/UPI/components/UPIMandate/UPIMandate.js +2 -0
  105. package/dist/es-legacy/components/UPI/components/UPIMandate/UPIMandate.js.map +1 -0
  106. package/dist/es-legacy/components/internal/Address/components/AddressSearch.js.map +1 -1
  107. package/dist/es-legacy/components/internal/Await/Await.js +1 -1
  108. package/dist/es-legacy/components/internal/Await/Await.js.map +1 -1
  109. package/dist/es-legacy/components/internal/FormFields/Fieldset/Fieldset.js +1 -1
  110. package/dist/es-legacy/components/internal/FormFields/Fieldset/Fieldset.js.map +1 -1
  111. package/dist/es-legacy/components/internal/IssuerList/IssuerList.js +1 -1
  112. package/dist/es-legacy/components/internal/IssuerList/IssuerList.js.map +1 -1
  113. package/dist/es-legacy/components/internal/PayButton/PayButton.js +1 -1
  114. package/dist/es-legacy/components/internal/PayButton/PayButton.js.map +1 -1
  115. package/dist/es-legacy/components/internal/PayButton/components/SecondaryButtonLabel.js.map +1 -1
  116. package/dist/es-legacy/components/internal/QRLoader/QRLoader.js +1 -1
  117. package/dist/es-legacy/components/internal/QRLoader/QRLoader.js.map +1 -1
  118. package/dist/es-legacy/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js +1 -1
  119. package/dist/es-legacy/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.js.map +1 -1
  120. package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js +1 -1
  121. package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
  122. package/dist/es-legacy/core/Analytics/Analytics.js +1 -1
  123. package/dist/es-legacy/core/Analytics/Analytics.js.map +1 -1
  124. package/dist/es-legacy/core/Analytics/utils.js +1 -1
  125. package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
  126. package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
  127. package/dist/es-legacy/core/Services/analytics/collect-id.js.map +1 -1
  128. package/dist/es-legacy/core/core.js +1 -1
  129. package/dist/es-legacy/core/core.js.map +1 -1
  130. package/dist/es-legacy/utils/setFocus.js +1 -1
  131. package/dist/es-legacy/utils/setFocus.js.map +1 -1
  132. package/package.json +157 -159
  133. package/styles/adyen.css +9 -10
@@ -1 +1 @@
1
- {"version":3,"file":"IssuerList.js","sources":["../../../../../src/components/internal/IssuerList/IssuerList.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useState, useEffect, useCallback, useRef } from 'preact/hooks';\nimport useForm from '../../../utils/useForm';\nimport Field from '../FormFields/Field';\nimport IssuerButtonGroup from './IssuerButtonGroup';\nimport ContentSeparator from '../ContentSeparator';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ValidatorRules } from '../../../utils/Validator/types';\nimport { IssuerListProps } from './types';\nimport './IssuerList.scss';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport { ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport DisclaimerMessage from '../DisclaimerMessage';\nimport Select from '../FormFields/Select';\nimport { SelectTargetObject } from '../FormFields/Select/types';\nimport {\n ANALYTICS_DISPLAYED_STR,\n ANALYTICS_FEATURED_ISSUER,\n ANALYTICS_INPUT_STR,\n ANALYTICS_LIST,\n ANALYTICS_LIST_SEARCH,\n ANALYTICS_SEARCH_DEBOUNCE_TIME,\n ANALYTICS_SELECTED_STR\n} from '../../../core/Analytics/constants';\nimport { debounce } from '../../../utils/debounce';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst payButtonLabel = ({ issuer, items }, i18n): string => {\n const issuerName = items.find(i => i.id === issuer)?.name;\n if (!issuer || !issuerName) return i18n.get('continue');\n return `${i18n.get('continueTo')} ${issuerName}`;\n};\n\nconst schema = ['issuer'];\nconst validationRules: ValidatorRules = {\n issuer: {\n validate: issuer => !!issuer && issuer.length > 0,\n errorMessage: 'issuerList.selectField.contextualText',\n modes: ['blur']\n }\n};\n\nenum IssuerListInputTypes {\n ButtonGroup,\n Dropdown\n}\n\nfunction IssuerList({ items, placeholder, issuer, highlightedIds = [], showContextualElement, contextualText, ...props }: IssuerListProps) {\n const { i18n } = useCoreContext();\n const { handleChangeFor, triggerValidation, data, valid, errors, isValid } = useForm({\n schema,\n defaultData: { issuer },\n rules: validationRules\n });\n const [status, setStatus] = useState('ready');\n const [inputType, setInputType] = useState<IssuerListInputTypes>(IssuerListInputTypes.Dropdown);\n\n const { setSRMessagesFromObjects, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n const getErrorMessage = error => (error && error.errorMessage ? i18n.get(error.errorMessage) : !!error);\n\n this.setStatus = newStatus => {\n setStatus(newStatus);\n };\n\n const handleInputChange = useCallback(\n (type: IssuerListInputTypes) => (event: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) => {\n const target = type === IssuerListInputTypes.Dropdown ? ANALYTICS_LIST : ANALYTICS_FEATURED_ISSUER;\n const issuerObj = items.find(issuer => issuer.id === (event.target as SelectTargetObject).value);\n\n const analyticsEvent = new AnalyticsInfoEvent({\n type: ANALYTICS_SELECTED_STR,\n target,\n issuer: issuerObj.name\n });\n props.onSubmitAnalytics(analyticsEvent);\n\n setInputType(type);\n handleChangeFor('issuer')(event);\n },\n [handleChangeFor]\n );\n\n const handleListToggle = useCallback((isOpen: boolean) => {\n if (isOpen) {\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DISPLAYED_STR,\n target: ANALYTICS_LIST\n });\n props.onSubmitAnalytics(event);\n }\n }, []);\n\n const debounceSearchAnalytics = useRef(debounce(props.onSubmitAnalytics, ANALYTICS_SEARCH_DEBOUNCE_TIME));\n\n const handleSearch = useCallback(() => {\n debounceSearchAnalytics.current({ type: ANALYTICS_INPUT_STR, target: ANALYTICS_LIST_SEARCH });\n }, []);\n\n useEffect(() => {\n props.onChange({ data, valid, errors, isValid });\n\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: true });\n if (srPanelResp?.action === ERROR_ACTION_FOCUS_FIELD) {\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField('.adyen-checkout__issuer-list', 'issuer-list');\n }\n }, [data, valid, errors, isValid]);\n\n this.showValidation = () => {\n triggerValidation();\n };\n\n const { highlightedItems } = items.reduce(\n (memo, item) => {\n if (highlightedIds.includes(item.id)) memo.highlightedItems.push({ ...item });\n return memo;\n },\n { highlightedItems: [] }\n );\n\n return (\n <div className=\"adyen-checkout__issuer-list\">\n {!!highlightedItems.length && (\n <Fragment>\n <IssuerButtonGroup\n selectedIssuerId={inputType === IssuerListInputTypes.ButtonGroup ? data['issuer'] : null}\n items={highlightedItems}\n onChange={handleInputChange(IssuerListInputTypes.ButtonGroup)}\n />\n <ContentSeparator />\n </Fragment>\n )}\n\n <Field\n label={i18n.get('issuerList.selectField.label')}\n errorMessage={getErrorMessage(errors.issuer)}\n classNameModifiers={['issuer-list']}\n name={'issuer'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n items={items}\n selectedValue={inputType === IssuerListInputTypes.Dropdown ? data['issuer'] : null}\n placeholder={placeholder}\n name={'issuer'}\n className={'adyen-checkout__issuer-list__dropdown'}\n onChange={handleInputChange(IssuerListInputTypes.Dropdown)}\n onListToggle={handleListToggle}\n onInput={handleSearch}\n />\n </Field>\n\n {props.termsAndConditions && (\n <div className=\"adyen-checkout__issuer-list__termsAndConditions\">\n <DisclaimerMessage message={i18n.get(props.termsAndConditions.translationKey)} urls={props.termsAndConditions.urls} />\n </div>\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n label: payButtonLabel({ issuer: data['issuer'], items: [...items, ...highlightedItems] }, i18n)\n })}\n </div>\n );\n}\n\nIssuerList.defaultProps = {\n onChange: () => {}\n};\n\nexport default IssuerList;\n"],"names":["payButtonLabel","issuer","items","i18n","issuerName","find","i","id","name","get","schema","validationRules","validate","length","errorMessage","modes","IssuerList","_param","placeholder","highlightedIds","showContextualElement","contextualText","props","useCoreContext","handleChangeFor","triggerValidation","data","valid","errors","isValid","useForm","defaultData","rules","status","setStatus","useState","inputType","setInputType","setSRMessagesFromObjects","shouldMoveFocusSR","useSRPanelContext","setSRMessages","this","newStatus","handleInputChange","useCallback","type","event","target","ANALYTICS_LIST","ANALYTICS_FEATURED_ISSUER","issuerObj","value","analyticsEvent","AnalyticsInfoEvent","ANALYTICS_SELECTED_STR","onSubmitAnalytics","handleListToggle","isOpen","ANALYTICS_DISPLAYED_STR","debounceSearchAnalytics","useRef","debounce","ANALYTICS_SEARCH_DEBOUNCE_TIME","handleSearch","current","ANALYTICS_INPUT_STR","ANALYTICS_LIST_SEARCH","useEffect","onChange","srPanelResp","isValidating","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","showValidation","highlightedItems","reduce","memo","item","includes","push","_object_spread","h","div","className","Fragment","IssuerButtonGroup","selectedIssuerId","ContentSeparator","Field","label","error","classNameModifiers","Select","selectedValue","onListToggle","onInput","termsAndConditions","DisclaimerMessage","message","translationKey","urls","showPayButton","payButton","defaultProps"],"mappings":"knDA8BA,MAAMA,EAAiB,EAAGC,SAAQC,SAASC,KACpBD,IAAAA,EAAnB,MAAME,EAAsCH,QAAzBC,EAAAA,EAAMG,KAAKC,GAAKA,EAAEC,KAAON,UAAzBC,IAAAA,OAAAA,EAAAA,EAAkCM,KACrD,OAAKP,GAAWG,EACT,GAAGD,EAAKM,IAAI,iBAAiBL,IADDD,EAAKM,IAAI,aAI1CC,EAAS,CAAC,UACVC,EAAkC,CACpCV,OAAQ,CACJW,SAAUX,KAAYA,GAAUA,EAAOY,OAAS,EAChDC,aAAc,wCACdC,MAAO,CAAC,UAShB,SAASC,EAAWC,GAAA,IAAAf,MAAEA,EAAKgB,YAAEA,EAAWjB,OAAEA,EAAMkB,eAAEA,EAAiB,GAAEC,sBAAEA,EAAqBC,eAAEA,GAA1EJ,EAA6FK,EAAAA,EAA7FL,EAAA,CAAEf,QAAOgB,cAAajB,SAAQkB,iBAAqBC,wBAAuBC,mBAC1F,MAAMlB,KAAEA,GAASoB,KACXC,gBAAEA,EAAeC,kBAAEA,EAAiBC,KAAEA,EAAIC,MAAEA,EAAKC,OAAEA,EAAMC,QAAEA,GAAYC,EAAQ,CACjFpB,SACAqB,YAAa,CAAE9B,UACf+B,MAAOrB,KAEJsB,EAAQC,GAAaC,EAAS,UAC9BC,EAAWC,GAAgBF,EAAAA,IAE5BG,yBAAEA,EAAwBC,kBAAEA,GAAsBC,IAClDC,EAAu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OAAY,KACpFxB,MAAO0E,GACPP,SAAUzB,EAAAA,KAEduC,EAACM,SAITN,EAACO,EAAAA,CACGC,MAAOxF,EAAKM,IAAI,gCAChBK,cA7EY8E,GA6EkBhE,EAAO3B,OA7Ef2F,IAASA,GAAM9E,aAAeX,EAAKM,IAAImF,GAAM9E,gBAAkB8E,IA8ErFC,mBAAoB,CAAC,eACrBrF,KAAM,SACNY,sBAAuBA,EACvBC,eAAgBA,GAEhB8D,EAACW,EAAAA,CACG5F,MAAOA,EACP6F,cAAe3D,IAAAA,EAA8CV,EAAK,OAAY,KAC9ER,YAAaA,EACbV,KAAM,SACN6E,UAAW,wCACXhB,SAAUzB,EAAAA,GACVoD,aAAcvC,EACdwC,QAASjC,MAIhB1C,EAAM4E,oBACHf,EAACC,MAAAA,CAAIC,UAAU,mDACXF,EAACgB,EAAAA,CAAkBC,QAASjG,EAAKM,IAAIa,EAAM4E,mBAAmBG,gBAAiBC,KAAMhF,EAAM4E,mBAAmBI,QAIrHhF,EAAMiF,eACHjF,EAAMkF,UAAU,CACZvE,SACA0D,MAAO3F,EAAe,CAAEC,OAAQyB,EAAK,OAAWxB,MAAO,IAAIA,KAAU0E,KAAqBzE,MAxGlFyF,IAAAA,EA4G5B,CAEA5E,EAAWyF,aAAe,CACtBpC,SAAU"}
1
+ {"version":3,"file":"IssuerList.js","sources":["../../../../../src/components/internal/IssuerList/IssuerList.tsx"],"sourcesContent":["import { Fragment, h } from 'preact';\nimport { useState, useEffect, useCallback, useRef } from 'preact/hooks';\nimport useForm from '../../../utils/useForm';\nimport Field from '../FormFields/Field';\nimport IssuerButtonGroup from './IssuerButtonGroup';\nimport ContentSeparator from '../ContentSeparator';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ValidatorRules } from '../../../utils/Validator/types';\nimport { IssuerListProps } from './types';\nimport './IssuerList.scss';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport { ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport DisclaimerMessage from '../DisclaimerMessage';\nimport Select from '../FormFields/Select';\nimport { SelectTargetObject } from '../FormFields/Select/types';\nimport {\n ANALYTICS_DISPLAYED_STR,\n ANALYTICS_FEATURED_ISSUER,\n ANALYTICS_INPUT_STR,\n ANALYTICS_LIST,\n ANALYTICS_LIST_SEARCH,\n ANALYTICS_SEARCH_DEBOUNCE_TIME,\n ANALYTICS_SELECTED_STR\n} from '../../../core/Analytics/constants';\nimport { debounce } from '../../../utils/debounce';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst payButtonLabel = ({ issuer, items }, i18n): string => {\n const issuerName = items.find(i => i.id === issuer)?.name;\n if (!issuer || !issuerName) return i18n.get('continue');\n return `${i18n.get('continueTo')} ${issuerName}`;\n};\n\nconst schema = ['issuer'];\nconst validationRules: ValidatorRules = {\n issuer: {\n validate: issuer => !!issuer && issuer.length > 0,\n errorMessage: 'issuerList.selectField.contextualText',\n modes: ['blur']\n }\n};\n\nenum IssuerListInputTypes {\n ButtonGroup,\n Dropdown\n}\n\nfunction IssuerList({\n items,\n placeholder,\n issuer,\n highlightedIds = [],\n showContextualElement,\n contextualText,\n selectFieldLabel,\n ...props\n}: IssuerListProps) {\n const { i18n } = useCoreContext();\n const { handleChangeFor, triggerValidation, data, valid, errors, isValid } = useForm({\n schema,\n defaultData: { issuer },\n rules: validationRules\n });\n const [status, setStatus] = useState('ready');\n const [inputType, setInputType] = useState<IssuerListInputTypes>(IssuerListInputTypes.Dropdown);\n\n const { setSRMessagesFromObjects, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n const containerRef = useRef<HTMLDivElement>(null);\n\n const getErrorMessage = error => (error && error.errorMessage ? i18n.get(error.errorMessage) : !!error);\n\n this.setStatus = newStatus => {\n setStatus(newStatus);\n };\n\n const handleInputChange = useCallback(\n (type: IssuerListInputTypes) => (event: h.JSX.TargetedKeyboardEvent<HTMLInputElement>) => {\n const target = type === IssuerListInputTypes.Dropdown ? ANALYTICS_LIST : ANALYTICS_FEATURED_ISSUER;\n const issuerObj = items.find(issuer => issuer.id === (event.target as SelectTargetObject).value);\n\n const analyticsEvent = new AnalyticsInfoEvent({\n type: ANALYTICS_SELECTED_STR,\n target,\n issuer: issuerObj.name\n });\n props.onSubmitAnalytics(analyticsEvent);\n\n setInputType(type);\n handleChangeFor('issuer')(event);\n },\n [handleChangeFor]\n );\n\n const handleListToggle = useCallback((isOpen: boolean) => {\n if (isOpen) {\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DISPLAYED_STR,\n target: ANALYTICS_LIST\n });\n props.onSubmitAnalytics(event);\n }\n }, []);\n\n const debounceSearchAnalytics = useRef(debounce(props.onSubmitAnalytics, ANALYTICS_SEARCH_DEBOUNCE_TIME));\n\n const handleSearch = useCallback(() => {\n debounceSearchAnalytics.current({ type: ANALYTICS_INPUT_STR, target: ANALYTICS_LIST_SEARCH });\n }, []);\n\n useEffect(() => {\n props.onChange({ data, valid, errors, isValid });\n\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: true });\n if (srPanelResp?.action === ERROR_ACTION_FOCUS_FIELD) {\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField(containerRef.current, 'issuer-list');\n }\n }, [data, valid, errors, isValid]);\n\n this.showValidation = () => {\n triggerValidation();\n };\n\n const { highlightedItems } = items.reduce(\n (memo, item) => {\n if (highlightedIds.includes(item.id)) memo.highlightedItems.push({ ...item });\n return memo;\n },\n { highlightedItems: [] }\n );\n\n return (\n <div ref={containerRef} className=\"adyen-checkout__issuer-list\">\n {!!highlightedItems.length && (\n <Fragment>\n <IssuerButtonGroup\n selectedIssuerId={inputType === IssuerListInputTypes.ButtonGroup ? data['issuer'] : null}\n items={highlightedItems}\n onChange={handleInputChange(IssuerListInputTypes.ButtonGroup)}\n />\n <ContentSeparator />\n </Fragment>\n )}\n\n <Field\n label={selectFieldLabel ?? i18n.get('issuerList.selectField.label')}\n errorMessage={getErrorMessage(errors.issuer)}\n classNameModifiers={['issuer-list']}\n name={'issuer'}\n showContextualElement={showContextualElement}\n contextualText={contextualText}\n >\n <Select\n items={items}\n selectedValue={inputType === IssuerListInputTypes.Dropdown ? data['issuer'] : null}\n placeholder={placeholder}\n name={'issuer'}\n className={'adyen-checkout__issuer-list__dropdown'}\n onChange={handleInputChange(IssuerListInputTypes.Dropdown)}\n onListToggle={handleListToggle}\n onInput={handleSearch}\n />\n </Field>\n\n {props.termsAndConditions && (\n <div className=\"adyen-checkout__issuer-list__termsAndConditions\">\n <DisclaimerMessage message={i18n.get(props.termsAndConditions.translationKey)} urls={props.termsAndConditions.urls} />\n </div>\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n label: payButtonLabel({ issuer: data['issuer'], items: [...items, ...highlightedItems] }, i18n)\n })}\n </div>\n );\n}\n\nIssuerList.defaultProps = {\n onChange: () => {}\n};\n\nexport default IssuerList;\n"],"names":["payButtonLabel","issuer","items","i18n","issuerName","find","i","id","name","get","schema","validationRules","validate","length","errorMessage","modes","IssuerList","_param","placeholder","highlightedIds","showContextualElement","contextualText","selectFieldLabel","props","useCoreContext","handleChangeFor","triggerValidation","data","valid","errors","isValid","useForm","defaultData","rules","status","setStatus","useState","inputType","setInputType","setSRMessagesFromObjects","shouldMoveFocusSR","useSRPanelContext","setSRMessages","containerRef","useRef","this","newStatus","handleInputChange","useCallback","type","event","target","ANALYTICS_LIST","ANALYTICS_FEATURED_ISSUER","issuerObj","value","analyticsEvent","AnalyticsInfoEvent","ANALYTICS_SELECTED_STR","onSubmitAnalytics","handleListToggle","isOpen","ANALYTICS_DISPLAYED_STR","debounceSearchAnalytics","debounce","ANALYTICS_SEARCH_DEBOUNCE_TIME","handleSearch","current","ANALYTICS_INPUT_STR","ANALYTICS_LIST_SEARCH","useEffect","onChange","srPanelResp","isValidating","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","showValidation","highlightedItems","reduce","memo","item","includes","push","_object_spread","h","div","ref","className","Fragment","IssuerButtonGroup","selectedIssuerId","ContentSeparator","Field","label","error","classNameModifiers","Select","selectedValue","onListToggle","onInput","termsAndConditions","DisclaimerMessage","message","translationKey","urls","showPayButton","payButton","defaultProps"],"mappings":"knDA8BA,MAAMA,EAAiB,EAAGC,SAAQC,SAASC,KACpBD,IAAAA,EAAnB,MAAME,EAAsCH,QAAzBC,EAAAA,EAAMG,KAAKC,GAAKA,EAAEC,KAAON,UAAzBC,IAAAA,OAAAA,EAAAA,EAAkCM,KACrD,OAAKP,GAAWG,EACT,GAAGD,EAAKM,IAAI,iBAAiBL,IADDD,EAAKM,IAAI,aAI1CC,EAAS,CAAC,UACVC,EAAkC,CACpCV,OAAQ,CACJW,SAAUX,KAAYA,GAAUA,EAAOY,OAAS,EAChDC,aAAc,wCACdC,MAAO,CAAC,UAShB,SAASC,EAAWC,GAAA,IAAAf,MAChBA,EAAKgB,YACLA,EAAWjB,OACXA,EAAMkB,eACNA,EAAiB,GAAEC,sBACnBA,EAAqBC,eACrBA,EAAcC,iBACdA,GAPgBL,EAQbM,EAAAA,EARaN,EAAA,CAChBf,QACAgB,cACAjB,SACAkB,iBACAC,wBACAC,iBACAC,qBAGA,MAAMnB,KAAEA,GAASqB,KACXC,gBAAEA,EAAeC,kBAAEA,EAAiBC,KAAEA,EAAIC,MAAEA,EAAKC,OAAEA,EAAMC,QAAEA,GAAYC,EAAQ,CACjFrB,SACAsB,YAAa,CAAE/B,UACfgC,MAAOtB,KAEJuB,EAAQC,GAAaC,EAAS,UAC9BC,EAAWC,GAAgBF,EAAAA,IAE5BG,yBAAEA,EAAwBC,kBAAEA,GAAsBC,IAClDC,EAAuCH,aAAAA,EAAAA,EAA2B,IAElEI,EAAeC,EAAuB,MAI5CC,KA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ACpFzB,MAAO4E,GACPP,SAAUxB,GAAAA,KAEdsC,EAACO,SAITP,EAACQ,EAAAA,CACGC,MAAOxE,QAAAA,EAAoBnB,EAAKM,IAAI,gCACpCK,cA7EYiF,GA6EkBlE,EAAO5B,OA7Ef8F,IAASA,GAAMjF,aAAeX,EAAKM,IAAIsF,GAAMjF,gBAAkBiF,IA8ErFC,mBAAoB,CAAC,eACrBxF,KAAM,SACNY,sBAAuBA,EACvBC,eAAgBA,GAEhBgE,EAACY,EAAAA,CACG/F,MAAOA,EACPgG,cAAe7D,IAAAA,EAA8CV,EAAK,OAAY,KAC9ET,YAAaA,EACbV,KAAM,SACNgF,UAAW,wCACXjB,SAAUxB,GAAAA,GACVoD,aAAcvC,GACdwC,QAASlC,MAIhB3C,EAAM8E,oBACHhB,EAACC,MAAAA,CAAIE,UAAU,mDACXH,EAACiB,EAAAA,CAAkBC,QAASpG,EAAKM,IAAIc,EAAM8E,mBAAmBG,gBAAiBC,KAAMlF,EAAM8E,mBAAmBI,QAIrHlF,EAAMmF,eACHnF,EAAMoF,UAAU,CACZzE,SACA4D,MAAO9F,EAAe,CAAEC,OAAQ0B,EAAK,OAAWzB,MAAO,IAAIA,KAAU4E,KAAqB3E,MAxGlF4F,IAAAA,EA4G5B,CAEA/E,EAAW4F,aAAe,CACtBrC,SAAU"}
@@ -1,2 +1,2 @@
1
- import{createElement as e}from"../../../external/preact/dist/preact.js";import t from"../Button/Button.js";import{useCoreContext as r}from"../../../core/Context/CoreProvider.js";import{payAmountLabel as n,secondaryAmountLabel as o}from"./utils.js";import c from"./components/SecondaryButtonLabel.js";function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t.push.apply(t,r)}return t}(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}),e}function i(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r,n,o={},c=Object.keys(e);for(n=0;n<c.length;n++)r=c[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(n=0;n<c.length;n++)r=c[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}const s=s=>{var{amount:u,secondaryAmount:b,classNameModifiers:f=[],label:p}=s,O=i(s,["amount","secondaryAmount","classNameModifiers","label"]);const{i18n:y}=r(),m=u&&{}.hasOwnProperty.call(u,"value")&&0===u.value,j=m?y.get("confirmPreauthorization"):n(y,u),d=!m&&!p&&u&&b&&Object.keys(b).length?o(y,b):null;return e(t,l(function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){a(e,t,r[t])})}return e}({},O),{disabled:O.disabled||"loading"===O.status,classNameModifiers:[...f,"pay"],label:p||j}),d&&e(c,{label:d}))};export{s as default,n as payAmountLabel};
1
+ import{createElement as e}from"../../../external/preact/dist/preact.js";import t from"../Button/Button.js";import{useCoreContext as r}from"../../../core/Context/CoreProvider.js";import{payAmountLabel as n,secondaryAmountLabel as o}from"./utils.js";import c from"./components/SecondaryButtonLabel.js";function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t.push.apply(t,r)}return t}(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}),e}function i(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r,n,o={},c=Object.keys(e);for(n=0;n<c.length;n++)r=c[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(n=0;n<c.length;n++)r=c[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}const s=s=>{var{amount:u,secondaryAmount:b,classNameModifiers:f=[],label:p}=s,y=i(s,["amount","secondaryAmount","classNameModifiers","label"]);const{i18n:O}=r(),m=u&&{}.hasOwnProperty.call(u,"value")&&0===u.value,j=m?O.get("confirmPreauthorization"):n(O,u),d=u&&"number"==typeof u.value&&!!u.currency,g=b&&Object.keys(b).length>0,P=!m&&!p&&d&&g?o(O,b):null;return e(t,l(function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){a(e,t,r[t])})}return e}({},y),{disabled:y.disabled||"loading"===y.status,classNameModifiers:[...f,"pay"],label:p||j}),P&&e(c,{label:P}))};export{s as default,n as payAmountLabel};
2
2
  //# sourceMappingURL=PayButton.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PayButton.js","sources":["../../../../../src/components/internal/PayButton/PayButton.tsx"],"sourcesContent":["import { h } from 'preact';\nimport Button from '../Button';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ButtonProps } from '../Button/types';\nimport { payAmountLabel, secondaryAmountLabel } from './utils';\nimport { PaymentAmountExtended } from '../../../types/global-types';\nimport SecondaryButtonLabel from './components/SecondaryButtonLabel';\n\nexport interface PayButtonProps extends ButtonProps {\n /**\n * Class name modifiers will be used as: `adyen-checkout__image--${modifier}`\n */\n classNameModifiers?: string[];\n label?: string;\n amount: PaymentAmountExtended;\n secondaryAmount?: PaymentAmountExtended;\n status?: string;\n disabled?: boolean;\n icon?: string;\n onClick?(): void;\n}\n\nconst PayButton = ({ amount, secondaryAmount, classNameModifiers = [], label, ...props }: PayButtonProps) => {\n const { i18n } = useCoreContext();\n const isZeroAuth = amount && {}.hasOwnProperty.call(amount, 'value') && amount.value === 0;\n const defaultLabel = isZeroAuth ? i18n.get('confirmPreauthorization') : payAmountLabel(i18n, amount);\n\n /**\n * Show the secondaryLabel if:\n * - it's not zero auth, and\n * - we don't have a predefined label (i.e. redirect, qrcode, await based comps...), and\n * - we do have an amount object (merchant might not be passing this in order to not show the amount on the button), and\n * - we have a secondaryAmount object with some properties\n */\n const secondaryLabel =\n !isZeroAuth && !label && amount && secondaryAmount && Object.keys(secondaryAmount).length\n ? secondaryAmountLabel(i18n, secondaryAmount)\n : null;\n\n return (\n <Button\n {...props}\n disabled={props.disabled || props.status === 'loading'}\n classNameModifiers={[...classNameModifiers, 'pay']}\n label={label || defaultLabel}\n >\n {secondaryLabel && <SecondaryButtonLabel label={secondaryLabel} />}\n </Button>\n );\n};\n\nexport default PayButton;\nexport { payAmountLabel };\n"],"names":["PayButton","_param","amount","secondaryAmount","classNameModifiers","label","props","i18n","useCoreContext","isZeroAuth","hasOwnProperty","call","value","defaultLabel","get","payAmountLabel","secondaryLabel","Object","keys","length","secondaryAmountLabel","h","Button","disabled","status","SecondaryButtonLabel"],"mappings":"qoCAsBA,MAAMA,EAAYC,QAACC,OAAEA,EAAMC,gBAAEA,EAAeC,mBAAEA,EAAqB,GAAEC,MAAEA,GAAiCJ,EAAvBK,EAAAA,EAAAA,EAAAA,CAA5DJ,SAAQC,kBAAiBC,qBAAyBC,UACnE,MAAME,KAAEA,GAASC,IACXC,EAAaP,GAAU,CAAC,EAAEQ,eAAeC,KAAKT,EAAQ,UAA6B,IAAjBA,EAAOU,MACzEC,EAAeJ,EAAaF,EAAKO,IAAI,2BAA6BC,EAAeR,EAAML,GASvFc,GACDP,IAAeJ,GAASH,GAAUC,GAAmBc,OAAOC,KAAKf,GAAiBgB,OAC7EC,EAAqBb,EAAMJ,GAC3B,KAEV,OACIkB,EAACC,EAAAA,oUAAAA,CAAAA,CAAAA,EACOhB,GAAAA,CACJiB,SAAUjB,EAAMiB,UAA6B,YAAjBjB,EAAMkB,OAClCpB,mBAAoB,IAAIA,EAAoB,OAC5CC,MAAOA,GAASQ,IAEfG,GAAkBK,EAACI,EAAAA,CAAqBpB,MAAOW"}
1
+ {"version":3,"file":"PayButton.js","sources":["../../../../../src/components/internal/PayButton/PayButton.tsx"],"sourcesContent":["import { h } from 'preact';\nimport Button from '../Button';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport { ButtonProps } from '../Button/types';\nimport { payAmountLabel, secondaryAmountLabel } from './utils';\nimport { PaymentAmountExtended } from '../../../types/global-types';\nimport SecondaryButtonLabel from './components/SecondaryButtonLabel';\n\nexport interface PayButtonProps extends ButtonProps {\n /**\n * Class name modifiers will be used as: `adyen-checkout__image--${modifier}`\n */\n classNameModifiers?: string[];\n label?: string;\n amount?: PaymentAmountExtended;\n secondaryAmount?: PaymentAmountExtended;\n status?: string;\n disabled?: boolean;\n icon?: string;\n onClick?(): void;\n}\n\nconst PayButton = ({ amount, secondaryAmount, classNameModifiers = [], label, ...props }: PayButtonProps) => {\n const { i18n } = useCoreContext();\n const isZeroAuth = amount && {}.hasOwnProperty.call(amount, 'value') && amount.value === 0;\n const defaultLabel = isZeroAuth ? i18n.get('confirmPreauthorization') : payAmountLabel(i18n, amount);\n\n /**\n * Show the secondaryLabel if:\n * - it's not zero auth, and\n * - we don't have a predefined label (i.e. redirect, qrcode, await based comps...), and\n * - we do have an amount object (merchant might not be passing this in order to not show the amount on the button), and\n * - we have a secondaryAmount object with some properties\n */\n const hasValidAmount = amount && typeof amount.value === 'number' && !!amount.currency;\n const hasSecondaryAmount = secondaryAmount && Object.keys(secondaryAmount).length > 0;\n\n const secondaryLabel = !isZeroAuth && !label && hasValidAmount && hasSecondaryAmount ? secondaryAmountLabel(i18n, secondaryAmount) : null;\n\n return (\n <Button\n {...props}\n disabled={props.disabled || props.status === 'loading'}\n classNameModifiers={[...classNameModifiers, 'pay']}\n label={label || defaultLabel}\n >\n {secondaryLabel && <SecondaryButtonLabel label={secondaryLabel} />}\n </Button>\n );\n};\n\nexport default PayButton;\nexport { payAmountLabel };\n"],"names":["PayButton","_param","amount","secondaryAmount","classNameModifiers","label","props","i18n","useCoreContext","isZeroAuth","hasOwnProperty","call","value","defaultLabel","get","payAmountLabel","hasValidAmount","currency","hasSecondaryAmount","Object","keys","length","secondaryLabel","secondaryAmountLabel","h","Button","disabled","status","SecondaryButtonLabel"],"mappings":"qoCAsBA,MAAMA,EAAYC,QAACC,OAAEA,EAAMC,gBAAEA,EAAeC,mBAAEA,EAAqB,GAAEC,MAAEA,GAAiCJ,EAAvBK,EAAAA,EAAAA,EAAAA,CAA5DJ,SAAQC,kBAAiBC,qBAAyBC,UACnE,MAAME,KAAEA,GAASC,IACXC,EAAaP,GAAU,CAAC,EAAEQ,eAAeC,KAAKT,EAAQ,UAA6B,IAAjBA,EAAOU,MACzEC,EAAeJ,EAAaF,EAAKO,IAAI,2BAA6BC,EAAeR,EAAML,GASvFc,EAAiBd,GAAkC,iBAAjBA,EAAOU,SAAwBV,EAAOe,SACxEC,EAAqBf,GAAmBgB,OAAOC,KAAKjB,GAAiBkB,OAAS,EAE9EC,GAAkBb,IAAeJ,GAASW,GAAkBE,EAAqBK,EAAqBhB,EAAMJ,GAAmB,KAErI,OACIqB,EAACC,EAAAA,oUAAAA,CAAAA,CAAAA,EACOnB,GAAAA,CACJoB,SAAUpB,EAAMoB,UAA6B,YAAjBpB,EAAMqB,OAClCvB,mBAAoB,IAAIA,EAAoB,OAC5CC,MAAOA,GAASQ,IAEfS,GAAkBE,EAACI,EAAAA,CAAqBvB,MAAOiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"SecondaryButtonLabel.js","sources":["../../../../../../src/components/internal/PayButton/components/SecondaryButtonLabel.tsx"],"sourcesContent":["import { h } from 'preact';\nimport './SecondaryButtonLabel.scss';\n\nconst SecondaryButtonLabel = ({ label }) => {\n return <span className={'checkout-secondary-button__text'}>{label}</span>;\n};\n\nexport default SecondaryButtonLabel;\n"],"names":["SecondaryButtonLabel","label","h","span","className"],"mappings":"2EAGA,MAAMA,EAAuB,EAAGC,WACrBC,EAACC,OAAAA,CAAKC,UAAW,mCAAoCH"}
1
+ {"version":3,"file":"SecondaryButtonLabel.js","sources":["../../../../../../src/components/internal/PayButton/components/SecondaryButtonLabel.tsx"],"sourcesContent":["import { h } from 'preact';\n\nconst SecondaryButtonLabel = ({ label }) => {\n return <span className={'checkout-secondary-button__text'}>{label}</span>;\n};\n\nexport default SecondaryButtonLabel;\n"],"names":["SecondaryButtonLabel","label","h","span","className"],"mappings":"2EAEA,MAAMA,EAAuB,EAAGC,WACrBC,EAACC,OAAAA,CAAKC,UAAW,mCAAoCH"}
@@ -1,2 +1,2 @@
1
- import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import o from"../Countdown/index.js";import r from"../Button/Button.js";import s from"../Spinner/Spinner.js";import a from"../../../core/Services/payment-status.js";import{processResponse as i}from"../../../core/ProcessResponse/process-response.js";import{copyToClipboard as n}from"../../../utils/clipboard.js";import c from"../../../core/Errors/AdyenCheckoutError.js";import{useCoreContext as p}from"../../../core/Context/CoreProvider.js";import d from"../ContentSeparator/ContentSeparator.js";import l from"../../../core/Context/useImage.js";import{useA11yReporter as m}from"../../../core/Errors/useA11yReporter.js";import u from"../../../utils/useAutoFocus.js";import{ANALYTICS_QR_CODE_DOWNLOAD as h,ANALYTICS_DOWNLOAD_STR as _}from"../../../core/Analytics/constants.js";import{PREFIX as y}from"../Icon/constants.js";import{AnalyticsInfoEvent as g}from"../../../core/Analytics/AnalyticsInfoEvent.js";function f(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class k extends t{componentDidMount(){this.statusInterval()}componentWillUnmount(){clearTimeout(this.timeoutId)}pollStatus(t){clearTimeout(this.timeoutId),this.timeoutId=setTimeout(async()=>{const t=performance.now();await this.checkStatus();const e=performance.now();this.statusInterval(Math.round(e-t))},t)}render({amount:t,url:a,brandLogo:i,brandName:c,countdownTime:f,type:k,onActionHandled:v},{expired:q,completed:b,loading:C}){var w,N,I,T;const{i18n:j,loadingContext:S}=p(),x=l(),E=this.props.qrCodeData?`${S}utility/v1/barcode.png?type=qrCode&data=${this.props.qrCodeData}&clientKey=${this.props.clientKey}`:this.props.qrCodeImage,A=(t,o)=>{const r=j.get(o);return m(r),e("div",{className:"adyen-checkout__qr-loader adyen-checkout__qr-loader--result"},e("img",{className:"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result",src:x({imageFolder:"components/"})(t),alt:r}),e("div",{className:"adyen-checkout__qr-loader__subtitle"},r))};if(q)return A("error","error.subtitle.payment");if(b)return A("success","creditCard.success");if(C)return e("div",{className:"adyen-checkout__qr-loader"},i&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{alt:c,src:i,className:"adyen-checkout__qr-loader__brand-logo"})),e(s,null));const P=j.get(this.props.timeToPay).split("%@"),D=u(),R=this.props.classNameModifiers.map(t=>`adyen-checkout__qr-loader--${t}`);return e("div",{className:`adyen-checkout__qr-loader adyen-checkout__qr-loader--${k} ${R.join(" ")}`},i&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{src:i,alt:c,className:"adyen-checkout__qr-loader__brand-logo"})),t&&t.value&&t.currency&&e("div",{className:"adyen-checkout__qr-loader__payment_amount"},j.amount(t.value,t.currency)),a&&e("div",{className:"adyen-checkout__qr-loader__app-link"},this.props.redirectIntroduction&&e("div",{className:"adyen-checkout__qr-loader__subtitle"},j.get(this.props.redirectIntroduction)),e(r,{classNameModifiers:["qr-loader"],onClick:()=>this.redirectToApp(a),label:j.get(this.props.buttonLabel)}),e(d,null)),e("div",{ref:D,tabIndex:0,className:"adyen-checkout__qr-loader__subtitle"},"string"==typeof this.props.introduction?j.get(this.props.introduction):null===(w=(N=this.props).introduction)||void 0===w?void 0:w.call(N)),e("img",{src:E,alt:j.get("wechatpay.scanqrcode"),onLoad:()=>{null==v||v({componentType:this.props.type,actionDescription:"qr-code-loaded"})}}),e("div",{className:"adyen-checkout__qr-loader__progress"},e("span",{className:"adyen-checkout__qr-loader__percentage",style:{width:`${this.state.percentage}%`}})),e("div",{className:"adyen-checkout__qr-loader__countdown"},P[0]," ",e(o,{minutesFromNow:f,onTick:this.onTick,onCompleted:this.onTimeUp})," ",P[1]),this.props.instructions&&e("div",{className:"adyen-checkout__qr-loader__instructions"},"string"==typeof this.props.instructions?j.get(this.props.instructions):null===(I=(T=this.props).instructions)||void 0===I?void 0:I.call(T)),this.props.copyBtn&&e("div",{className:"adyen-checkout__qr-loader__actions"},e(r,{inline:!0,variant:"action",onClick:(t,{complete:e})=>{n(this.props.qrCodeData);const o=new g({type:_,target:h});this.props.onSubmitAnalytics(o),e()},icon:x({imageFolder:"components/"})(`${y}copy`),label:j.get("button.copy")})))}constructor(t){super(t),f(this,"timeoutId",void 0),f(this,"redirectToApp",t=>{window.location.assign(t)}),f(this,"statusInterval",(t=0)=>{if(this.state.expired||this.state.completed)return;this.setState(e=>({timePassed:e.timePassed+this.props.delay+t}));const e=this.state.timePassed>=this.props.throttleTime?this.props.throttledInterval:this.state.delay;this.pollStatus(e)}),f(this,"onTick",t=>{this.setState({percentage:t.percentage})}),f(this,"onTimeUp",()=>{this.setState({expired:!0}),clearTimeout(this.timeoutId),this.props.onError(new c("ERROR","Payment Expired"))}),f(this,"onComplete",t=>{clearTimeout(this.timeoutId),this.setState({completed:!0,loading:!1});const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)}),f(this,"onError",t=>{if(clearTimeout(this.timeoutId),this.setState({expired:!0,loading:!1}),t.props.payload){const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)}const e=new c("ERROR","error result with no payload in response");return this.props.onError(e)}),f(this,"checkStatus",()=>{const{paymentData:t,clientKey:e,loadingContext:o,throttledInterval:r}=this.props;return a(t,e,o,r).then(i).catch(t=>({type:"network-error",props:t})).then(t=>{switch(t.type){case"success":this.onComplete(t);break;case"error":this.onError(t);break;default:this.setState({loading:!1})}return t})}),this.state={buttonStatus:"default",completed:!1,delay:t.delay,expired:!1,loading:!0,percentage:100,timePassed:0}}}f(k,"defaultProps",{delay:2e3,countdownTime:15,onError:()=>{},onComplete:()=>{},throttleTime:6e4,classNameModifiers:[],throttledInterval:1e4,introduction:"wechatpay.scanqrcode",timeToPay:"wechatpay.timetopay",buttonLabel:"openApp"});export{k as default};
1
+ import{Component as t,createElement as e}from"../../../external/preact/dist/preact.js";import o from"../Countdown/index.js";import r from"../Button/Button.js";import s from"../Spinner/Spinner.js";import a from"../../../core/Services/payment-status.js";import{processResponse as i}from"../../../core/ProcessResponse/process-response.js";import{copyToClipboard as n}from"../../../utils/clipboard.js";import c from"../../../core/Errors/AdyenCheckoutError.js";import{useCoreContext as p}from"../../../core/Context/CoreProvider.js";import d from"../ContentSeparator/ContentSeparator.js";import l from"../../../core/Context/useImage.js";import{useA11yReporter as m}from"../../../core/Errors/useA11yReporter.js";import u from"../../../utils/useAutoFocus.js";import{ANALYTICS_QR_CODE_DOWNLOAD as h,ANALYTICS_DOWNLOAD_STR as _}from"../../../core/Analytics/constants.js";import{PREFIX as y}from"../Icon/constants.js";import{AnalyticsInfoEvent as g}from"../../../core/Analytics/AnalyticsInfoEvent.js";function f(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class k extends t{componentDidMount(){this.statusInterval()}componentWillUnmount(){clearTimeout(this.timeoutId)}pollStatus(t){clearTimeout(this.timeoutId),this.timeoutId=setTimeout(async()=>{const t=performance.now();await this.checkStatus();const e=performance.now();this.statusInterval(Math.round(e-t))},t)}render({amount:t,showAmount:a,url:i,brandLogo:c,brandName:f,countdownTime:k,type:v,onActionHandled:q},{expired:b,completed:w,loading:C}){var N,I,T,j;const{i18n:S,loadingContext:x}=p(),A=l(),E=this.props.qrCodeData?`${x}utility/v1/barcode.png?type=qrCode&data=${this.props.qrCodeData}&clientKey=${this.props.clientKey}`:this.props.qrCodeImage,P=(t,o)=>{const r=S.get(o);return m(r),e("div",{className:"adyen-checkout__qr-loader adyen-checkout__qr-loader--result"},e("img",{className:"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result",src:A({imageFolder:"components/"})(t),alt:r}),e("div",{className:"adyen-checkout__qr-loader__subtitle"},r))};if(b)return P("error","error.subtitle.payment");if(w)return P("success","creditCard.success");if(C)return e("div",{className:"adyen-checkout__qr-loader"},c&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{alt:f,src:c,className:"adyen-checkout__qr-loader__brand-logo"})),e(s,null));const D=S.get(this.props.timeToPay).split("%@"),R=u(),$=this.props.classNameModifiers.map(t=>`adyen-checkout__qr-loader--${t}`);return e("div",{className:`adyen-checkout__qr-loader adyen-checkout__qr-loader--${v} ${$.join(" ")}`},c&&e("div",{className:"adyen-checkout__qr-loader__brand-logo-wrapper"},e("img",{src:c,alt:f,className:"adyen-checkout__qr-loader__brand-logo"})),a&&t&&null!==t.value&&!!t.currency&&e("div",{className:"adyen-checkout__qr-loader__payment_amount"},S.amount(t.value,t.currency)),i&&e("div",{className:"adyen-checkout__qr-loader__app-link"},this.props.redirectIntroduction&&e("div",{className:"adyen-checkout__qr-loader__subtitle"},S.get(this.props.redirectIntroduction)),e(r,{classNameModifiers:["qr-loader"],onClick:()=>this.redirectToApp(i),label:S.get(this.props.buttonLabel)}),e(d,null)),e("div",{ref:R,tabIndex:0,className:"adyen-checkout__qr-loader__subtitle"},"string"==typeof this.props.introduction?S.get(this.props.introduction):null===(N=(I=this.props).introduction)||void 0===N?void 0:N.call(I)),e("img",{src:E,alt:S.get("wechatpay.scanqrcode"),onLoad:()=>{null==q||q({componentType:this.props.type,actionDescription:"qr-code-loaded"})}}),e("div",{className:"adyen-checkout__qr-loader__progress"},e("span",{className:"adyen-checkout__qr-loader__percentage",style:{width:`${this.state.percentage}%`}})),e("div",{className:"adyen-checkout__qr-loader__countdown"},D[0]," ",e(o,{minutesFromNow:k,onTick:this.onTick,onCompleted:this.onTimeUp})," ",D[1]),this.props.instructions&&e("div",{className:"adyen-checkout__qr-loader__instructions"},"string"==typeof this.props.instructions?S.get(this.props.instructions):null===(T=(j=this.props).instructions)||void 0===T?void 0:T.call(j)),this.props.copyBtn&&e("div",{className:"adyen-checkout__qr-loader__actions"},e(r,{inline:!0,variant:"action",onClick:(t,{complete:e})=>{n(this.props.qrCodeData);const o=new g({type:_,target:h});this.props.onSubmitAnalytics(o),e()},icon:A({imageFolder:"components/"})(`${y}copy`),label:S.get("button.copy")})))}constructor(t){super(t),f(this,"timeoutId",void 0),f(this,"redirectToApp",t=>{window.location.assign(t)}),f(this,"statusInterval",(t=0)=>{if(this.state.expired||this.state.completed)return;this.setState(e=>({timePassed:e.timePassed+this.props.delay+t}));const e=this.state.timePassed>=this.props.throttleTime?this.props.throttledInterval:this.state.delay;this.pollStatus(e)}),f(this,"onTick",t=>{this.setState({percentage:t.percentage})}),f(this,"onTimeUp",()=>{this.setState({expired:!0}),clearTimeout(this.timeoutId),this.props.onError(new c("ERROR","Payment Expired"))}),f(this,"onComplete",t=>{clearTimeout(this.timeoutId),this.setState({completed:!0,loading:!1});const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)}),f(this,"onError",t=>{if(clearTimeout(this.timeoutId),this.setState({expired:!0,loading:!1}),t.props.payload){const e={data:{details:{payload:t.props.payload},paymentData:this.props.paymentData}};this.props.onComplete(e,this)}const e=new c("ERROR","error result with no payload in response");return this.props.onError(e)}),f(this,"checkStatus",()=>{const{paymentData:t,clientKey:e,loadingContext:o,throttledInterval:r}=this.props;return a(t,e,o,r).then(i).catch(t=>({type:"network-error",props:t})).then(t=>{switch(t.type){case"success":this.onComplete(t);break;case"error":this.onError(t);break;default:this.setState({loading:!1})}return t})}),this.state={buttonStatus:"default",completed:!1,delay:t.delay,expired:!1,loading:!0,percentage:100,timePassed:0}}}f(k,"defaultProps",{delay:2e3,countdownTime:15,onError:()=>{},onComplete:()=>{},throttleTime:6e4,classNameModifiers:[],throttledInterval:1e4,introduction:"wechatpay.scanqrcode",timeToPay:"wechatpay.timetopay",buttonLabel:"openApp",showAmount:!0});export{k as default};
2
2
  //# sourceMappingURL=QRLoader.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"QRLoader.js","sources":["../../../../../src/components/internal/QRLoader/QRLoader.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport Countdown from '../Countdown';\nimport Button from '../Button';\nimport Spinner from '../Spinner';\nimport checkPaymentStatus from '../../../core/Services/payment-status';\nimport processResponse from '../../../core/ProcessResponse';\n\nimport './QRLoader.scss';\nimport { QRLoaderProps, QRLoaderState } from './types';\nimport copyToClipboard from '../../../utils/clipboard';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport ContentSeparator from '../ContentSeparator';\nimport { StatusObject } from '../Await/types';\nimport useImage from '../../../core/Context/useImage';\nimport { useA11yReporter } from '../../../core/Errors/useA11yReporter';\nimport useAutoFocus from '../../../utils/useAutoFocus';\nimport { ANALYTICS_DOWNLOAD_STR, ANALYTICS_QR_CODE_DOWNLOAD } from '../../../core/Analytics/constants';\nimport { PREFIX } from '../Icon/constants';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst QRCODE_URL = 'utility/v1/barcode.png?type=qrCode&data=';\n\nclass QRLoader extends Component<QRLoaderProps, QRLoaderState> {\n private timeoutId;\n\n constructor(props) {\n super(props);\n\n this.state = {\n buttonStatus: 'default',\n completed: false,\n delay: props.delay,\n expired: false,\n loading: true,\n percentage: 100,\n timePassed: 0\n };\n }\n\n public static defaultProps = {\n delay: 2000,\n countdownTime: 15,\n onError: () => {},\n onComplete: () => {},\n throttleTime: 60000,\n classNameModifiers: [],\n throttledInterval: 10000,\n introduction: 'wechatpay.scanqrcode',\n timeToPay: 'wechatpay.timetopay',\n buttonLabel: 'openApp'\n };\n\n componentDidMount() {\n this.statusInterval();\n }\n\n componentWillUnmount() {\n clearTimeout(this.timeoutId);\n }\n\n public redirectToApp = (url: string | URL) => {\n window.location.assign(url);\n };\n\n // Retry until getting a complete response from the server, or it times out\n public statusInterval = (responseTime = 0) => {\n // If we are already in the final statuses, do not poll!\n if (this.state.expired || this.state.completed) return;\n\n this.setState(previous => ({ timePassed: previous.timePassed + this.props.delay + responseTime }));\n // Changes interval time to 10 seconds after 1 minute (60 seconds)\n const newDelay = this.state.timePassed >= this.props.throttleTime ? this.props.throttledInterval : this.state.delay;\n this.pollStatus(newDelay);\n };\n\n private pollStatus(delay: number) {\n clearTimeout(this.timeoutId);\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.timeoutId = setTimeout(async () => {\n // Wait for previous status call to finish.\n // Also taking the server response time into the consideration to calculate timePassed.\n const start = performance.now();\n await this.checkStatus();\n const end = performance.now();\n this.statusInterval(Math.round(end - start));\n }, delay);\n }\n\n private onTick = (time): void => {\n this.setState({ percentage: time.percentage });\n };\n\n private onTimeUp = (): void => {\n this.setState({ expired: true });\n clearTimeout(this.timeoutId);\n this.props.onError(new AdyenCheckoutError('ERROR', 'Payment Expired'));\n };\n\n private onComplete = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ completed: true, loading: false });\n\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n\n this.props.onComplete(state, this);\n };\n\n private onError = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ expired: true, loading: false });\n\n if (status.props.payload) {\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n this.props.onComplete(state, this);\n }\n\n const error = new AdyenCheckoutError('ERROR', 'error result with no payload in response');\n return this.props.onError(error);\n };\n\n private checkStatus = () => {\n const { paymentData, clientKey, loadingContext, throttledInterval } = this.props;\n\n return checkPaymentStatus(paymentData, clientKey, loadingContext, throttledInterval)\n .then(processResponse)\n .catch(response => ({ type: 'network-error', props: response }))\n .then((status: StatusObject) => {\n switch (status.type) {\n case 'success':\n this.onComplete(status);\n break;\n case 'error':\n this.onError(status);\n break;\n default:\n this.setState({ loading: false });\n }\n return status;\n });\n };\n\n render({ amount, url, brandLogo, brandName, countdownTime, type, onActionHandled }: QRLoaderProps, { expired, completed, loading }) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n\n const qrCodeImage = this.props.qrCodeData\n ? `${loadingContext}${QRCODE_URL}${this.props.qrCodeData}&clientKey=${this.props.clientKey}`\n : this.props.qrCodeImage;\n\n const finalState = (image, message) => {\n const status = i18n.get(message);\n useA11yReporter(status);\n return (\n <div className=\"adyen-checkout__qr-loader adyen-checkout__qr-loader--result\">\n <img\n className=\"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result\"\n src={getImage({ imageFolder: 'components/' })(image)}\n alt={status}\n />\n <div className=\"adyen-checkout__qr-loader__subtitle\">{status}</div>\n </div>\n );\n };\n\n if (expired) {\n return finalState('error', 'error.subtitle.payment');\n }\n\n if (completed) {\n return finalState('success', 'creditCard.success');\n }\n\n if (loading) {\n return (\n <div className=\"adyen-checkout__qr-loader\">\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img alt={brandName} src={brandLogo} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n <Spinner />\n </div>\n );\n }\n\n const timeToPayString = i18n.get(this.props.timeToPay).split('%@');\n\n const qrSubtitleRef = useAutoFocus();\n const classnames = this.props.classNameModifiers.map(m => `adyen-checkout__qr-loader--${m}`);\n\n return (\n <div className={`adyen-checkout__qr-loader adyen-checkout__qr-loader--${type} ${classnames.join(' ')}`}>\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img src={brandLogo} alt={brandName} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n\n {amount && amount.value && amount.currency && (\n <div className=\"adyen-checkout__qr-loader__payment_amount\">{i18n.amount(amount.value, amount.currency)}</div>\n )}\n\n {url && (\n <div className=\"adyen-checkout__qr-loader__app-link\">\n {this.props.redirectIntroduction && (\n <div className=\"adyen-checkout__qr-loader__subtitle\">{i18n.get(this.props.redirectIntroduction)}</div>\n )}\n <Button classNameModifiers={['qr-loader']} onClick={() => this.redirectToApp(url)} label={i18n.get(this.props.buttonLabel)} />\n <ContentSeparator />\n </div>\n )}\n\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}\n <div ref={qrSubtitleRef} tabIndex={0} className=\"adyen-checkout__qr-loader__subtitle\">\n {typeof this.props.introduction === 'string' ? i18n.get(this.props.introduction) : this.props.introduction?.()}\n </div>\n\n <img\n src={qrCodeImage}\n alt={i18n.get('wechatpay.scanqrcode')}\n onLoad={() => {\n onActionHandled?.({\n componentType: this.props.type,\n actionDescription: 'qr-code-loaded'\n });\n }}\n />\n\n <div className=\"adyen-checkout__qr-loader__progress\">\n <span className=\"adyen-checkout__qr-loader__percentage\" style={{ width: `${this.state.percentage}%` }} />\n </div>\n\n <div className=\"adyen-checkout__qr-loader__countdown\">\n {timeToPayString[0]}&nbsp;\n <Countdown minutesFromNow={countdownTime} onTick={this.onTick} onCompleted={this.onTimeUp} />\n &nbsp;{timeToPayString[1]}\n </div>\n\n {this.props.instructions && (\n <div className=\"adyen-checkout__qr-loader__instructions\">\n {typeof this.props.instructions === 'string' ? i18n.get(this.props.instructions) : this.props.instructions?.()}\n </div>\n )}\n\n {this.props.copyBtn && (\n <div className=\"adyen-checkout__qr-loader__actions\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n void copyToClipboard(this.props.qrCodeData);\n\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DOWNLOAD_STR,\n target: ANALYTICS_QR_CODE_DOWNLOAD\n });\n this.props.onSubmitAnalytics(event);\n\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </div>\n )}\n </div>\n );\n }\n}\n\nexport default QRLoader;\n"],"names":["QRLoader","Component","componentDidMount","this","statusInterval","componentWillUnmount","clearTimeout","timeoutId","pollStatus","delay","setTimeout","async","start","performance","now","checkStatus","end","Math","round","render","amount","url","brandLogo","brandName","countdownTime","type","onActionHandled","expired","completed","loading","_this_props_introduction","_this_props","_this_props_instructions","_this_props1","i18n","loadingContext","useCoreContext","getImage","useImage","qrCodeImage","props","qrCodeData","clientKey","finalState","image","message","status","get","useA11yReporter","h","div","className","img","src","imageFolder","alt","Spinner","timeToPayString","timeToPay","split","qrSubtitleRef","useAutoFocus","classnames","classNameModifiers","map","m","join","value","currency","redirectIntroduction","Button","onClick","redirectToApp","label","buttonLabel","ContentSeparator","ref","tabIndex","introduction","call","onLoad","componentType","actionDescription","span","style","width","state","percentage","Countdown","minutesFromNow","onTick","onCompleted","onTimeUp","instructions","copyBtn","inline","variant","e","complete","copyToClipboard","event","AnalyticsInfoEvent","ANALYTICS_DOWNLOAD_STR","target","ANALYTICS_QR_CODE_DOWNLOAD","onSubmitAnalytics","icon","PREFIX","constructor","super","_define_property","window","location","assign","responseTime","setState","previous","timePassed","newDelay","throttleTime","throttledInterval","time","onError","AdyenCheckoutError","onComplete","data","details","payload","paymentData","error","checkPaymentStatus","then","processResponse","catch","response","buttonStatus","defaultProps"],"mappings":"slCAuBA,MAAMA,UAAiBC,EA8BnBC,iBAAAA,GACIC,KAAKC,gBACT,CAEAC,oBAAAA,GACIC,aAAaH,KAAKI,UACtB,CAiBQC,UAAAA,CAAWC,GACfH,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+B,EAAM/B,MACbkB,SAAS,EACTE,SAAS,EACT0D,WAAY,IACZ8B,WAAY,EAEpB,EAEAP,EAjBE9G,EAiBYwI,eAAe,CACzB/H,MAAO,IACPe,cAAe,GACfkG,QAAS,OACTE,WAAY,OACZL,aAAc,IACdxD,mBAAoB,GACpByD,kBAAmB,IACnB1C,aAAc,uBACdpB,UAAW,sBACXgB,YAAa"}
1
+ {"version":3,"file":"QRLoader.js","sources":["../../../../../src/components/internal/QRLoader/QRLoader.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport Countdown from '../Countdown';\nimport Button from '../Button';\nimport Spinner from '../Spinner';\nimport checkPaymentStatus from '../../../core/Services/payment-status';\nimport processResponse from '../../../core/ProcessResponse';\n\nimport './QRLoader.scss';\nimport { QRLoaderProps, QRLoaderState } from './types';\nimport copyToClipboard from '../../../utils/clipboard';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport ContentSeparator from '../ContentSeparator';\nimport { StatusObject } from '../Await/types';\nimport useImage from '../../../core/Context/useImage';\nimport { useA11yReporter } from '../../../core/Errors/useA11yReporter';\nimport useAutoFocus from '../../../utils/useAutoFocus';\nimport { ANALYTICS_DOWNLOAD_STR, ANALYTICS_QR_CODE_DOWNLOAD } from '../../../core/Analytics/constants';\nimport { PREFIX } from '../Icon/constants';\nimport { AnalyticsInfoEvent } from '../../../core/Analytics/AnalyticsInfoEvent';\n\nconst QRCODE_URL = 'utility/v1/barcode.png?type=qrCode&data=';\n\nclass QRLoader extends Component<QRLoaderProps, QRLoaderState> {\n private timeoutId;\n\n constructor(props) {\n super(props);\n\n this.state = {\n buttonStatus: 'default',\n completed: false,\n delay: props.delay,\n expired: false,\n loading: true,\n percentage: 100,\n timePassed: 0\n };\n }\n\n public static defaultProps = {\n delay: 2000,\n countdownTime: 15,\n onError: () => {},\n onComplete: () => {},\n throttleTime: 60000,\n classNameModifiers: [],\n throttledInterval: 10000,\n introduction: 'wechatpay.scanqrcode',\n timeToPay: 'wechatpay.timetopay',\n buttonLabel: 'openApp',\n showAmount: true\n };\n\n componentDidMount() {\n this.statusInterval();\n }\n\n componentWillUnmount() {\n clearTimeout(this.timeoutId);\n }\n\n public redirectToApp = (url: string | URL) => {\n window.location.assign(url);\n };\n\n // Retry until getting a complete response from the server, or it times out\n public statusInterval = (responseTime = 0) => {\n // If we are already in the final statuses, do not poll!\n if (this.state.expired || this.state.completed) return;\n\n this.setState(previous => ({ timePassed: previous.timePassed + this.props.delay + responseTime }));\n // Changes interval time to 10 seconds after 1 minute (60 seconds)\n const newDelay = this.state.timePassed >= this.props.throttleTime ? this.props.throttledInterval : this.state.delay;\n this.pollStatus(newDelay);\n };\n\n private pollStatus(delay: number) {\n clearTimeout(this.timeoutId);\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.timeoutId = setTimeout(async () => {\n // Wait for previous status call to finish.\n // Also taking the server response time into the consideration to calculate timePassed.\n const start = performance.now();\n await this.checkStatus();\n const end = performance.now();\n this.statusInterval(Math.round(end - start));\n }, delay);\n }\n\n private onTick = (time): void => {\n this.setState({ percentage: time.percentage });\n };\n\n private onTimeUp = (): void => {\n this.setState({ expired: true });\n clearTimeout(this.timeoutId);\n this.props.onError(new AdyenCheckoutError('ERROR', 'Payment Expired'));\n };\n\n private onComplete = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ completed: true, loading: false });\n\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n\n this.props.onComplete(state, this);\n };\n\n private onError = (status: StatusObject): void => {\n clearTimeout(this.timeoutId);\n this.setState({ expired: true, loading: false });\n\n if (status.props.payload) {\n const state = {\n data: {\n details: { payload: status.props.payload },\n paymentData: this.props.paymentData\n }\n };\n this.props.onComplete(state, this);\n }\n\n const error = new AdyenCheckoutError('ERROR', 'error result with no payload in response');\n return this.props.onError(error);\n };\n\n private checkStatus = () => {\n const { paymentData, clientKey, loadingContext, throttledInterval } = this.props;\n\n return checkPaymentStatus(paymentData, clientKey, loadingContext, throttledInterval)\n .then(processResponse)\n .catch(response => ({ type: 'network-error', props: response }))\n .then((status: StatusObject) => {\n switch (status.type) {\n case 'success':\n this.onComplete(status);\n break;\n case 'error':\n this.onError(status);\n break;\n default:\n this.setState({ loading: false });\n }\n return status;\n });\n };\n\n render({ amount, showAmount, url, brandLogo, brandName, countdownTime, type, onActionHandled }: QRLoaderProps, { expired, completed, loading }) {\n const { i18n, loadingContext } = useCoreContext();\n const getImage = useImage();\n\n const qrCodeImage = this.props.qrCodeData\n ? `${loadingContext}${QRCODE_URL}${this.props.qrCodeData}&clientKey=${this.props.clientKey}`\n : this.props.qrCodeImage;\n\n const finalState = (image, message) => {\n const status = i18n.get(message);\n useA11yReporter(status);\n return (\n <div className=\"adyen-checkout__qr-loader adyen-checkout__qr-loader--result\">\n <img\n className=\"adyen-checkout__qr-loader__icon adyen-checkout__qr-loader__icon--result\"\n src={getImage({ imageFolder: 'components/' })(image)}\n alt={status}\n />\n <div className=\"adyen-checkout__qr-loader__subtitle\">{status}</div>\n </div>\n );\n };\n\n if (expired) {\n return finalState('error', 'error.subtitle.payment');\n }\n\n if (completed) {\n return finalState('success', 'creditCard.success');\n }\n\n if (loading) {\n return (\n <div className=\"adyen-checkout__qr-loader\">\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img alt={brandName} src={brandLogo} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n <Spinner />\n </div>\n );\n }\n\n const timeToPayString = i18n.get(this.props.timeToPay).split('%@');\n\n const qrSubtitleRef = useAutoFocus();\n const classnames = this.props.classNameModifiers.map(m => `adyen-checkout__qr-loader--${m}`);\n\n return (\n <div className={`adyen-checkout__qr-loader adyen-checkout__qr-loader--${type} ${classnames.join(' ')}`}>\n {brandLogo && (\n <div className=\"adyen-checkout__qr-loader__brand-logo-wrapper\">\n <img src={brandLogo} alt={brandName} className=\"adyen-checkout__qr-loader__brand-logo\" />\n </div>\n )}\n\n {showAmount && amount && amount.value !== null && !!amount.currency && (\n <div className=\"adyen-checkout__qr-loader__payment_amount\">{i18n.amount(amount.value, amount.currency)}</div>\n )}\n\n {url && (\n <div className=\"adyen-checkout__qr-loader__app-link\">\n {this.props.redirectIntroduction && (\n <div className=\"adyen-checkout__qr-loader__subtitle\">{i18n.get(this.props.redirectIntroduction)}</div>\n )}\n <Button classNameModifiers={['qr-loader']} onClick={() => this.redirectToApp(url)} label={i18n.get(this.props.buttonLabel)} />\n <ContentSeparator />\n </div>\n )}\n\n {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}\n <div ref={qrSubtitleRef} tabIndex={0} className=\"adyen-checkout__qr-loader__subtitle\">\n {typeof this.props.introduction === 'string' ? i18n.get(this.props.introduction) : this.props.introduction?.()}\n </div>\n\n <img\n src={qrCodeImage}\n alt={i18n.get('wechatpay.scanqrcode')}\n onLoad={() => {\n onActionHandled?.({\n componentType: this.props.type,\n actionDescription: 'qr-code-loaded'\n });\n }}\n />\n\n <div className=\"adyen-checkout__qr-loader__progress\">\n <span className=\"adyen-checkout__qr-loader__percentage\" style={{ width: `${this.state.percentage}%` }} />\n </div>\n\n <div className=\"adyen-checkout__qr-loader__countdown\">\n {timeToPayString[0]}&nbsp;\n <Countdown minutesFromNow={countdownTime} onTick={this.onTick} onCompleted={this.onTimeUp} />\n &nbsp;{timeToPayString[1]}\n </div>\n\n {this.props.instructions && (\n <div className=\"adyen-checkout__qr-loader__instructions\">\n {typeof this.props.instructions === 'string' ? i18n.get(this.props.instructions) : this.props.instructions?.()}\n </div>\n )}\n\n {this.props.copyBtn && (\n <div className=\"adyen-checkout__qr-loader__actions\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n void copyToClipboard(this.props.qrCodeData);\n\n const event = new AnalyticsInfoEvent({\n type: ANALYTICS_DOWNLOAD_STR,\n target: ANALYTICS_QR_CODE_DOWNLOAD\n });\n this.props.onSubmitAnalytics(event);\n\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </div>\n )}\n </div>\n );\n }\n}\n\nexport default QRLoader;\n"],"names":["QRLoader","Component","componentDidMount","this","statusInterval","componentWillUnmount","clearTimeout","timeoutId","pollStatus","delay","setTimeout","async","start","performance","now","checkStatus","end","Math","round","render","amount","showAmount","url","brandLogo","brandName","countdownTime","type","onActionHandled","expired","completed","loading","_this_props_introduction","_this_props","_this_props_instructions","_this_props1","i18n","loadingContext","useCoreContext","getImage","useImage","qrCodeImage","props","qrCodeData","clientKey","finalState","image","message","status","get","useA11yReporter","h","div","className","img","src","imageFolder","alt","Spinner","timeToPayString","timeToPay","split","qrSubtitleRef","useAutoFocus","classnames","classNameModifiers","map","m","join","value","currency","redirectIntroduction","Button","onClick","redirectToApp","label","buttonLabel","ContentSeparator","ref","tabIndex","introduction","call","onLoad","componentType","actionDescription","span","style","width","state","percentage","Countdown","minutesFromNow","onTick","onCompleted","onTimeUp","instructions","copyBtn","inline","variant","e","complete","copyToClipboard","event","AnalyticsInfoEvent","ANALYTICS_DOWNLOAD_STR","target","ANALYTICS_QR_CODE_DOWNLOAD","onSubmitAnalytics","icon","PREFIX","constructor","super","_define_property","window","location","assign","responseTime","setState","previous","timePassed","newDelay","throttleTime","throttledInterval","time","onError","AdyenCheckoutError","onComplete","data","details","payload","paymentData","error","checkPaymentStatus","then","processResponse","catch","response","buttonStatus","defaultProps"],"mappings":"slCAuBA,MAAMA,UAAiBC,EA+BnBC,iBAAAA,GACIC,KAAKC,gBACT,CAEAC,oBAAAA,GACIC,aAAaH,KAAKI,UACtB,CAiBQC,UAAAA,CAAWC,GACfH,aAAaH,KAAKI,WAGlBJ,KAAKI,UAAYG,WAAWC,UAGxB,MAAMC,EAAQC,YAAYC,YACpBX,KAAKY,cACX,MAAMC,EAAMH,YAAYC,MACxBX,KAAKC,eAAea,KAAKC,MAAMF,EAAMJ,K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e,GACfkG,QAAS,OACTE,WAAY,OACZL,aAAc,IACdxD,mBAAoB,GACpByD,kBAAmB,IACnB1C,aAAc,uBACdpB,UAAW,sBACXgB,YAAa,UACbtD,YAAY"}
@@ -1,2 +1,2 @@
1
- function d(d){const[e,a]=d;return{dualBrandSelectElements:[{id:e.brand,brandObject:e},{id:a.brand,brandObject:a}],selectedBrandValue:e.brand,leadBrand:e}}export{d as default};
1
+ function d(d,e){const[a,n]=d;return{dualBrandSelectElements:[{id:a.brand,brandObject:a},{id:n.brand,brandObject:n}],selectedBrandValue:e?a.brand:"",leadBrand:a}}export{d as default};
2
2
  //# sourceMappingURL=createCardVariantSwitcher.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"createCardVariantSwitcher.js","sources":["../../../../../../src/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.ts"],"sourcesContent":["import { BrandObject, DualBrandSelectElement } from '../../../Card/types';\n\n/**\n * Creates an object used for setting state - that will trigger the rendering of a select element to allow a choice between 2 different card variants\n * @param brandObjArr - array containing 2 card brands objects\n */\nexport default function createCardVariantSwitcher(brandObjArr: BrandObject[]) {\n const [leadBrand, subBrand] = brandObjArr;\n\n return {\n dualBrandSelectElements: [\n { id: leadBrand.brand, brandObject: leadBrand },\n { id: subBrand.brand, brandObject: subBrand }\n ] as DualBrandSelectElement[],\n selectedBrandValue: leadBrand.brand, // set to leadBrand.brand if an initial selection is to be made; else set to empty string\n leadBrand\n };\n}\n"],"names":["createCardVariantSwitcher","brandObjArr","leadBrand","subBrand","dualBrandSelectElements","id","brand","brandObject","selectedBrandValue"],"mappings":"AAMe,SAASA,EAA0BC,GAC9C,MAAOC,EAAWC,GAAYF,EAE9B,MAAO,CACHG,wBAAyB,CACrB,CAAEC,GAAIH,EAAUI,MAAOC,YAAaL,GACpC,CAAEG,GAAIF,EAASG,MAAOC,YAAaJ,IAEvCK,mBAAoBN,EAAUI,MAC9BJ,YAER"}
1
+ {"version":3,"file":"createCardVariantSwitcher.js","sources":["../../../../../../src/components/internal/SecuredFields/binLookup/createCardVariantSwitcher.ts"],"sourcesContent":["import { BrandObject, DualBrandSelectElement } from '../../../Card/types';\n\n/**\n * Creates an object used for setting state - that will trigger the rendering of a select element to allow a choice between 2 different card variants\n * @param brandObjArr - array containing 2 card brands objects\n */\nexport default function createCardVariantSwitcher(brandObjArr: BrandObject[], preselectBrand: boolean) {\n const [leadBrand, subBrand] = brandObjArr;\n\n return {\n dualBrandSelectElements: [\n { id: leadBrand.brand, brandObject: leadBrand },\n { id: subBrand.brand, brandObject: subBrand }\n ] as DualBrandSelectElement[],\n selectedBrandValue: preselectBrand ? leadBrand.brand : '', // set to leadBrand.brand if an initial selection is to be made; else set to empty string\n leadBrand\n };\n}\n"],"names":["createCardVariantSwitcher","brandObjArr","preselectBrand","leadBrand","subBrand","dualBrandSelectElements","id","brand","brandObject","selectedBrandValue"],"mappings":"AAMe,SAASA,EAA0BC,EAA4BC,GAC1E,MAAOC,EAAWC,GAAYH,EAE9B,MAAO,CACHI,wBAAyB,CACrB,CAAEC,GAAIH,EAAUI,MAAOC,YAAaL,GACpC,CAAEG,GAAIF,EAASG,MAAOC,YAAaJ,IAEvCK,mBAAoBP,EAAiBC,EAAUI,MAAQ,GACvDJ,YAER"}
@@ -1,2 +1,2 @@
1
- import e from"./createCardVariantSwitcher.js";import{BRAND_ICON_UI_EXCLUSION_LIST as n}from"../lib/constants.js";function t(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}const r=(e,n)=>e.reduce((e,t)=>e||n.includes(t.brand),!1),o=e=>e.map(e=>function(e){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(n){t(e,n,r[n])})}return e}({},e)),s=(e,n="mc",t="visa")=>{const r=o(e);return r[0].brand!==n&&r[0].brand!==t&&r.reverse(),r.length=1,r};function u(t,u,a,c={}){const{type:d,cvcPolicy:i}=t,{sfp:l}=u,{dualBrandSelectElements:p,setDualBrandSelectElements:g,setSelectedBrandValue:b,issuingCountryCode:B,setIssuingCountryCode:f}=a;return{processBinLookup:(t,u)=>{var a;const p=(null==t?void 0:t.issuingCountryCode)?t.issuingCountryCode.toLowerCase():null;if(f(p),!t||!Object.keys(t).length){g([]),b("");const e=u&&"card"!==d?d:null;return l.current.processBinLookupResponse(t,{brand:e,cvcPolicy:i}),void(c.current=0)}if(null===(a=t.supportedBrands)||void 0===a?void 0:a.length){const u=r(t.supportedBrands,n),a=u?s(t.supportedBrands):o(t.supportedBrands);if(a.length>1){const n=e(a);g(n.dualBrandSelectElements),b(n.selectedBrandValue),l.current.processBinLookupResponse({issuingCountryCode:t.issuingCountryCode,supportedBrands:[n.leadBrand]}),n.leadBrand.panLength>0&&(c.current=n.leadBrand.panLength)}else g([]),b(""),u||b(a[0].brand),l.current.processBinLookupResponse({issuingCountryCode:t.issuingCountryCode,supportedBrands:a}),a[0].panLength>0&&(c.current=a[0].panLength)}},handleDualBrandSelection:e=>{let n=e;if(e instanceof Event){const t=e.target;n=t.getAttribute("data-value")||t.getAttribute("value")}let t=[];n&&(t=p.reduce((e,t)=>(t.brandObject.brand===n&&e.push(t.brandObject),e),[]),t.length&&(b(n),l.current.processBinLookupResponse({issuingCountryCode:B,supportedBrands:t,isDualBrandSelection:!0})))}}}export{o as cloneBrandsArr,r as containsExcludedBrand,u as default,s as removeExcludedBrand};
1
+ import e from"./createCardVariantSwitcher.js";import{BRAND_ICON_UI_EXCLUSION_LIST as n}from"../lib/constants.js";import{mustHandleDualBrandingAccordingToEURegulations as r}from"../../../Card/components/CardInput/utils.js";import{DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM as t}from"../../../Card/Card.js";function o(e,n,r){return n in e?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,e}const s=(e,n)=>e.reduce((e,r)=>e||n.includes(r.brand),!1),u=e=>e.map(e=>function(e){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{},t=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),t.forEach(function(n){o(e,n,r[n])})}return e}({},e)),a=(e,n="mc",r="visa")=>{const t=u(e);return t[0].brand!==n&&t[0].brand!==r&&t.reverse(),t.length=1,t};function d(o,d,c,i={}){const{type:l,cvcPolicy:p}=o,{sfp:b}=d,{dualBrandSelectElements:g,setDualBrandSelectElements:C,setSelectedBrandValue:f,issuingCountryCode:B,setIssuingCountryCode:y}=c;return{processBinLookup:(o,d)=>{var c;const g=(null==o?void 0:o.issuingCountryCode)?o.issuingCountryCode.toLowerCase():null;if(y(g),!o||!Object.keys(o).length){C([]),f("");const e=d&&"card"!==l?l:null;return b.current.processBinLookupResponse(o,{brand:e,cvcPolicy:p}),void(i.current=0)}if(null===(c=o.supportedBrands)||void 0===c?void 0:c.length){const d=s(o.supportedBrands,n),c=d?a(o.supportedBrands):u(o.supportedBrands);if(c.length>1){const n=r(t,c,"brand"),s=e(c,n);C(s.dualBrandSelectElements),f(s.selectedBrandValue),b.current.processBinLookupResponse({issuingCountryCode:o.issuingCountryCode,supportedBrands:[s.leadBrand]}),s.leadBrand.panLength>0&&(i.current=s.leadBrand.panLength)}else C([]),f(""),d||f(c[0].brand),b.current.processBinLookupResponse({issuingCountryCode:o.issuingCountryCode,supportedBrands:c}),c[0].panLength>0&&(i.current=c[0].panLength)}},handleDualBrandSelection:e=>{let n=e;if(e instanceof Event){const r=e.target;n=r.getAttribute("data-value")||r.getAttribute("value")}let r=[];n&&(r=g.reduce((e,r)=>(r.brandObject.brand===n&&e.push(r.brandObject),e),[]),r.length&&(f(n),b.current.processBinLookupResponse({issuingCountryCode:B,supportedBrands:r,isDualBrandSelection:!0})))}}}export{u as cloneBrandsArr,s as containsExcludedBrand,d as default,a as removeExcludedBrand};
2
2
  //# sourceMappingURL=extensions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"extensions.js","sources":["../../../../../../src/components/internal/SecuredFields/binLookup/extensions.ts"],"sourcesContent":["import { SingleBrandResetObject } from '../SFP/types';\nimport { BrandObject } from '../../../Card/types';\nimport createCardVariantSwitcher from './createCardVariantSwitcher';\nimport { BRAND_ICON_UI_EXCLUSION_LIST } from '../lib/constants';\n\n// Externally testable utils\nexport const containsExcludedBrand = (brandsArr: BrandObject[], excludedBrands: string[]): boolean => {\n return brandsArr.reduce((acc, brandObj) => acc || excludedBrands.includes(brandObj.brand), false);\n};\n\nexport const cloneBrandsArr = (brandsArr: BrandObject[]): BrandObject[] => brandsArr.map(item => ({ ...item }));\n\nexport const removeExcludedBrand = (brandsArr: BrandObject[], mainBrand1 = 'mc', mainBrand2 = 'visa'): BrandObject[] => {\n const clonedBrands: BrandObject[] = cloneBrandsArr(brandsArr);\n\n if (clonedBrands[0].brand !== mainBrand1 && clonedBrands[0].brand !== mainBrand2) clonedBrands.reverse();\n clonedBrands.length = 1;\n return clonedBrands;\n};\n// --\n\nexport default function extensions(props, refs, states, hasPanLengthRef: Partial<{ current }> = {}) {\n // Destructure props, refs and state hooks\n const { type, cvcPolicy } = props;\n const { sfp } = refs;\n const { dualBrandSelectElements, setDualBrandSelectElements, setSelectedBrandValue, issuingCountryCode, setIssuingCountryCode } = states;\n\n return {\n /**\n * Handle the binLookup response object generated in triggerBinLookup and process it in relation to the CardInput and it's sub-components.\n * e.g. we might need to add/remove additional markup (a selector for brands), and inform SFP of the issuingCountryCode & detected brand(s).\n *\n * @param binLookupResponse -\n * @param isReset -\n */\n processBinLookup: (binLookupResponse, isReset) => {\n const issuingCode = binLookupResponse?.issuingCountryCode ? binLookupResponse.issuingCountryCode.toLowerCase() : null;\n setIssuingCountryCode(issuingCode);\n\n // Reset UI\n if (!binLookupResponse || !Object.keys(binLookupResponse).length) {\n setDualBrandSelectElements([]);\n setSelectedBrandValue('');\n\n // If /binLookup has 'reset' then for a generic card the internal regex will kick in to show the right brand icon - so set to null\n // However for a single-branded card we need to pass the \"base\" type so the brand logo is reset - so set to type\n const brandToReset = isReset && type !== 'card' ? type : null;\n\n sfp.current.processBinLookupResponse(binLookupResponse, {\n brand: brandToReset,\n cvcPolicy: cvcPolicy // undefined except for Bancontact\n } as SingleBrandResetObject);\n\n // Reset storage var\n hasPanLengthRef.current = 0;\n return;\n }\n\n // RESULT: binLookup has found a result so proceed accordingly\n if (binLookupResponse.supportedBrands?.length) {\n const hasExcludedBrand: boolean = containsExcludedBrand(binLookupResponse.supportedBrands, BRAND_ICON_UI_EXCLUSION_LIST);\n\n const supportedBrands: BrandObject[] = hasExcludedBrand\n ? removeExcludedBrand(binLookupResponse.supportedBrands)\n : cloneBrandsArr(binLookupResponse.supportedBrands);\n\n // 1) Multiple options found - add to the UI & inform SFP\n if (supportedBrands.length > 1) {\n // --\n const switcherObj = createCardVariantSwitcher(supportedBrands);\n\n // Set properties on state to trigger the dual branding icons in the UI\n setDualBrandSelectElements(switcherObj.dualBrandSelectElements);\n setSelectedBrandValue(switcherObj.selectedBrandValue); // initially this value from switcherObj will be ''\n\n // Pass an object through to SFP\n sfp.current.processBinLookupResponse({\n issuingCountryCode: binLookupResponse.issuingCountryCode,\n supportedBrands: [switcherObj.leadBrand]\n });\n\n // Store the fact the binLookup obj has a panLength prop\n if (switcherObj.leadBrand.panLength > 0) {\n hasPanLengthRef.current = switcherObj.leadBrand.panLength;\n }\n\n // 2) Single option found (binValueObject.supportedBrands.length === 1)\n } else {\n // Reset UI\n setDualBrandSelectElements([]);\n setSelectedBrandValue('');\n\n // Set (single) value from binLookup so it will be added to the 'brand' property in the paymentMethod object\n // EXCEPT - if we are dealing with a brand that we exclude from the UI\n if (!hasExcludedBrand) setSelectedBrandValue(supportedBrands[0].brand);\n\n // Pass object through to SFP\n sfp.current.processBinLookupResponse({\n issuingCountryCode: binLookupResponse.issuingCountryCode,\n supportedBrands\n });\n\n // Store the fact the binLookup obj has a panLength prop\n if (supportedBrands[0].panLength > 0) {\n hasPanLengthRef.current = supportedBrands[0].panLength;\n }\n }\n }\n },\n /**\n * Handler for clicks on the icons added in response to the /binLookup call\n * Inform SFP of the brand changes when these selections are made\n */\n handleDualBrandSelection: (e: Event | string): void => {\n let value: Event | string = e;\n if (e instanceof Event) {\n const target = e.target as HTMLLIElement;\n value = target.getAttribute('data-value') || target.getAttribute('value');\n }\n\n // Check if we have a value and whether that value corresponds to a brandObject we can propagate\n // If either are false then abandon the process\n let brandObjArr: BrandObject[] = [];\n if (value) {\n // Find the brandObject with the matching brand value and place into an array\n brandObjArr = dualBrandSelectElements.reduce((acc, item) => {\n if (item.brandObject.brand === value) {\n acc.push(item.brandObject);\n }\n return acc;\n }, []);\n\n if (!brandObjArr.length) {\n return; // no brand object associated with value was found\n }\n } else {\n return; // no value passed\n }\n\n setSelectedBrandValue(value);\n\n // Pass brand object into SecuredFields\n sfp.current.processBinLookupResponse({\n issuingCountryCode,\n supportedBrands: brandObjArr,\n isDualBrandSelection: true\n });\n }\n };\n}\n"],"names":["containsExcludedBrand","brandsArr","excludedBrands","reduce","acc","brandObj","includes","brand","cloneBrandsArr","map","item","_object_spread","removeExcludedBrand","mainBrand1","mainBrand2","clonedBrands","reverse","length","extensions","props","refs","states","hasPanLengthRef","type","cvcPolicy","sfp","dualBrandSelectElements","setDualBrandSelectElements","setSelectedBrandValue","issuingCountryCode","setIssuingCountryCode","processBinLookup","binLookupResponse","isReset","issuingCode","toLowerCase","Object","keys","brandToReset","current","processBinLookupResponse","supportedBrands","hasExcludedBrand","BRAND_ICON_UI_EXCLUSION_LIST","switcherObj","createCardVariantSwitcher","selectedBrandValue","leadBrand","panLength","handleDualBrandSelection","e","value","Event","target","getAttribute","brandObjArr","brandObject","push","isDualBrandSelection"],"mappings":"yOAMO,MAAMA,EAAwB,CAACC,EAA0BC,IACrDD,EAAUE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BAGlCrB,EAAIc,QAAQC,yBAAyB,CACjCX,mBAAoBG,EAAkBH,mBACtCY,gBAAiB,CAACG,EAAYG,aAI9BH,EAAYG,UAAUC,UAAY,IAClC1B,EAAgBiB,QAAUK,EAAYG,UAAUC,UAIxD,MAEIrB,EAA2B,IAC3BC,EAAsB,IAIjBc,GAAkBd,EAAsBa,EAAgB,GAAGlC,OAGhEkB,EAAIc,QAAQC,yBAAyB,CACjCX,mBAAoBG,EAAkBH,mBACtCY,oBAIAA,EAAgB,GAAGO,UAAY,IAC/B1B,EAAgBiB,QAAUE,EAAgB,GAAGO,UAGzD,GAMJC,yBAA2BC,IACvB,IAAIC,EAAwBD,EAC5B,GAAIA,aAAaE,MAAO,CACpB,MAAMC,EAASH,EAAEG,OACjBF,EAAQE,EAAOC,aAAa,eAAiBD,EAAOC,aAAa,QACrE,CAIA,IAAIC,EAA6B,GAC7BJ,IAEAI,EAAc7B,EAAwBvB,OAAO,CAACC,EAAKM,KAC3CA,EAAK8C,YAAYjD,QAAU4C,GAC3B/C,EAAIqD,KAAK/C,EAAK8C,aAEXpD,GACR,IAEEmD,EAAYtC,SAOrBW,EAAsBuB,GAGtB1B,EAAIc,QAAQC,yBAAyB,CACjCX,qBACAY,gBAAiBc,EACjBG,sBAAsB,OAItC"}
1
+ {"version":3,"file":"extensions.js","sources":["../../../../../../src/components/internal/SecuredFields/binLookup/extensions.ts"],"sourcesContent":["import { SingleBrandResetObject } from '../SFP/types';\nimport { BrandObject } from '../../../Card/types';\nimport createCardVariantSwitcher from './createCardVariantSwitcher';\nimport { BRAND_ICON_UI_EXCLUSION_LIST } from '../lib/constants';\nimport { mustHandleDualBrandingAccordingToEURegulations } from '../../../Card/components/CardInput/utils';\nimport { DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM } from '../../../Card/Card';\n\n// Externally testable utils\nexport const containsExcludedBrand = (brandsArr: BrandObject[], excludedBrands: string[]): boolean => {\n return brandsArr.reduce((acc, brandObj) => acc || excludedBrands.includes(brandObj.brand), false);\n};\n\nexport const cloneBrandsArr = (brandsArr: BrandObject[]): BrandObject[] => brandsArr.map(item => ({ ...item }));\n\nexport const removeExcludedBrand = (brandsArr: BrandObject[], mainBrand1 = 'mc', mainBrand2 = 'visa'): BrandObject[] => {\n const clonedBrands: BrandObject[] = cloneBrandsArr(brandsArr);\n\n if (clonedBrands[0].brand !== mainBrand1 && clonedBrands[0].brand !== mainBrand2) clonedBrands.reverse();\n clonedBrands.length = 1;\n return clonedBrands;\n};\n// --\n\nexport default function extensions(props, refs, states, hasPanLengthRef: Partial<{ current }> = {}) {\n // Destructure props, refs and state hooks\n const { type, cvcPolicy } = props;\n const { sfp } = refs;\n const { dualBrandSelectElements, setDualBrandSelectElements, setSelectedBrandValue, issuingCountryCode, setIssuingCountryCode } = states;\n\n return {\n /**\n * Handle the binLookup response object generated in triggerBinLookup and process it in relation to the CardInput and it's sub-components.\n * e.g. we might need to add/remove additional markup (a selector for brands), and inform SFP of the issuingCountryCode & detected brand(s).\n *\n * @param binLookupResponse -\n * @param isReset -\n */\n processBinLookup: (binLookupResponse, isReset) => {\n const issuingCode = binLookupResponse?.issuingCountryCode ? binLookupResponse.issuingCountryCode.toLowerCase() : null;\n setIssuingCountryCode(issuingCode);\n\n // Reset UI\n if (!binLookupResponse || !Object.keys(binLookupResponse).length) {\n setDualBrandSelectElements([]);\n setSelectedBrandValue('');\n\n // If /binLookup has 'reset' then for a generic card the internal regex will kick in to show the right brand icon - so set to null\n // However for a single-branded card we need to pass the \"base\" type so the brand logo is reset - so set to type\n const brandToReset = isReset && type !== 'card' ? type : null;\n\n sfp.current.processBinLookupResponse(binLookupResponse, {\n brand: brandToReset,\n cvcPolicy: cvcPolicy // undefined except for Bancontact\n } as SingleBrandResetObject);\n\n // Reset storage var\n hasPanLengthRef.current = 0;\n return;\n }\n\n // RESULT: binLookup has found a result so proceed accordingly\n if (binLookupResponse.supportedBrands?.length) {\n const hasExcludedBrand: boolean = containsExcludedBrand(binLookupResponse.supportedBrands, BRAND_ICON_UI_EXCLUSION_LIST);\n\n const supportedBrands: BrandObject[] = hasExcludedBrand\n ? removeExcludedBrand(binLookupResponse.supportedBrands)\n : cloneBrandsArr(binLookupResponse.supportedBrands);\n\n // 1) Multiple options found - add to the UI & inform SFP\n if (supportedBrands.length > 1) {\n // --\n\n // Only if the brands in DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM are present in the binLookup response should we handle dual branding based on EU regulations\n const preselectBrand = mustHandleDualBrandingAccordingToEURegulations(\n DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM,\n supportedBrands,\n 'brand'\n );\n\n const switcherObj = createCardVariantSwitcher(supportedBrands, preselectBrand);\n\n // Set properties on state to trigger the dual branding icons in the UI\n setDualBrandSelectElements(switcherObj.dualBrandSelectElements);\n setSelectedBrandValue(switcherObj.selectedBrandValue); // initially this value from switcherObj will be ''\n\n // Pass an object through to SFP\n sfp.current.processBinLookupResponse({\n issuingCountryCode: binLookupResponse.issuingCountryCode,\n supportedBrands: [switcherObj.leadBrand]\n });\n\n // Store the fact the binLookup obj has a panLength prop\n if (switcherObj.leadBrand.panLength > 0) {\n hasPanLengthRef.current = switcherObj.leadBrand.panLength;\n }\n\n // 2) Single option found (binValueObject.supportedBrands.length === 1)\n } else {\n // Reset UI\n setDualBrandSelectElements([]);\n setSelectedBrandValue('');\n\n // Set (single) value from binLookup so it will be added to the 'brand' property in the paymentMethod object\n // EXCEPT - if we are dealing with a brand that we exclude from the UI\n if (!hasExcludedBrand) setSelectedBrandValue(supportedBrands[0].brand);\n\n // Pass object through to SFP\n sfp.current.processBinLookupResponse({\n issuingCountryCode: binLookupResponse.issuingCountryCode,\n supportedBrands\n });\n\n // Store the fact the binLookup obj has a panLength prop\n if (supportedBrands[0].panLength > 0) {\n hasPanLengthRef.current = supportedBrands[0].panLength;\n }\n }\n }\n },\n /**\n * Handler for clicks on the icons added in response to the /binLookup call\n * Inform SFP of the brand changes when these selections are made\n */\n handleDualBrandSelection: (e: Event | string): void => {\n let value: Event | string = e;\n if (e instanceof Event) {\n const target = e.target as HTMLLIElement;\n value = target.getAttribute('data-value') || target.getAttribute('value');\n }\n\n // Check if we have a value and whether that value corresponds to a brandObject we can propagate\n // If either are false then abandon the process\n let brandObjArr: BrandObject[] = [];\n if (value) {\n // Find the brandObject with the matching brand value and place into an array\n brandObjArr = dualBrandSelectElements.reduce((acc, item) => {\n if (item.brandObject.brand === value) {\n acc.push(item.brandObject);\n }\n return acc;\n }, []);\n\n if (!brandObjArr.length) {\n return; // no brand object associated with value was found\n }\n } else {\n return; // no value passed\n }\n\n setSelectedBrandValue(value);\n\n // Pass brand object into SecuredFields\n sfp.current.processBinLookupResponse({\n issuingCountryCode,\n supportedBrands: brandObjArr,\n isDualBrandSelection: true\n });\n }\n };\n}\n"],"names":["containsExcludedBrand","brandsArr","excludedBrands","reduce","acc","brandObj","includes","brand","cloneBrandsArr","map","item","_object_spread","removeExcludedBrand","mainBrand1","mainBrand2","clonedBrands","reverse","length","extensions","props","refs","states","hasPanLengthRef","type","cvcPolicy","sfp","dualBrandSelectElements","setDualBrandSelectElements","setSelectedBrandValue","issuingCountryCode","setIssuingCountryCode","processBinLookup","binLookupResponse","isReset","issuingCode","toLowerCase","Object","keys","brandToReset","current","processBinLookupResponse","supportedBrands","hasExcludedBrand","BRAND_ICON_UI_EXCLUSION_LIST","preselectBrand","mustHandleDualBrandingAccordingToEURegulations","DUAL_BRANDS_THAT_NEED_SELECTION_MECHANISM","switcherObj","createCardVariantSwitcher","selectedBrandValue","leadBrand","panLength","handleDualBrandSelection","e","value","Event","target","getAttribute","brandObjArr","brandObject","push","isDualBrandSelection"],"mappings":"waAQO,MAAMA,EAAwB,CAACC,EAA0BC,IACrDD,EAAUE,OAAO,CAACC,EAAKC,IAAaD,GAAOF,EAAeI,SAASD,EAASE,QAAQ,GAGlFC,EAAkBP,GAA4CA,EAAUQ,IAAIC,qUAASC,CAAA,CAAA,EAAKD,IAE1FE,EAAsB,CAACX,EAA0B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,IAClC7B,EAAgBiB,QAAUQ,EAAYG,UAAUC,UAIxD,MAEIxB,EAA2B,IAC3BC,EAAsB,IAIjBc,GAAkBd,EAAsBa,EAAgB,GAAGlC,OAGhEkB,EAAIc,QAAQC,yBAAyB,CACjCX,mBAAoBG,EAAkBH,mBACtCY,oBAIAA,EAAgB,GAAGU,UAAY,IAC/B7B,EAAgBiB,QAAUE,EAAgB,GAAGU,UAGzD,GAMJC,yBAA2BC,IACvB,IAAIC,EAAwBD,EAC5B,GAAIA,aAAaE,MAAO,CACpB,MAAMC,EAASH,EAAEG,OACjBF,EAAQE,EAAOC,aAAa,eAAiBD,EAAOC,aAAa,QACrE,CAIA,IAAIC,EAA6B,GAC7BJ,IAEAI,EAAchC,EAAwBvB,OAAO,CAACC,EAAKM,KAC3CA,EAAKiD,YAAYpD,QAAU+C,GAC3BlD,EAAIwD,KAAKlD,EAAKiD,aAEXvD,GACR,IAEEsD,EAAYzC,SAOrBW,EAAsB0B,GAGtB7B,EAAIc,QAAQC,yBAAyB,CACjCX,qBACAY,gBAAiBiB,EACjBG,sBAAsB,OAItC"}
@@ -1,2 +1,2 @@
1
- import e from"../Services/analytics/collect-id.js";import t from"./EventsQueue.js";import{ANALYTIC_LEVEL as n,ANALYTICS_EVENT as l,ANALYTICS_INFO_TIMER_INTERVAL as a,ANALYTICS_PATH as o}from"./constants.js";import{debounce as r}from"../../utils/debounce.js";import{processAnalyticsData as c}from"./utils.js";function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},l=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(l=l.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),l.forEach(function(t){i(e,t,n[t])})}return e}let u=null,y=null;const f=({locale:i,clientKey:f,analytics:m,amount:b,analyticsContext:d,bundleType:p})=>{const g=s({},{enabled:!0,checkoutAttemptId:null,analyticsData:{}},m),j=e({analyticsContext:d,clientKey:f,locale:i,analyticsPath:o,bundleType:p}),h=t({analyticsContext:d,clientKey:f,analyticsPath:o}),v=()=>u?h.run(u):Promise.resolve(null);return{setUp:async e=>{const{payload:t,enabled:l}=g,a=l?n.all:n.initial,o=c(g.analyticsData);if(!u)try{u=await j(s({},e,t&&s({},t),Object.keys(o).length&&s({},o),{level:a}))}catch(e){console.warn("Fetching checkoutAttemptId failed."+(e?` Error=${e}`:""))}},getCheckoutAttemptId:()=>u,getEventsQueue:()=>h,getEnabled:()=>g.enabled,sendAnalytics:e=>{if(!g.enabled)return!1;return((e,t)=>{const n=e===l.info?e:`${e}s`;h.add(`${n}`,t),e===l.info&&(clearTimeout(y),y=setTimeout(()=>{v()},a)),e!==l.log&&e!==l.error||(clearTimeout(y),r(v)())})(e.getEventCategory(),e),!0}}};export{f as default};
1
+ import t from"../Services/analytics/collect-id.js";import e from"./EventsQueue.js";import{ANALYTIC_LEVEL as n,ANALYTICS_EVENT as r,ANALYTICS_INFO_TIMER_INTERVAL as o,ANALYTICS_PATH as c}from"./constants.js";import{debounce as l}from"../../utils/debounce.js";import{processAnalyticsData as i}from"./utils.js";import a from"../../utils/Storage.js";function s(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable}))),r.forEach(function(e){s(t,e,n[e])})}return t}function p(t,e){return e=null!=e?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)):function(t){var e=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e.push.apply(e,n)}return e}(Object(e)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}let y=null,m=null;const f=({locale:s,clientKey:f,analytics:b,analyticsContext:d,bundleType:O})=>{const j=u({},{enabled:!0},b),g=t({analyticsContext:d,clientKey:f,locale:s,analyticsPath:c,bundleType:O}),w=new a("checkout-attempt-id","sessionStorage"),P=e({analyticsContext:d,clientKey:f,analyticsPath:c}),v=()=>y?P.run(y):Promise.resolve(null);return{setUp:async t=>{try{const e=u({},{},t),r=w.get(),o=function(t){if(!(null==t?void 0:t.timestamp))return!1;const e=Date.now()-9e5;return t.timestamp>e}(r),{payload:c,enabled:l}=j,a=l?n.all:n.initial,s=i(j.analyticsData),m=o?r.id:null==s?void 0:s.checkoutAttemptId,f=p(u({},e,c,s,m&&{checkoutAttemptId:m}),{level:a});y=await g(f),w.set({id:y,timestamp:o?r.timestamp:Date.now()})}catch(t){console.warn(t)}},getCheckoutAttemptId:()=>y,getEventsQueue:()=>P,getEnabled:()=>j.enabled,flush:()=>{v()},sendAnalytics:t=>{if(!j.enabled)return!1;return((t,e)=>{const n=t===r.info?t:`${t}s`;P.add(`${n}`,e),t===r.info&&(clearTimeout(m),m=setTimeout(()=>{v()},o)),t!==r.log&&t!==r.error||(clearTimeout(m),l(v)())})(t.getEventCategory(),t),!0}}};export{f as default};
2
2
  //# sourceMappingURL=Analytics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Analytics.js","sources":["../../../../src/core/Analytics/Analytics.ts"],"sourcesContent":["import CollectId from '../Services/analytics/collect-id';\nimport EventsQueue, { EventsQueueModule } from './EventsQueue';\nimport { AnalyticsEventCategory, AnalyticsInitialEvent, AnalyticsObject, AnalyticsProps } from './types';\nimport { ANALYTIC_LEVEL, ANALYTICS_INFO_TIMER_INTERVAL, ANALYTICS_PATH, ANALYTICS_EVENT } from './constants';\nimport { debounce } from '../../utils/debounce';\nimport { AnalyticsModule } from '../../types/global-types';\nimport { processAnalyticsData } from './utils';\nimport { AnalyticsEvent } from './AnalyticsEvent';\n\nlet capturedCheckoutAttemptId = null;\nlet sendEventsTimerId = null;\n\nconst Analytics = ({ locale, clientKey, analytics, amount, analyticsContext, bundleType }: AnalyticsProps): AnalyticsModule => {\n const defaultProps = {\n enabled: true,\n checkoutAttemptId: null,\n analyticsData: {}\n };\n\n const props = { ...defaultProps, ...analytics };\n\n const collectId = CollectId({ analyticsContext, clientKey, locale, amount, analyticsPath: ANALYTICS_PATH, bundleType });\n const eventsQueue: EventsQueueModule = EventsQueue({ analyticsContext, clientKey, analyticsPath: ANALYTICS_PATH });\n\n const sendAnalyticsEvents = () => {\n if (capturedCheckoutAttemptId) {\n return eventsQueue.run(capturedCheckoutAttemptId);\n }\n return Promise.resolve(null);\n };\n\n const addAnalyticsEvent = (eventCat: AnalyticsEventCategory, obj: AnalyticsObject) => {\n const arrayName = eventCat === ANALYTICS_EVENT.info ? eventCat : `${eventCat}s`;\n eventsQueue.add(`${arrayName}`, obj);\n\n /**\n * The logic is:\n * - info events are stored until a log or error comes along,\n * but, if after a set time, no other analytics event (log or error) has come along then we send the info events anyway\n */\n if (eventCat === ANALYTICS_EVENT.info) {\n clearTimeout(sendEventsTimerId);\n sendEventsTimerId = setTimeout(() => void sendAnalyticsEvents(), ANALYTICS_INFO_TIMER_INTERVAL);\n }\n\n /**\n * The logic is:\n * - errors and logs get sent straightaway\n * ...but... tests with the 3DS2 process show that many logs can happen almost at the same time (or you can have an error followed immediately by a log),\n * so instead of making several sequential api calls we see if we can \"batch\" them using debounce\n */\n if (eventCat === ANALYTICS_EVENT.log || eventCat === ANALYTICS_EVENT.error) {\n clearTimeout(sendEventsTimerId); // clear any timer that might be about to dispatch the info events array\n\n debounce(sendAnalyticsEvents)();\n }\n };\n\n return {\n /**\n * Make \"setup\" call, to pass containerWidth, buildType, channel etc, and receive a checkoutAttemptId in return\n * @param initialEvent -\n */\n setUp: async (initialEvent: AnalyticsInitialEvent) => {\n const { payload, enabled } = props; // TODO what is payload, is it ever used?\n const level = enabled ? ANALYTIC_LEVEL.all : ANALYTIC_LEVEL.initial;\n const analyticsData = processAnalyticsData(props.analyticsData);\n if (!capturedCheckoutAttemptId) {\n try {\n capturedCheckoutAttemptId = await collectId({\n ...initialEvent,\n ...(payload && { ...payload }),\n ...(Object.keys(analyticsData).length && { ...analyticsData }),\n ...{ level }\n });\n } catch (e: any) {\n console.warn(`Fetching checkoutAttemptId failed.${e ? ` Error=${e}` : ''}`);\n }\n }\n },\n\n getCheckoutAttemptId: (): string => capturedCheckoutAttemptId,\n\n // Expose getter for testing purposes\n getEventsQueue: () => eventsQueue,\n\n getEnabled: () => props.enabled,\n\n sendAnalytics: (analyticsObj: AnalyticsEvent): boolean => {\n if (!props.enabled) return false;\n\n const eventCategory: AnalyticsEventCategory = analyticsObj.getEventCategory();\n\n addAnalyticsEvent(eventCategory, analyticsObj);\n\n return true;\n }\n } as AnalyticsModule;\n};\n\nexport default Analytics;\n"],"names":["capturedCheckoutAttemptId","sendEventsTimerId","Analytics","locale","clientKey","analytics","amount","analyticsContext","bundleType","props","_object_spread","enabled","checkoutAttemptId","analyticsData","collectId","CollectId","analyticsPath","ANALYTICS_PATH","eventsQueue","EventsQueue","sendAnalyticsEvents","run","Promise","resolve","setUp","async","initialEvent","payload","level","ANALYTIC_LEVEL","all","initial","processAnalyticsData","Object","keys","length","e","console","warn","getCheckoutAttemptId","getEventsQueue","getEnabled","sendAnalytics","analyticsObj","eventCat","obj","arrayName","ANALYTICS_EVENT","info","add","clearTimeout","setTimeout","ANALYTICS_INFO_TIMER_INTERVAL","log","error","debounce","addAnalyticsEvent","getEventCategory"],"mappings":"gvBASA,IAAIA,EAA4B,KAC5BC,EAAoB,KAExB,MAAMC,EAAY,EAAGC,SAAQC,YAAWC,YAAWC,SAAQC,mBAAkBC,iBACzE,MAMMC,EAAQC,KANO,CACjBC,SAAS,EACTC,kBAAmB,KACnBC,cAAe,CAAA,GAGiBR,GAE9BS,EAAYC,EAAU,CAAER,mBAAkBH,YAAWD,SAAgBa,cAAeC,EAAgBT,eACpGU,EAAiCC,EAAY,CAAEZ,mBAAkBH,YAAWY,cAAeC,IAE3FG,EAAsB,IACpBpB,EACOkB,EAAYG,IAAIrB,GAEpBsB,QAAQC,QAAQ,MA8B3B,MAAO,CAKHC,MAAOC,MAAOC,IACV,MAAMC,QAAEA,EAAOhB,QAAEA,GAAYF,EACvBmB,EAAQjB,EAAUkB,EAAeC,IAAMD,EAAeE,QACtDlB,EAAgBmB,EAAqBvB,EAAMI,eACjD,IAAKb,EACD,IACIA,QAAkCc,EAAUJ,EAAA,CAAA,EACrCgB,EACCC,GAAWjB,EAAA,CAAA,EAAKiB,GAChBM,OAAOC,KAAKrB,GAAesB,QAAUzB,KAAKG,GAC3C,CAAEe,UAEb,CAAE,MAAOQ,GACLC,QAAQC,KAAK,sCAAqCF,EAAI,UAAUA,IAAM,IAC1E,GAIRG,qBAAsB,IAAcvC,EAGpCwC,eAAgB,IAAMtB,EAEtBuB,WAAY,IAAMhC,EAAME,QAExB+B,cAAgBC,IACZ,IAAKlC,EAAME,QAAS,OAAO,EAM3B,MAhEkB,EAACiC,EAAkCC,KACzD,MAAMC,EAAYF,IAAaG,EAAgBC,KAAOJ,EAAW,GAAGA,KACpE1B,EAAY+B,IAAI,GAAGH,IAAaD,GAO5BD,IAAaG,EAAgBC,OAC7BE,aAAajD,GACbA,EAAoBkD,WAAW,KAAW/B,KAAuBgC,IASjER,IAAaG,EAAgBM,KAAOT,IAAaG,EAAgBO,QACjEJ,aAAajD,GAEbsD,EAASnC,EAATmC,KAuCAC,CAF8Cb,EAAac,mBAE1Bd,IAE1B"}
1
+ {"version":3,"file":"Analytics.js","sources":["../../../../src/core/Analytics/Analytics.ts"],"sourcesContent":["import CollectId from '../Services/analytics/collect-id';\nimport EventsQueue, { EventsQueueModule } from './EventsQueue';\nimport { AnalyticsEventCategory, AnalyticsInitialEvent, AnalyticsObject, AnalyticsProps } from './types';\nimport { ANALYTIC_LEVEL, ANALYTICS_INFO_TIMER_INTERVAL, ANALYTICS_PATH, ANALYTICS_EVENT } from './constants';\nimport { debounce } from '../../utils/debounce';\nimport { AnalyticsModule } from '../../types/global-types';\nimport { processAnalyticsData } from './utils';\nimport { AnalyticsEvent } from './AnalyticsEvent';\nimport Storage from '../../utils/Storage';\nimport { CheckoutAttemptIdSession } from '../Services/analytics/types';\n\nlet capturedCheckoutAttemptId: string | null = null;\nlet sendEventsTimerId = null;\n\n/**\n * If the checkout attempt ID was stored more than fifteen minutes ago, then we should request a new ID.\n * More here: COWEB-1099\n */\nfunction isSessionCreatedUnderFifteenMinutes(session: CheckoutAttemptIdSession): boolean {\n const FIFTEEN_MINUTES_IN_MS = 15 * 60 * 1000;\n if (!session?.timestamp) return false;\n const fifteenMinutesAgo = Date.now() - FIFTEEN_MINUTES_IN_MS;\n return session.timestamp > fifteenMinutesAgo;\n}\n\nconst Analytics = ({ locale, clientKey, analytics, analyticsContext, bundleType }: AnalyticsProps): AnalyticsModule => {\n const defaultProps = {\n enabled: true\n };\n\n const props = { ...defaultProps, ...analytics };\n\n const collectId = CollectId({\n analyticsContext,\n clientKey,\n locale,\n analyticsPath: ANALYTICS_PATH,\n bundleType\n });\n\n const storage = new Storage<CheckoutAttemptIdSession>('checkout-attempt-id', 'sessionStorage');\n const eventsQueue: EventsQueueModule = EventsQueue({ analyticsContext, clientKey, analyticsPath: ANALYTICS_PATH });\n\n const sendAnalyticsEvents = () => {\n if (capturedCheckoutAttemptId) {\n return eventsQueue.run(capturedCheckoutAttemptId);\n }\n return Promise.resolve(null);\n };\n\n const addAnalyticsEvent = (eventCat: AnalyticsEventCategory, obj: AnalyticsObject) => {\n const arrayName = eventCat === ANALYTICS_EVENT.info ? eventCat : `${eventCat}s`;\n eventsQueue.add(`${arrayName}`, obj);\n\n /**\n * The logic is:\n * - info events are stored until a log or error comes along,\n * but, if after a set time, no other analytics event (log or error) has come along then we send the info events anyway\n */\n if (eventCat === ANALYTICS_EVENT.info) {\n clearTimeout(sendEventsTimerId);\n sendEventsTimerId = setTimeout(() => void sendAnalyticsEvents(), ANALYTICS_INFO_TIMER_INTERVAL);\n }\n\n /**\n * The logic is:\n * - errors and logs get sent straightaway\n * ...but... tests with the 3DS2 process show that many logs can happen almost at the same time (or you can have an error followed immediately by a log),\n * so instead of making several sequential api calls we see if we can \"batch\" them using debounce\n */\n if (eventCat === ANALYTICS_EVENT.log || eventCat === ANALYTICS_EVENT.error) {\n clearTimeout(sendEventsTimerId); // clear any timer that might be about to dispatch the info events array\n\n debounce(sendAnalyticsEvents)();\n }\n };\n\n return {\n setUp: async (setupProps?: AnalyticsInitialEvent): Promise<void> => {\n try {\n const defaultProps: Partial<AnalyticsInitialEvent> = {};\n const finalSetupProps = { ...defaultProps, ...setupProps };\n\n const checkoutAttemptIdSession = storage.get();\n const isSessionReusable = isSessionCreatedUnderFifteenMinutes(checkoutAttemptIdSession);\n\n const { payload, enabled } = props;\n const level = enabled ? ANALYTIC_LEVEL.all : ANALYTIC_LEVEL.initial;\n const analyticsData = processAnalyticsData(props.analyticsData);\n\n const availableCheckoutAttemptId: string | undefined = isSessionReusable\n ? checkoutAttemptIdSession.id\n : analyticsData?.checkoutAttemptId;\n\n const collectIdPayload = {\n ...finalSetupProps,\n ...payload,\n ...analyticsData,\n ...(availableCheckoutAttemptId && { checkoutAttemptId: availableCheckoutAttemptId }),\n level\n };\n\n capturedCheckoutAttemptId = await collectId(collectIdPayload);\n\n storage.set({\n id: capturedCheckoutAttemptId,\n timestamp: isSessionReusable ? checkoutAttemptIdSession.timestamp : Date.now()\n });\n } catch (error: unknown) {\n console.warn(error);\n }\n },\n\n getCheckoutAttemptId: (): string => capturedCheckoutAttemptId,\n\n // Expose getter for testing purposes\n getEventsQueue: () => eventsQueue,\n\n getEnabled: () => props.enabled,\n\n flush: () => {\n void sendAnalyticsEvents();\n },\n\n sendAnalytics: (analyticsObj: AnalyticsEvent): boolean => {\n if (!props.enabled) return false;\n\n const eventCategory: AnalyticsEventCategory = analyticsObj.getEventCategory();\n\n addAnalyticsEvent(eventCategory, analyticsObj);\n\n return true;\n }\n } as AnalyticsModule;\n};\n\nexport default Analytics;\n"],"names":["capturedCheckoutAttemptId","sendEventsTimerId","Analytics","locale","clientKey","analytics","analyticsContext","bundleType","props","_object_spread","enabled","collectId","CollectId","analyticsPath","ANALYTICS_PATH","storage","Storage","eventsQueue","EventsQueue","sendAnalyticsEvents","run","Promise","resolve","setUp","async","setupProps","finalSetupProps","checkoutAttemptIdSession","get","isSessionReusable","session","timestamp","fifteenMinutesAgo","Date","now","isSessionCreatedUnderFifteenMinutes","payload","level","ANALYTIC_LEVEL","all","initial","analyticsData","processAnalyticsData","availableCheckoutAttemptId","id","checkoutAttemptId","collectIdPayload","_object_spread_props","set","error","console","warn","getCheckoutAttemptId","getEventsQueue","getEnabled","flush","sendAnalytics","analyticsObj","eventCat","obj","arrayName","ANALYTICS_EVENT","info","add","clearTimeout","setTimeout","ANALYTICS_INFO_TIMER_INTERVAL","log","debounce","addAnalyticsEvent","getEventCategory"],"mappings":"moCAWA,IAAIA,EAA2C,KAC3CC,EAAoB,KAaxB,MAAMC,EAAY,EAAGC,SAAQC,YAAWC,YAAWC,mBAAkBC,iBACjE,MAIMC,EAAQC,KAJO,CACjBC,SAAS,GAGuBL,GAE9BM,EAAYC,EAAU,CACxBN,mBACAF,YACAD,SACAU,cAAeC,EACfP,eAGEQ,EAAU,IAAIC,EAAkC,sBAAuB,kBACvEC,EAAiCC,EAAY,CAAEZ,mBAAkBF,YAAWS,cAAeC,IAE3FK,EAAsB,IACpBnB,EACOiB,EAAYG,IAAIpB,GAEpBqB,QAAQC,QAAQ,MA8B3B,MAAO,CACHC,MAAOC,MAAOC,IACV,IACI,MACMC,EAAkBjB,KAD6B,CAAA,EACPgB,GAExCE,EAA2BZ,EAAQa,MACnCC,EAlEtB,SAA6CC,GAEzC,KAAKA,aAAAA,EAAAA,EAASC,WAAW,OAAO,EAChC,MAAMC,EAAoBC,KAAKC,MAFD,IAG9B,OAAOJ,EAAQC,UAAYC,CAC/B,CA6D0CG,CAAoCR,IAExDS,QAAEA,EAAO1B,QAAEA,GAAYF,EACvB6B,EAAQ3B,EAAU4B,EAAeC,IAAMD,EAAeE,QACtDC,EAAgBC,EAAqBlC,EAAMiC,eAE3CE,EAAiDd,EACjDF,EAAyBiB,GACzBH,aAAAA,EAAAA,EAAeI,kBAEfC,EAAmBC,EAAAtC,EAAA,CAAA,EAClBiB,EACAU,EACAK,EACCE,GAA8B,CAAEE,kBAAmBF,IAA2B,CAClFN,UAGJrC,QAAkCW,EAAUmC,GAE5C/B,EAAQiC,IAAI,CACRJ,GAAI5C,EACJ+B,UAAWF,EAAoBF,EAAyBI,UAAYE,KAAKC,OAEjF,CAAE,MAAOe,GACLC,QAAQC,KAAKF,EACjB,GAGJG,qBAAsB,IAAcpD,EAGpCqD,eAAgB,IAAMpC,EAEtBqC,WAAY,IAAM9C,EAAME,QAExB6C,MAAO,KACEpC,KAGTqC,cAAgBC,IACZ,IAAKjD,EAAME,QAAS,OAAO,EAM3B,MAjFkB,EAACgD,EAAkCC,KACzD,MAAMC,EAAYF,IAAaG,EAAgBC,KAAOJ,EAAW,GAAGA,KACpEzC,EAAY8C,IAAI,GAAGH,IAAaD,GAO5BD,IAAaG,EAAgBC,OAC7BE,aAAa/D,GACbA,EAAoBgE,WAAW,KAAW9C,KAAuB+C,IASjER,IAAaG,EAAgBM,KAAOT,IAAaG,EAAgBZ,QACjEe,aAAa/D,GAEbmE,EAASjD,EAATiD,KAwDAC,CAF8CZ,EAAaa,mBAE1Bb,IAE1B"}
@@ -1,2 +1,2 @@
1
- import{errorCodeMapping as r,ALLOWED_ANALYTICS_DATA as t}from"./constants.js";import{digitsOnlyFormatter as o}from"../../utils/Formatters/formatters.js";import{ERROR_FIELD_REQUIRED as s,ERROR_INVALID_FORMAT_EXPECTS as e}from"../Errors/constants.js";const n=()=>Date.now(),i=(t,n)=>{var i,m;if(t===s||t===e)return null!==(i=r[`${t}.${n}`])&&void 0!==i?i:t;let u=null!==(m=r[t])&&void 0!==m?m:t;return isNaN(Number(u))&&(u=o(u)),u},m=r=>Object.keys(r).reduce((o,s)=>(t.includes(s)&&(o[s]=r[s]),o),{});export{n as getUTCTimestamp,i as mapErrorCodesForAnalytics,m as processAnalyticsData};
1
+ import{errorCodeMapping as r,ALLOWED_ANALYTICS_DATA as t}from"./constants.js";import{digitsOnlyFormatter as o}from"../../utils/Formatters/formatters.js";import{ERROR_FIELD_REQUIRED as s,ERROR_INVALID_FORMAT_EXPECTS as e}from"../Errors/constants.js";const n=()=>Date.now(),i=(t,n)=>{var i,m;if(t===s||t===e)return null!==(i=r[`${t}.${n}`])&&void 0!==i?i:t;let u=null!==(m=r[t])&&void 0!==m?m:t;return isNaN(Number(u))&&(u=o(u)),u},m=r=>r?Object.keys(r).reduce((o,s)=>(t.includes(s)&&(o[s]=r[s]),o),{}):{};export{n as getUTCTimestamp,i as mapErrorCodesForAnalytics,m as processAnalyticsData};
2
2
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../../../src/core/Analytics/utils.ts"],"sourcesContent":["import { AnalyticsData } from './types';\nimport { errorCodeMapping, ALLOWED_ANALYTICS_DATA } from './constants';\nimport { digitsOnlyFormatter } from '../../utils/Formatters/formatters';\nimport { ERROR_FIELD_REQUIRED, ERROR_INVALID_FORMAT_EXPECTS } from '../Errors/constants';\n\nexport const getUTCTimestamp = () => Date.now();\n\nexport const mapErrorCodesForAnalytics = (errorCode: string, target: string) => {\n // Some of the more generic error codes required combination with target to retrieve a specific code\n if (errorCode === ERROR_FIELD_REQUIRED || errorCode === ERROR_INVALID_FORMAT_EXPECTS) {\n return errorCodeMapping[`${errorCode}.${target}`] ?? errorCode;\n }\n\n let errCode = errorCodeMapping[errorCode] ?? errorCode;\n\n // If errCode isn't now a number - then we just need to remove any non-digits\n // since the correct error code is already contained within the string e.g. securedField related errors\n if (isNaN(Number(errCode))) {\n errCode = digitsOnlyFormatter(errCode);\n }\n\n return errCode;\n};\n\nexport const processAnalyticsData = (analyticsData: AnalyticsData): AnalyticsData => {\n return Object.keys(analyticsData).reduce((acc, prop) => {\n if (ALLOWED_ANALYTICS_DATA.includes(prop)) acc[prop] = analyticsData[prop];\n return acc;\n }, {});\n};\n"],"names":["getUTCTimestamp","Date","now","mapErrorCodesForAnalytics","errorCode","target","errorCodeMapping","ERROR_FIELD_REQUIRED","ERROR_INVALID_FORMAT_EXPECTS","errCode","isNaN","Number","digitsOnlyFormatter","processAnalyticsData","analyticsData","Object","keys","reduce","acc","prop","ALLOWED_ANALYTICS_DATA","includes"],"mappings":"yPAKO,MAAMA,EAAkB,IAAMC,KAAKC,MAE7BC,EAA4B,CAACC,EAAmBC,KAG9CC,IAAAA,EAGGA,EAJd,GAAIF,IAAcG,GAAwBH,IAAcI,EACpD,OAAiD,QAA1CF,EAAAA,EAAiB,GAAGF,KAAaC,YAAjCC,IAAAA,EAAAA,EAA8CF,EAGzD,IAAIK,EAAqC,QAA3BH,EAAAA,EAAiBF,cAAjBE,EAAAA,EAA+BF,EAQ7C,OAJIM,MAAMC,OAAOF,MACbA,EAAUG,EAAoBH,IAG3BA,GAGEI,EAAwBC,GAC1BC,OAAOC,KAAKF,GAAeG,OAAO,CAACC,EAAKC,KACvCC,EAAuBC,SAASF,KAAOD,EAAIC,GAAQL,EAAcK,IAC9DD,GACR,CAAA"}
1
+ {"version":3,"file":"utils.js","sources":["../../../../src/core/Analytics/utils.ts"],"sourcesContent":["import { AnalyticsData } from './types';\nimport { errorCodeMapping, ALLOWED_ANALYTICS_DATA } from './constants';\nimport { digitsOnlyFormatter } from '../../utils/Formatters/formatters';\nimport { ERROR_FIELD_REQUIRED, ERROR_INVALID_FORMAT_EXPECTS } from '../Errors/constants';\n\nexport const getUTCTimestamp = () => Date.now();\n\nexport const mapErrorCodesForAnalytics = (errorCode: string, target: string) => {\n // Some of the more generic error codes required combination with target to retrieve a specific code\n if (errorCode === ERROR_FIELD_REQUIRED || errorCode === ERROR_INVALID_FORMAT_EXPECTS) {\n return errorCodeMapping[`${errorCode}.${target}`] ?? errorCode;\n }\n\n let errCode = errorCodeMapping[errorCode] ?? errorCode;\n\n // If errCode isn't now a number - then we just need to remove any non-digits\n // since the correct error code is already contained within the string e.g. securedField related errors\n if (isNaN(Number(errCode))) {\n errCode = digitsOnlyFormatter(errCode);\n }\n\n return errCode;\n};\n\nexport const processAnalyticsData = (analyticsData?: AnalyticsData): AnalyticsData => {\n if (!analyticsData) return {};\n\n return Object.keys(analyticsData).reduce((acc, prop) => {\n if (ALLOWED_ANALYTICS_DATA.includes(prop)) acc[prop] = analyticsData[prop];\n return acc;\n }, {});\n};\n"],"names":["getUTCTimestamp","Date","now","mapErrorCodesForAnalytics","errorCode","target","errorCodeMapping","ERROR_FIELD_REQUIRED","ERROR_INVALID_FORMAT_EXPECTS","errCode","isNaN","Number","digitsOnlyFormatter","processAnalyticsData","analyticsData","Object","keys","reduce","acc","prop","ALLOWED_ANALYTICS_DATA","includes"],"mappings":"yPAKO,MAAMA,EAAkB,IAAMC,KAAKC,MAE7BC,EAA4B,CAACC,EAAmBC,KAG9CC,IAAAA,EAGGA,EAJd,GAAIF,IAAcG,GAAwBH,IAAcI,EACpD,OAAiD,QAA1CF,EAAAA,EAAiB,GAAGF,KAAaC,YAAjCC,IAAAA,EAAAA,EAA8CF,EAGzD,IAAIK,EAAqC,QAA3BH,EAAAA,EAAiBF,cAAjBE,EAAAA,EAA+BF,EAQ7C,OAJIM,MAAMC,OAAOF,MACbA,EAAUG,EAAoBH,IAG3BA,GAGEI,EAAwBC,GAC5BA,EAEEC,OAAOC,KAAKF,GAAeG,OAAO,CAACC,EAAKC,KACvCC,EAAuBC,SAASF,KAAOD,EAAIC,GAAQL,EAAcK,IAC9DD,GACR,CAAA,GALwB,CAAA"}
@@ -1,2 +1,2 @@
1
- import{httpPost as e}from"../http.js";import t from"../../../utils/Storage.js";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const r='WARNING: Failed to retrieve "checkoutAttemptId". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.';const o=({analyticsContext:o,clientKey:i,locale:c,analyticsPath:l,bundleType:a})=>{let s;const u={errorLevel:"fatal",loadingContext:o,path:`${l}?clientKey=${i}`};return o=>{const l=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(t){n(e,t,r[t])})}return e}({version:"6.20.0",channel:"Web",platform:"Web",buildType:a,locale:c,referrer:window.location.href,screenWidth:window.screen.width},o);if(s)return s;if(!i)return Promise.reject("no-client-key");const f=new t("checkout-attempt-id","sessionStorage"),p=f.get();return function(e){if(!(null==e?void 0:e.id))return!1;const t=Date.now()-9e5;return e.timestamp>t}(p)?Promise.resolve(p.id):(s=e(u,l).then(e=>{if(null==e?void 0:e.checkoutAttemptId)return f.set({id:e.checkoutAttemptId,timestamp:Date.now()}),e.checkoutAttemptId}).catch(()=>Promise.reject(r)),s)}};export{r as FAILURE_MSG,o as default};
1
+ import{httpPost as e}from"../http.js";import t from"../../Errors/AdyenCheckoutError.js";function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const n='WARNING: Failed to retrieve "checkoutAttemptId". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.',o=({analyticsContext:o,clientKey:l,locale:c,analyticsPath:a,bundleType:i})=>{let u=null;const s={errorLevel:"fatal",loadingContext:o,path:`${a}?clientKey=${l}`,errorMessage:n};return n=>{if(null!==u)return u;const o=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},o=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),o.forEach(function(t){r(e,t,n[t])})}return e}({version:"6.22.0",channel:"Web",platform:"Web",buildType:i,locale:c,referrer:window.location.href,screenWidth:window.screen.width},n);return u=e(s,o).then(e=>{if(null==e?void 0:e.checkoutAttemptId)return e.checkoutAttemptId;throw new t("NETWORK_ERROR","Analytics: Attempt ID request was successfully but no ID was returned")}),u}};export{n as FAILURE_MSG,o as default};
2
2
  //# sourceMappingURL=collect-id.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collect-id.js","sources":["../../../../../src/core/Services/analytics/collect-id.ts"],"sourcesContent":["import { httpPost } from '../http';\nimport Storage from '../../../utils/Storage';\nimport { CheckoutAttemptIdSession, CollectIdEvent, CollectIdProps, TelemetryEvent } from './types';\n\nexport const FAILURE_MSG =\n 'WARNING: Failed to retrieve \"checkoutAttemptId\". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.';\n\n/**\n * If the checkout attempt ID was stored more than fifteen minutes ago, then we should request a new ID.\n * More here: COWEB-1099\n */\nfunction confirmSessionDurationIsMaxFifteenMinutes(checkoutAttemptIdSession: CheckoutAttemptIdSession): boolean {\n if (!checkoutAttemptIdSession?.id) return false;\n\n const fifteenMinInMs = 1000 * 60 * 15;\n const fifteenMinAgoTimestamp = Date.now() - fifteenMinInMs;\n return checkoutAttemptIdSession.timestamp > fifteenMinAgoTimestamp;\n}\n\n/**\n * Send an event to Adyen with some basic telemetry info and receive a checkoutAttemptId in response\n * @param config - object containing values needed to calculate the url for the request; and also some that need to be serialized and included in the body of request\n * @returns a function returning a promise containing the response of the call (an object containing a checkoutAttemptId property)\n */\n// const collectId = ({ analyticsContext, clientKey, locale, amount }: CollectIdProps) => { // TODO - amount will be supported in the future\nconst collectId = ({ analyticsContext, clientKey, locale, analyticsPath, bundleType }: CollectIdProps) => {\n let promise;\n\n const options = {\n errorLevel: 'fatal' as const, // ensure our catch block is called\n loadingContext: analyticsContext,\n path: `${analyticsPath}?clientKey=${clientKey}`\n };\n\n return (event: CollectIdEvent): Promise<string> => {\n const telemetryEvent: TelemetryEvent = {\n // amount, // TODO will be supported in the future\n version: process.env.VERSION,\n // The data team want both platform & channel properties:\n channel: 'Web',\n platform: 'Web',\n buildType: bundleType,\n locale,\n referrer: window.location.href,\n screenWidth: window.screen.width,\n ...event\n };\n\n if (promise) return promise; // Prevents multiple standalone components on the same page from making multiple calls to collect a checkoutAttemptId\n if (!clientKey) return Promise.reject('no-client-key');\n\n const storage = new Storage<CheckoutAttemptIdSession>('checkout-attempt-id', 'sessionStorage');\n const checkoutAttemptIdSession = storage.get();\n\n // In some cases, e.g. where the merchant has redirected the shopper and then returned them to checkout, we still have a valid checkoutAttemptId\n // so there is no need for the re-initialised Checkout to generate another one\n if (confirmSessionDurationIsMaxFifteenMinutes(checkoutAttemptIdSession)) {\n return Promise.resolve(checkoutAttemptIdSession.id);\n }\n\n promise = httpPost(options, telemetryEvent)\n .then(conversion => {\n if (conversion?.checkoutAttemptId) {\n storage.set({ id: conversion.checkoutAttemptId, timestamp: Date.now() });\n return conversion.checkoutAttemptId;\n }\n return undefined;\n })\n .catch(() => {\n return Promise.reject(FAILURE_MSG);\n });\n\n return promise;\n };\n};\n\nexport default collectId;\n"],"names":["FAILURE_MSG","collectId","analyticsContext","clientKey","locale","analyticsPath","bundleType","promise","options","errorLevel","loadingContext","path","event","telemetryEvent","_object_spread","version","channel","platform","buildType","referrer","window","location","href","screenWidth","screen","width","Promise","reject","storage","Storage","checkoutAttemptIdSession","get","id","fifteenMinAgoTimestamp","Date","now","timestamp","confirmSessionDurationIsMaxFifteenMinutes","resolve","httpPost","then","conversion","checkoutAttemptId","set","catch"],"mappings":"uMAIO,MAAMA,EACT,uKAoBJ,MAAMC,EAAY,EAAGC,mBAAkBC,YAAWC,SAAQC,gBAAeC,iBACrE,IAAIC,EAEJ,MAAMC,EAAU,CACZC,WAAY,QACZC,eAAgBR,EAChBS,KAAM,GAAGN,eAA2BF,KAGxC,OAAQS,IACJ,MAAMC,oUAAiCC,CAAA,CAEnCC,QAAS,SAETC,QAAS,MACTC,SAAU,MACVC,UAAWZ,EACXF,SACAe,SAAUC,OAAOC,SAASC,KAC1BC,YAAaH,OAAOI,OAAOC,OACxBb,GAGP,GAAIL,EAAS,OAAOA,EACpB,IAAKJ,EAAW,OAAOuB,QAAQC,OAAO,iBAEtC,MAAMC,EAAU,IAAIC,EAAkC,sBAAuB,kBACvEC,EAA2BF,EAAQG,MAIzC,OA7CR,SAAmDD,GAC/C,KAAKA,aAAAA,EAAAA,EAA0BE,IAAI,OAAO,EAE1C,MACMC,EAAyBC,KAAKC,MADb,IAEvB,OAAOL,EAAyBM,UAAYH,CAChD,CAuCYI,CAA0CP,GACnCJ,QAAQY,QAAQR,EAAyBE,KAGpDzB,EAAUgC,EAAS/B,EAASK,GACvB2B,KAAKC,IACF,GAAIA,aAAAA,EAAAA,EAAYC,kBAEZ,OADAd,EAAQe,IAAI,CAAEX,GAAIS,EAAWC,kBAAmBN,UAAWF,KAAKC,QACzDM,EAAWC,oBAIzBE,MAAM,IACIlB,QAAQC,OAAO3B,IAGvBO"}
1
+ {"version":3,"file":"collect-id.js","sources":["../../../../../src/core/Services/analytics/collect-id.ts"],"sourcesContent":["import { HttpOptions, httpPost } from '../http';\nimport type { CollectIdEvent, CollectIdProps, TelemetryEvent } from './types';\nimport AdyenCheckoutError from '../../Errors/AdyenCheckoutError';\n\nexport const FAILURE_MSG =\n 'WARNING: Failed to retrieve \"checkoutAttemptId\". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.';\n\n/**\n * Send an event to Adyen with some basic telemetry info and receive a checkoutAttemptId in response\n * @param config - object containing values needed to calculate the url for the request; and also some that need to be serialized and included in the body of request\n * @returns a function returning a promise containing the response of the call (an object containing a checkoutAttemptId property)\n */\nconst collectId = ({ analyticsContext, clientKey, locale, analyticsPath, bundleType }: CollectIdProps) => {\n let memoizedPromise: Promise<string> | null = null;\n\n const options: HttpOptions = {\n errorLevel: 'fatal' as const,\n loadingContext: analyticsContext,\n path: `${analyticsPath}?clientKey=${clientKey}`,\n errorMessage: FAILURE_MSG\n };\n\n return (event: CollectIdEvent): Promise<string> => {\n // Prevents multiple standalone components on the same page from making multiple calls to collect a checkoutAttemptId\n if (memoizedPromise !== null) {\n return memoizedPromise;\n }\n\n const telemetryEvent: TelemetryEvent = {\n version: process.env.VERSION,\n channel: 'Web',\n platform: 'Web',\n buildType: bundleType,\n locale,\n referrer: window.location.href,\n screenWidth: window.screen.width,\n ...event\n };\n\n memoizedPromise = httpPost<{ checkoutAttemptId: string }>(options, telemetryEvent).then(conversion => {\n if (conversion?.checkoutAttemptId) {\n return conversion.checkoutAttemptId;\n }\n throw new AdyenCheckoutError('NETWORK_ERROR', 'Analytics: Attempt ID request was successfully but no ID was returned');\n });\n\n return memoizedPromise;\n };\n};\n\nexport default collectId;\n"],"names":["FAILURE_MSG","collectId","analyticsContext","clientKey","locale","analyticsPath","bundleType","memoizedPromise","options","errorLevel","loadingContext","path","errorMessage","event","telemetryEvent","_object_spread","version","channel","platform","buildType","referrer","window","location","href","screenWidth","screen","width","httpPost","then","conversion","checkoutAttemptId","AdyenCheckoutError"],"mappings":"gNAIO,MAAMA,EACT,uKAOEC,EAAY,EAAGC,mBAAkBC,YAAWC,SAAQC,gBAAeC,iBACrE,IAAIC,EAA0C,KAE9C,MAAMC,EAAuB,CACzBC,WAAY,QACZC,eAAgBR,EAChBS,KAAM,GAAGN,eAA2BF,IACpCS,aAAcZ,GAGlB,OAAQa,IAEJ,GAAwB,OAApBN,EACA,OAAOA,EAGX,MAAMO,oUAAiCC,CAAA,CACnCC,QAAS,SACTC,QAAS,MACTC,SAAU,MACVC,UAAWb,EACXF,SACAgB,SAAUC,OAAOC,SAASC,KAC1BC,YAAaH,OAAOI,OAAOC,OACxBb,GAUP,OAPAN,EAAkBoB,EAAwCnB,EAASM,GAAgBc,KAAKC,IACpF,GAAIA,aAAAA,EAAAA,EAAYC,kBACZ,OAAOD,EAAWC,kBAEtB,MAAM,IAAIC,EAAmB,gBAAiB,2EAG3CxB"}
@@ -1,2 +1,2 @@
1
- import{Language as t}from"../language/Language.js";import o from"./RiskModule/RiskModule.js";import e from"./ProcessResponse/PaymentMethods/PaymentMethods.js";import{getComponentForAction as s}from"./ProcessResponse/PaymentAction/PaymentAction.js";import n from"./Analytics/Analytics.js";import{processGlobalOptions as i,assertConfigurationPropertiesAreValid as r}from"./utils.js";import a from"./CheckoutSession/CheckoutSession.js";import{hasOwnProperty as l}from"../utils/hasOwnProperty.js";import{Resources as c}from"./Context/Resources.js";import{SRPanel as h}from"./Errors/SRPanel.js";import p from"./core.registry.js";import{sanitizeResponse as d,verifyPaymentDidNotFail as m,cleanupFinalResult as u}from"../components/internal/UIElement/utils.js";import y,{IMPLEMENTATION_ERROR as f}from"./Errors/AdyenCheckoutError.js";import{ANALYTICS_ACTION_STR as g}from"./Analytics/constants.js";import{THREEDS2_FULL as v}from"../components/ThreeDS2/constants.js";import{DEFAULT_LOCALE as b}from"../language/constants.js";import C from"./Services/get-translations.js";import{defaultProps as j}from"./core.defaultProps.js";import{formatLocale as w,formatCustomTranslations as O}from"../language/utils.js";import{resolveEnvironments as P}from"./Environment/Environment.js";import{AnalyticsLogEvent as A}from"./Analytics/AnalyticsLogEvent.js";import E from"./Errors/CancelError.js";function M(t,o,e){return o in t?Object.defineProperty(t,o,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[o]=e,t}function T(t){for(var o=1;o<arguments.length;o++){var e=null!=arguments[o]?arguments[o]:{},s=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(s=s.concat(Object.getOwnPropertySymbols(e).filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.forEach(function(o){M(t,o,e[o])})}return t}function x(t,o){return o=null!=o?o:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):function(t){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(t);o.push.apply(o,e)}return o}(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))}),t}function R(t,o){if(null==t)return{};var e,s,n=function(t,o){if(null==t)return{};var e,s,n={},i=Object.keys(t);for(s=0;s<i.length;s++)e=i[s],o.indexOf(e)>=0||(n[e]=t[e]);return n}(t,o);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(s=0;s<i.length;s++)e=i[s],o.indexOf(e)>=0||Object.prototype.propertyIsEnumerable.call(t,e)&&(n[e]=t[e])}return n}class k{static setBundleType(t){k.metadata.bundleType=t}static register(...t){p.add(...t)}register(...t){p.add(...t)}getComponent(t){return p.getComponent(t)}async initialize(){return await this.initializeCore(),this.validateCoreConfiguration(),await this.createCoreModules(),this}async initializeCore(){return this.session?this.session.setupSession(this.options).then(t=>{const{amount:o,shopperLocale:e,countryCode:s,paymentMethods:n}=t,i=R(t,["amount","shopperLocale","countryCode","paymentMethods"]);return this.setOptions(x(T({},i),{amount:this.options.order?this.options.order.remainingAmount:o,locale:this.options.locale||e,countryCode:this.options.countryCode||s})),this.createPaymentMethodsList(n),this}).catch(t=>(this.options.onError&&this.options.onError(t),Promise.reject(t))):(this.createPaymentMethodsList(),Promise.resolve(this))}async fetchLocaleTranslations(){try{return await C(this.cdnTranslationsUrl,k.metadata.version,this.options.locale)}catch(n){var t,o,e,s;n instanceof y?null===(t=(o=this.options).onError)||void 0===t||t.call(o,n):null===(e=(s=this.options).onError)||void 0===e||e.call(s,new y("ERROR","Failed to fetch translation",{cause:n}))}}validateCoreConfiguration(){if(this.options.paymentMethodsConfiguration&&console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.'),!this.options.countryCode)throw new y(f,"You must specify a countryCode when initializing checkout.");this.options.locale||this.setOptions({locale:b}),this.options.locale=w(this.options.locale),this.options.translations=O(this.options.translations)}submitDetails(t){let o=null;var e,s;(this.options.onAdditionalDetails&&(o=new Promise((o,e)=>{this.options.onAdditionalDetails({data:t},void 0,{resolve:o,reject:e})})),this.session&&(o=this.session.submitDetails(t).catch(t=>{var o,e;return null===(o=(e=this.options).onError)||void 0===o||o.call(e,t),Promise.reject(t)})),o)?o.then(d).then(m).then(this.afterAdditionalDetails).then(t=>{var o,e;u(t),null===(o=(e=this.options).onPaymentCompleted)||void 0===o||o.call(e,t)}).catch(t=>{var o,e;t instanceof E||(u(t),null===(o=(e=this.options).onPaymentFailed)||void 0===o||o.call(e,t))}):null===(e=(s=this.options).onError)||void 0===e||e.call(s,new y("IMPLEMENTATION_ERROR",'It can not submit the details. The callback "onAdditionalDetails" or the Session is not setup correctly.'))}createFromAction(t,o={}){if(!t||!t.type){if(l(t,"action")&&l(t,"resultCode"))throw new Error('createFromAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('createFromAction::Invalid Action - the passed action object does not have a "type" property')}if(t.type){const e=t.type===v?`${t.type}${t.subtype}`:t.paymentMethodType,n=new A({type:g,subType:t.type,message:`${e} action was handled by the SDK`,component:e});this.modules.analytics.sendAnalytics(n);const i=T({},this.getCorePropsForComponent(),o);return s(this,p,t,i)}return this.handleCreateError()}getCorePropsForComponent(){return x(T({},i(this.options)),{core:this,i18n:this.modules.i18n,modules:this.modules,session:this.session,loadingContext:this.loadingContext,cdnContext:this.cdnImagesUrl,createFromAction:this.createFromAction})}storeElementReference(t){t&&this.components.push(t)}handleCreateError(t){var o;const e=null!==(o=null==t?void 0:t.name)&&void 0!==o?o:"The passed payment method",s=t?`${e} is not a valid Checkout Component. What was passed as a txVariant was: ${JSON.stringify(t)}. Check if this payment method is configured in the Backoffice or if the txVariant is a valid one`:"No Payment Method component was passed";throw new Error(s)}createPaymentMethodsList(t){this.paymentMethodsResponse=new e(this.options.paymentMethodsResponse||t,this.options)}async createCoreModules(){if(this.modules)return;const e=await this.fetchLocaleTranslations();this.modules=Object.freeze({risk:new o(this,x(T({},this.options),{loadingContext:this.loadingContext})),analytics:n({loadingContext:this.loadingContext,analyticsContext:this.analyticsContext,clientKey:this.options.clientKey,locale:this.options.locale,analytics:this.options.analytics,amount:this.options.amount,bundleType:k.metadata.bundleType}),resources:new c(this.cdnImagesUrl),i18n:new t({locale:this.options.locale,translations:e,customTranslations:this.options.translations}),srPanel:new h(this,T({},this.options.srConfig))})}constructor(t){var o;M(this,"session",void 0),M(this,"paymentMethodsResponse",void 0),M(this,"modules",void 0),M(this,"options",void 0),M(this,"analyticsContext",void 0),M(this,"loadingContext",void 0),M(this,"cdnImagesUrl",void 0),M(this,"cdnTranslationsUrl",void 0),M(this,"components",[]),M(this,"afterAdditionalDetails",t=>{if(this.options.afterAdditionalDetails&&(null==t?void 0:t.action)){const o=this.createFromAction(t.action);return this.options.afterAdditionalDetails(o),Promise.reject(new E("Handled by afterAdditionalDetails"))}return Promise.resolve(t)}),M(this,"update",(t={})=>(this.setOptions(t),this.initialize().then(()=>(this.components.forEach(o=>{const e=T({},t,this.session&&{session:this.session});o.update(e)}),this)))),M(this,"remove",t=>(this.components=this.components.filter(o=>o._id!==t._id),t.unmount(),this)),M(this,"setOptions",t=>{var o;this.options=x(T({},this.options,t),{locale:(null==t?void 0:t.locale)||(null===(o=this.options)||void 0===o?void 0:o.locale)})}),r(t),this.createFromAction=this.createFromAction.bind(this),this.setOptions(T({},j,t));const{apiUrl:e,analyticsUrl:s,cdnImagesUrl:n,cdnTranslationsUrl:i}=P(this.options.environment,this.options._environmentUrls);this.loadingContext=e,this.analyticsContext=s,this.cdnImagesUrl=n,this.cdnTranslationsUrl=i,this.session=this.options.session&&new a(this.options.session,this.options.clientKey,this.loadingContext);const l=null===(o=this.options.clientKey)||void 0===o?void 0:o.substring(0,4);var c,h;if(("test"===l||"live"===l)&&!this.loadingContext.includes(l))throw new y("IMPLEMENTATION_ERROR",`Error: you are using a ${l} clientKey against the ${(null===(c=this.options._environmentUrls)||void 0===c?void 0:c.api)||this.options.environment} environment`);"pub."===l&&console.debug(`The value you are passing as your "clientKey" looks like an originKey (${null===(h=this.options.clientKey)||void 0===h?void 0:h.substring(0,12)}..). Although this is supported it is not the recommended way to integrate. To generate a clientKey, see the documentation (https://docs.adyen.com/development-resources/client-side-authentication/migrate-from-origin-key-to-client-key/) for more details.`);this.options.exposeLibraryMetadata&&(window.AdyenWebMetadata=k.metadata)}}M(k,"metadata",{version:"6.20.0",bundleType:"eslegacy"}),M(k,"registry",p);export{k as default};
1
+ import{Language as t}from"../language/Language.js";import o from"./RiskModule/RiskModule.js";import e from"./ProcessResponse/PaymentMethods/PaymentMethods.js";import{getComponentForAction as s}from"./ProcessResponse/PaymentAction/PaymentAction.js";import i from"./Analytics/Analytics.js";import{processGlobalOptions as n,assertConfigurationPropertiesAreValid as r}from"./utils.js";import a from"./CheckoutSession/CheckoutSession.js";import{hasOwnProperty as l}from"../utils/hasOwnProperty.js";import{Resources as c}from"./Context/Resources.js";import{SRPanel as h}from"./Errors/SRPanel.js";import p from"./core.registry.js";import{sanitizeResponse as d,verifyPaymentDidNotFail as m,cleanupFinalResult as u}from"../components/internal/UIElement/utils.js";import y,{IMPLEMENTATION_ERROR as f}from"./Errors/AdyenCheckoutError.js";import{ANALYTICS_ACTION_STR as v}from"./Analytics/constants.js";import{THREEDS2_FULL as g}from"../components/ThreeDS2/constants.js";import{DEFAULT_LOCALE as b}from"../language/constants.js";import C from"./Services/get-translations.js";import{defaultProps as j}from"./core.defaultProps.js";import{formatLocale as w,formatCustomTranslations as O}from"../language/utils.js";import{resolveEnvironments as P}from"./Environment/Environment.js";import{AnalyticsLogEvent as A}from"./Analytics/AnalyticsLogEvent.js";import E from"./Errors/CancelError.js";function M(t,o,e){return o in t?Object.defineProperty(t,o,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[o]=e,t}function T(t){for(var o=1;o<arguments.length;o++){var e=null!=arguments[o]?arguments[o]:{},s=Object.keys(e);"function"==typeof Object.getOwnPropertySymbols&&(s=s.concat(Object.getOwnPropertySymbols(e).filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.forEach(function(o){M(t,o,e[o])})}return t}function x(t,o){return o=null!=o?o:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):function(t){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(t);o.push.apply(o,e)}return o}(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))}),t}function R(t,o){if(null==t)return{};var e,s,i=function(t,o){if(null==t)return{};var e,s,i={},n=Object.keys(t);for(s=0;s<n.length;s++)e=n[s],o.indexOf(e)>=0||(i[e]=t[e]);return i}(t,o);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(s=0;s<n.length;s++)e=n[s],o.indexOf(e)>=0||Object.prototype.propertyIsEnumerable.call(t,e)&&(i[e]=t[e])}return i}class k{static setBundleType(t){k.metadata.bundleType=t}static register(...t){p.add(...t)}register(...t){p.add(...t)}getComponent(t){return p.getComponent(t)}async initialize(){return await this.initializeCore(),this.validateCoreConfiguration(),await this.createCoreModules(),this}async initializeCore(){return this.session?this.session.setupSession(this.options).then(t=>{const{amount:o,shopperLocale:e,countryCode:s,paymentMethods:i}=t,n=R(t,["amount","shopperLocale","countryCode","paymentMethods"]);return this.setOptions(x(T({},n),{amount:this.options.order?this.options.order.remainingAmount:o,locale:this.options.locale||e,countryCode:this.options.countryCode||s})),this.createPaymentMethodsList(i),this}).catch(t=>(this.options.onError&&this.options.onError(t),Promise.reject(t))):(this.createPaymentMethodsList(),Promise.resolve(this))}async fetchLocaleTranslations(){try{return await C(this.cdnTranslationsUrl,k.metadata.version,this.options.locale)}catch(i){var t,o,e,s;i instanceof y?null===(t=(o=this.options).onError)||void 0===t||t.call(o,i):null===(e=(s=this.options).onError)||void 0===e||e.call(s,new y("ERROR","Failed to fetch translation",{cause:i}))}}validateCoreConfiguration(){if(this.options.paymentMethodsConfiguration&&console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.'),!this.options.countryCode)throw new y(f,"You must specify a countryCode when initializing checkout.");this.options.locale||this.setOptions({locale:b}),this.options.locale=w(this.options.locale),this.options.translations=O(this.options.translations)}submitDetails(t){let o=null;var e,s;(this.options.onAdditionalDetails&&(o=new Promise((o,e)=>{this.options.onAdditionalDetails({data:t},void 0,{resolve:o,reject:e})})),this.session&&(o=this.session.submitDetails(t).catch(t=>{var o,e;return null===(o=(e=this.options).onError)||void 0===o||o.call(e,t),Promise.reject(t)})),o)?o.then(d).then(m).then(this.afterAdditionalDetails).then(t=>{var o,e;u(t),null===(o=(e=this.options).onPaymentCompleted)||void 0===o||o.call(e,t)}).catch(t=>{var o,e;t instanceof E||(u(t),null===(o=(e=this.options).onPaymentFailed)||void 0===o||o.call(e,t))}):null===(e=(s=this.options).onError)||void 0===e||e.call(s,new y("IMPLEMENTATION_ERROR",'It can not submit the details. The callback "onAdditionalDetails" or the Session is not setup correctly.'))}createFromAction(t,o={}){if(!t||!t.type){if(l(t,"action")&&l(t,"resultCode"))throw new Error('createFromAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('createFromAction::Invalid Action - the passed action object does not have a "type" property')}if(t.type){const e=t.type===g?`${t.type}${t.subtype}`:t.paymentMethodType,i=new A({type:v,subType:t.type,message:`${e} action was handled by the SDK`,component:e});this.modules.analytics.sendAnalytics(i);const n=T({},this.getCorePropsForComponent(),o);return s(this,p,t,n)}return this.handleCreateError()}getCorePropsForComponent(){return x(T({},n(this.options)),{core:this,i18n:this.modules.i18n,modules:this.modules,session:this.session,loadingContext:this.loadingContext,cdnContext:this.cdnImagesUrl,createFromAction:this.createFromAction})}storeElementReference(t){t&&this.components.push(t)}handleCreateError(t){var o;const e=null!==(o=null==t?void 0:t.name)&&void 0!==o?o:"The passed payment method",s=t?`${e} is not a valid Checkout Component. What was passed as a txVariant was: ${JSON.stringify(t)}. Check if this payment method is configured in the Backoffice or if the txVariant is a valid one`:"No Payment Method component was passed";throw new Error(s)}createPaymentMethodsList(t){this.paymentMethodsResponse=new e(this.options.paymentMethodsResponse||t,this.options)}async createCoreModules(){if(this.modules)return;const e=await this.fetchLocaleTranslations();this.modules=Object.freeze({risk:new o(this,x(T({},this.options),{loadingContext:this.loadingContext})),analytics:i({analyticsContext:this.analyticsContext,clientKey:this.options.clientKey,locale:this.options.locale,analytics:this.options.analytics,bundleType:k.metadata.bundleType}),resources:new c(this.cdnImagesUrl),i18n:new t({locale:this.options.locale,translations:e,customTranslations:this.options.translations}),srPanel:new h(this,T({},this.options.srConfig))})}constructor(t){var o;M(this,"session",void 0),M(this,"paymentMethodsResponse",void 0),M(this,"modules",void 0),M(this,"options",void 0),M(this,"analyticsContext",void 0),M(this,"loadingContext",void 0),M(this,"cdnImagesUrl",void 0),M(this,"cdnTranslationsUrl",void 0),M(this,"components",[]),M(this,"afterAdditionalDetails",t=>{if(this.options.afterAdditionalDetails&&(null==t?void 0:t.action)){const o=this.createFromAction(t.action);return this.options.afterAdditionalDetails(o),Promise.reject(new E("Handled by afterAdditionalDetails"))}return Promise.resolve(t)}),M(this,"update",(t={})=>(this.setOptions(t),this.initialize().then(()=>(this.components.forEach(o=>{const e=T({},t,this.session&&{session:this.session});o.update(e)}),this)))),M(this,"remove",t=>(this.components=this.components.filter(o=>o._id!==t._id),t.unmount(),this)),M(this,"setOptions",t=>{var o;this.options=x(T({},this.options,t),{locale:(null==t?void 0:t.locale)||(null===(o=this.options)||void 0===o?void 0:o.locale)})}),r(t),this.createFromAction=this.createFromAction.bind(this),this.setOptions(T({},j,t));const{apiUrl:e,analyticsUrl:s,cdnImagesUrl:i,cdnTranslationsUrl:n}=P(this.options.environment,this.options._environmentUrls);this.loadingContext=e,this.analyticsContext=s,this.cdnImagesUrl=i,this.cdnTranslationsUrl=n,this.session=this.options.session&&new a(this.options.session,this.options.clientKey,this.loadingContext);const l=null===(o=this.options.clientKey)||void 0===o?void 0:o.substring(0,4);var c,h;if(("test"===l||"live"===l)&&!this.loadingContext.includes(l))throw new y("IMPLEMENTATION_ERROR",`Error: you are using a ${l} clientKey against the ${(null===(c=this.options._environmentUrls)||void 0===c?void 0:c.api)||this.options.environment} environment`);"pub."===l&&console.debug(`The value you are passing as your "clientKey" looks like an originKey (${null===(h=this.options.clientKey)||void 0===h?void 0:h.substring(0,12)}..). Although this is supported it is not the recommended way to integrate. To generate a clientKey, see the documentation (https://docs.adyen.com/development-resources/client-side-authentication/migrate-from-origin-key-to-client-key/) for more details.`);this.options.exposeLibraryMetadata&&(window.AdyenWebMetadata=k.metadata)}}M(k,"metadata",{version:"6.22.0",bundleType:"eslegacy"}),M(k,"registry",p);export{k as default};
2
2
  //# sourceMappingURL=core.js.map