diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b2227891..163060c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## [0.38.2](https://github.com/juspay/hyperswitch-web/compare/v0.38.1...v0.38.2) (2024-04-05) + ## [0.38.1](https://github.com/juspay/hyperswitch-web/compare/v0.38.0...v0.38.1) (2024-04-04) diff --git a/package-lock.json b/package-lock.json index dce023300..de37d5bce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.38.1", + "version": "0.38.2", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -2870,21 +2870,6 @@ "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "dev": true }, - "color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "requires": { - "color-name": "~1.1.4" - } - }, - "color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, "emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", @@ -2902,40 +2887,6 @@ "strip-ansi": "^7.0.1" } }, - "string-width-cjs": { - "version": "npm:string-width@4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - } - } - }, "strip-ansi": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", @@ -2945,23 +2896,6 @@ "ansi-regex": "^6.0.1" } }, - "strip-ansi-cjs": { - "version": "npm:strip-ansi@6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - } - } - }, "wrap-ansi": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", @@ -2972,60 +2906,6 @@ "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } - }, - "wrap-ansi-cjs": { - "version": "npm:wrap-ansi@7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "requires": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true - }, - "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "requires": { - "color-convert": "^2.0.1" - } - }, - "emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "requires": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - } - }, - "strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "requires": { - "ansi-regex": "^5.0.1" - } - } - } } } }, @@ -20972,6 +20852,17 @@ "strip-ansi": "^6.0.1" } }, + "string-width-cjs": { + "version": "npm:string-width@4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, "string.prototype.matchall": { "version": "4.0.11", "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.11.tgz", @@ -21063,6 +20954,15 @@ "ansi-regex": "^5.0.1" } }, + "strip-ansi-cjs": { + "version": "npm:strip-ansi@6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.1" + } + }, "strip-bom": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", @@ -23630,6 +23530,43 @@ } } }, + "wrap-ansi-cjs": { + "version": "npm:wrap-ansi@7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + } + } + }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/package.json b/package.json index 73cdabccf..5bf216194 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca-payment-page", - "version": "0.38.1", + "version": "0.38.2", "main": "index.js", "private": true, "dependencies": { diff --git a/src/BrowserSpec.res b/src/BrowserSpec.res index 02f7f1bfc..64212c9a4 100644 --- a/src/BrowserSpec.res +++ b/src/BrowserSpec.res @@ -15,7 +15,7 @@ let checkIsSafari = () => { let userAgentString = navigator.userAgent let chromeAgent = userAgentString->String.indexOf("Chrome") > -1 let safariAgent = userAgentString->String.indexOf("Safari") > -1 - chromeAgent && safariAgent ? false : safariAgent ? true : false + !chromeAgent && safariAgent } let date = date() diff --git a/src/BrutalTheme.res b/src/BrutalTheme.res index c13da8e99..2059bacfd 100644 --- a/src/BrutalTheme.res +++ b/src/BrutalTheme.res @@ -173,7 +173,7 @@ let brutalRules = (theme: CardThemeType.themeClass) => "borderTopColor": "transparent !important", "borderLeftColor": "transparent !important", }, - }->toJson + }->Identity.anyTypeToJson let default = brutal let defaultRules = brutalRules diff --git a/src/CardTheme.res b/src/CardTheme.res index 005251657..25245d06f 100644 --- a/src/CardTheme.res +++ b/src/CardTheme.res @@ -293,8 +293,8 @@ let getVariables = (str, dict, default, logger) => { let getAppearance = ( str, dict, - default: OrcaPaymentPage.CardThemeType.themeClass, - defaultRules: OrcaPaymentPage.CardThemeType.themeClass => JSON.t, + default: CardThemeType.themeClass, + defaultRules: CardThemeType.themeClass => JSON.t, logger, ) => { dict @@ -341,8 +341,8 @@ let getFonts = (str, dict, logger) => { } let itemToObjMapper = ( dict, - default: OrcaPaymentPage.CardThemeType.themeClass, - defaultRules: OrcaPaymentPage.CardThemeType.themeClass => JSON.t, + default: CardThemeType.themeClass, + defaultRules: CardThemeType.themeClass => JSON.t, logger, ) => { unknownKeysWarning( diff --git a/src/CardUtils.res b/src/CardUtils.res index 763b476eb..b77f1d6a1 100644 --- a/src/CardUtils.res +++ b/src/CardUtils.res @@ -91,7 +91,7 @@ let getQueryParamsDictforKey = (searchParams, keyName) => { dict->Dict.get(keyName)->Option.getOr("") } -let cardType = val => { +let getCardType = val => { switch val { | "Visa" => VISA | "Mastercard" => MASTERCARD @@ -197,7 +197,7 @@ let formatExpiryToTwoDigit = expiry => { } } -let isExipryComplete = val => { +let isExpiryComplete = val => { let (month, year) = splitExpiryDates(val) month->String.length == 2 && year->String.length == 2 } @@ -316,29 +316,30 @@ let calculateLuhn = value => { let getCardBrandIcon = (cardType, paymentType) => { open CardThemeType + open Utils switch cardType { - | VISA => - | MASTERCARD => - | AMEX => - | MAESTRO => - | DINERSCLUB => - | DISCOVER => - | BAJAJ => - | SODEXO => - | RUPAY => - | JCB => - | CARTESBANCAIRES => - | UNIONPAY => - | INTERAC => + | VISA => + | MASTERCARD => + | AMEX => + | MAESTRO => + | DINERSCLUB => + | DISCOVER => + | BAJAJ => + | SODEXO => + | RUPAY => + | JCB => + | CARTESBANCAIRES => + | UNIONPAY => + | INTERAC => | NOTFOUND => switch paymentType { - | Payment => + | Payment => | Card | CardNumberElement | CardExpiryElement | CardCVCElement | NONE => - + } } } @@ -359,7 +360,7 @@ let getExpiryValidity = cardExpiry => { valid } let isExipryValid = val => { - val->String.length > 0 && getExpiryValidity(val) && isExipryComplete(val) + val->String.length > 0 && getExpiryValidity(val) && isExpiryComplete(val) } let cardNumberInRange = val => { @@ -371,7 +372,7 @@ let cardNumberInRange = val => { cardLengthInRange } let max = (a, b) => { - a > b ? a : b + Math.Int.max(a, b) } let getMaxLength = val => { @@ -426,7 +427,7 @@ let genreateFontsLink = (fonts: array) => { } let maxCardLength = cardBrand => { let obj = getobjFromCardPattern(cardBrand) - Array.reduce(obj.length, 0, (acc, val) => acc > val ? acc : val) + Array.reduce(obj.length, 0, (acc, val) => max(acc, val)) } let cardValid = (cardNumber, cardBrand) => { @@ -543,9 +544,9 @@ let setCardValid = (cardnumber, setIsCardValid) => { let setExpiryValid = (expiry, setIsExpiryValid) => { if isExipryValid(expiry) { setIsExpiryValid(_ => Some(true)) - } else if !getExpiryValidity(expiry) && isExipryComplete(expiry) { + } else if !getExpiryValidity(expiry) && isExpiryComplete(expiry) { setIsExpiryValid(_ => Some(false)) - } else if !isExipryComplete(expiry) { + } else if !isExpiryComplete(expiry) { setIsExpiryValid(_ => None) } } @@ -571,25 +572,23 @@ let clientTimeZone = dateTimeFormat().resolvedOptions().timeZone let clientCountry = Utils.getClientCountry(clientTimeZone) let postalRegex = (postalCodes: array, ~country=?, ()) => { - let country = switch country { - | Some(val) => val - | None => clientCountry.isoAlpha2 - } + let country = country->Option.getOr(clientCountry.isoAlpha2) let countryPostal = Utils.getCountryPostal(country, postalCodes) - countryPostal.regex == "" ? "" : countryPostal.regex + countryPostal.regex } let setRightIconForCvc = (~cardEmpty, ~cardInvalid, ~color, ~cardComplete) => { + open Utils if cardEmpty { - + } else if cardInvalid {
- +
} else if cardComplete { - + } else { - + } } diff --git a/src/CharcoalTheme.res b/src/CharcoalTheme.res index 2711ef31e..172a0bb61 100644 --- a/src/CharcoalTheme.res +++ b/src/CharcoalTheme.res @@ -173,7 +173,7 @@ let charcoalRules = theme => "fontWeight": theme.fontWeightLight, "fontSize": theme.fontSizeLg, }, - }->toJson + }->Identity.anyTypeToJson let default = charcoal let defaultRules = charcoalRules diff --git a/src/Components/AddressPaymentInput.res b/src/Components/AddressPaymentInput.res index e9783d719..a24b4d0d0 100644 --- a/src/Components/AddressPaymentInput.res +++ b/src/Components/AddressPaymentInput.res @@ -67,9 +67,7 @@ let make = (~paymentType, ~className="") => { let checkPostalValidity = ( postal: RecoilAtomTypes.field, - setPostal: ( - OrcaPaymentPage.RecoilAtomTypes.field => OrcaPaymentPage.RecoilAtomTypes.field - ) => unit, + setPostal: (RecoilAtomTypes.field => RecoilAtomTypes.field) => unit, regex, ) => { if RegExp.test(regex->RegExp.fromString, postal.value) && postal.value !== "" && regex !== "" { @@ -168,7 +166,7 @@ let make = (~paymentType, ~className="") => { let submitCallback = React.useCallback((ev: Window.event) => { let json = ev.data->JSON.parseExn - let confirm = json->Utils.getDictFromJson->ConfirmType.itemToObjMapper + let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit { if line1.value == "" { setLine1(prev => { diff --git a/src/Components/BlikCodePaymentInput.res b/src/Components/BlikCodePaymentInput.res index 455ed147c..a4439b193 100644 --- a/src/Components/BlikCodePaymentInput.res +++ b/src/Components/BlikCodePaymentInput.res @@ -42,7 +42,7 @@ let make = () => { let submitCallback = React.useCallback((ev: Window.event) => { let json = ev.data->JSON.parseExn - let confirm = json->Utils.getDictFromJson->ConfirmType.itemToObjMapper + let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit { if blikCode.value == "" { setblikCode(prev => { diff --git a/src/Components/DynamicFields.res b/src/Components/DynamicFields.res index bef9f90ae..0a5a1dcac 100644 --- a/src/Components/DynamicFields.res +++ b/src/Components/DynamicFields.res @@ -13,6 +13,7 @@ let make = ( ~cvcProps=None, ~isBancontact=false, ) => { + open Utils React.useEffect(() => { setRequiredFieldsBody(_ => Dict.make()) None @@ -125,9 +126,8 @@ let make = ( let (stateJson, setStatesJson) = React.useState(_ => None) - let bankNames = - Bank.getBanks(paymentMethodType)->Utils.getBankNames(paymentMethodTypes.bank_names) - let countryNames = Utils.getCountryNames(Country.getCountry(paymentMethodType)) + let bankNames = Bank.getBanks(paymentMethodType)->getBankNames(paymentMethodTypes.bank_names) + let countryNames = getCountryNames(Country.getCountry(paymentMethodType)) let setCurrency = val => { setCurrency(val) @@ -226,11 +226,7 @@ let make = ( None }) - let _regex = CardUtils.postalRegex( - postalCodes, - ~country={Utils.getCountryCode(country).isoAlpha2}, - (), - ) + let _regex = CardUtils.postalRegex(postalCodes, ~country={getCountryCode(country).isoAlpha2}, ()) let onPostalChange = ev => { let val = ReactEvent.Form.target(ev)["value"] @@ -282,7 +278,7 @@ let make = ( ) let submitCallback = DynamicFieldsUtils.useSubmitCallback() - Utils.useSubmitPaymentData(submitCallback) + useSubmitPaymentData(submitCallback) let bottomElement = @@ -518,7 +514,7 @@ let make = ( fieldName=localeString.stateLabel value=state setValue=setState - options={options->Utils.getStateNames({ + options={options->getStateNames({ value: country, isValid: None, errorString: "", @@ -640,7 +636,7 @@ let make = ( fieldName=localeString.stateLabel value=state setValue=setState - options={options->Utils.getStateNames({ + options={options->getStateNames({ value: country, isValid: None, errorString: "", diff --git a/src/Components/EmailPaymentInput.res b/src/Components/EmailPaymentInput.res index ac8b7945a..367f34468 100644 --- a/src/Components/EmailPaymentInput.res +++ b/src/Components/EmailPaymentInput.res @@ -17,15 +17,15 @@ let make = (~paymentType) => { let val: string = ReactEvent.Form.target(ev)["value"] setEmail(prev => { value: val, - isValid: val->Utils.isEmailValid, - errorString: val->Utils.isEmailValid->Option.getOr(false) ? "" : prev.errorString, + isValid: val->isEmailValid, + errorString: val->isEmailValid->Option.getOr(false) ? "" : prev.errorString, }) } let onBlur = ev => { let val = ReactEvent.Focus.target(ev)["value"] setEmail(prev => { ...prev, - isValid: val->Utils.isEmailValid, + isValid: val->isEmailValid, }) } @@ -42,7 +42,7 @@ let make = (~paymentType) => { let submitCallback = React.useCallback((ev: Window.event) => { let json = ev.data->JSON.parseExn - let confirm = json->Utils.getDictFromJson->ConfirmType.itemToObjMapper + let confirm = json->getDictFromJson->ConfirmType.itemToObjMapper if confirm.doSubmit { if email.value == "" { setEmail(prev => { diff --git a/src/Components/PayNowButton.res b/src/Components/PayNowButton.res index bb33eb92e..0c411e645 100644 --- a/src/Components/PayNowButton.res +++ b/src/Components/PayNowButton.res @@ -1,7 +1,5 @@ @send external postMessage: (Window.window, JSON.t, string) => unit = "postMessage" -external eventToJson: 'a => JSON.t = "%identity" - module Loader = { @react.component let make = () => { @@ -16,8 +14,8 @@ module Loader = { @react.component let make = () => { open RecoilAtoms + open Utils let (showLoader, setShowLoader) = React.useState(() => false) - let {themeObj, localeString} = configAtom->Recoil.useRecoilValueFromAtom let {sdkHandleConfirmPayment} = optionAtom->Recoil.useRecoilValueFromAtom let (isPayNowButtonDisable, setIsPayNowButtonDisable) = payNowButtonDisable->Recoil.useRecoilState @@ -26,8 +24,8 @@ let make = () => { let buttonText = sdkHandleConfirmPayment.buttonText->Option.getOr(localeString.payNowButton) let handleMessage = (event: Types.event) => { - let json = event.data->eventToJson->OrcaUtils.getStringfromjson("")->OrcaUtils.safeParse - let dict = json->Utils.getDictFromJson + let json = event.data->Identity.anyTypeToJson->getStringFromJson("")->safeParse + let dict = json->getDictFromJson switch dict->Dict.get("submitSuccessful") { | Some(_) => setIsPayNowButtonDisable(_ => false) @@ -40,7 +38,7 @@ let make = () => { setIsPayNowButtonDisable(_ => true) setShowLoader(_ => true) EventListenerManager.addSmartEventListener("message", handleMessage, "onSubmitSuccessful") - Utils.handlePostMessage([("handleSdkConfirm", confirmPayload)]) + handlePostMessage([("handleSdkConfirm", confirmPayload)]) }
diff --git a/src/Components/PaymentDropDownField.res b/src/Components/PaymentDropDownField.res index 53b48f4d0..d63b61037 100644 --- a/src/Components/PaymentDropDownField.res +++ b/src/Components/PaymentDropDownField.res @@ -2,9 +2,7 @@ open RecoilAtoms @react.component let make = ( ~value: RecoilAtomTypes.field, - ~setValue: ( - OrcaPaymentPage.RecoilAtomTypes.field => OrcaPaymentPage.RecoilAtomTypes.field - ) => unit, + ~setValue: (RecoilAtomTypes.field => RecoilAtomTypes.field) => unit, ~fieldName, ~options, ~disabled=false, diff --git a/src/Components/SavedCardItem.res b/src/Components/SavedCardItem.res index d14cd0cfa..c4f9efa17 100644 --- a/src/Components/SavedCardItem.res +++ b/src/Components/SavedCardItem.res @@ -167,7 +167,7 @@ let make = ( list paymentMethod=paymentItem.paymentMethod paymentMethodType - cardBrand={cardBrand->CardUtils.cardType} + cardBrand={cardBrand->CardUtils.getCardType} />
diff --git a/src/Components/SavedMethods.res b/src/Components/SavedMethods.res index e98fe2dad..944506758 100644 --- a/src/Components/SavedMethods.res +++ b/src/Components/SavedMethods.res @@ -43,7 +43,7 @@ let make = ( switch obj.card.scheme { | Some(ele) => ele | None => "" - }->cardType, + }->getCardType, ""->CardTheme.getPaymentMode, ) } @@ -130,9 +130,9 @@ let make = ( ~bodyArr=savedPaymentMethodBody ->Dict.fromArray ->JSON.Encode.object - ->OrcaUtils.flattenObject(true) - ->OrcaUtils.mergeTwoFlattenedJsonDicts(requiredFieldsBody) - ->OrcaUtils.getArrayOfTupleFromDict, + ->flattenObject(true) + ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) + ->getArrayOfTupleFromDict, ~confirmParam=confirm.confirmParams, ~handleUserError=false, (), diff --git a/src/DefaultTheme.res b/src/DefaultTheme.res index 99dd6bc17..791bf7070 100644 --- a/src/DefaultTheme.res +++ b/src/DefaultTheme.res @@ -185,7 +185,7 @@ let defaultRules = theme => "fontWeight": theme.fontWeightLight, "fontSize": theme.fontSizeLg, }, - }->toJson + }->Identity.anyTypeToJson let default = default let defaultRules = defaultRules diff --git a/src/Hooks/CommonHooks.res b/src/Hooks/CommonHooks.res index 523895a17..e25667f9b 100644 --- a/src/Hooks/CommonHooks.res +++ b/src/Hooks/CommonHooks.res @@ -28,8 +28,6 @@ external addEventListener: (element, string, event => unit) => unit = "addEventL @send external removeEventListener: (element, string, event => unit) => unit = "removeEventListener" -external dictToObj: Dict.t<'a> => {..} = "%identity" - let useScript = (src: string) => { let (status, setStatus) = React.useState(_ => src != "" ? "loading" : "idle") React.useEffect(() => { @@ -66,7 +64,7 @@ let useScript = (src: string) => { let updateKeys = (dict, keyPair, setKeys) => { let (key, value) = keyPair - let valueStr = value->JSON.Decode.string->Option.getOr("") + let valueStr = value->Utils.getStringFromJson("") let valueBool = default => value->JSON.Decode.bool->Option.getOr(default) if dict->Utils.getDictIsSome(key) { switch key { diff --git a/src/Hooks/OutsideClick.res b/src/Hooks/OutsideClick.res index a4c5fe87d..8ebf5c3c9 100644 --- a/src/Hooks/OutsideClick.res +++ b/src/Hooks/OutsideClick.res @@ -1,4 +1,3 @@ -external ffToDomType: {..} => Dom.node_like<'a> = "%identity" @send external contains: (Dom.element, {..}) => bool = "contains" type ref = diff --git a/src/LoaderController.res b/src/LoaderController.res index f4f7e3624..60e1430a5 100644 --- a/src/LoaderController.res +++ b/src/LoaderController.res @@ -23,7 +23,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let {config} = configAtom let {iframeId} = keys - let handlePostMessage = data => Utils.handlePostMessage(data, ~targetOrigin=keys.parentURL) + let handlePostMessage = data => handlePostMessage(data, ~targetOrigin=keys.parentURL) let setUserFullName = Recoil.useLoggedSetRecoilState(userFullName, "fullName", logger) let setUserEmail = Recoil.useLoggedSetRecoilState(userEmailAddress, "email", logger) @@ -56,7 +56,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime }) if optionsPayment.defaultValues.billingDetails.address.country === "" { let clientTimeZone = CardUtils.dateTimeFormat().resolvedOptions().timeZone - let clientCountry = Utils.getClientCountry(clientTimeZone) + let clientCountry = getClientCountry(clientTimeZone) setUserAddressCountry(prev => { ...prev, value: clientCountry.countryName, @@ -94,7 +94,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let (default, defaultRules) = (themeValues.default, themeValues.defaultRules) let config = CardTheme.itemToObjMapper(paymentOptions, default, defaultRules, logger) - let localeString = Utils.getWarningString(optionsDict, "locale", "", ~logger) + let optionsLocaleString = getWarningString(optionsDict, "locale", "", ~logger) let optionsAppearance = CardTheme.getAppearance( "appearance", @@ -105,7 +105,9 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime ) let appearance = optionsAppearance == CardTheme.defaultAppearance ? config.appearance : optionsAppearance - + let localeString = CardTheme.getLocaleObject( + optionsLocaleString == "" ? config.locale : optionsLocaleString, + ) setConfig(_ => { config: { appearance, @@ -115,9 +117,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime loader: config.loader, }, themeObj: appearance.variables, - localeString: localeString == "" - ? CardTheme.getLocaleObject(config.locale) - : CardTheme.getLocaleObject(localeString), + localeString, showLoader: config.loader == Auto || config.loader == Always, }) } @@ -128,7 +128,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime logger.setLogInitiated() let updatedState: PaymentType.loadType = switch paymentlist { | Loading => - showCardFormByDefault && Utils.checkPriorityList(paymentMethodOrder) ? SemiLoaded : Loading + showCardFormByDefault && checkPriorityList(paymentMethodOrder) ? SemiLoaded : Loading | x => x } let finalLoadLatency = if launchTime <= 0.0 { @@ -174,7 +174,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime CardUtils.genreateFontsLink(config.fonts) let dict = config.appearance.rules->getDictFromJson if dict->Dict.toArray->Array.length > 0 { - Utils.generateStyleSheet("", dict, "themestyle") + generateStyleSheet("", dict, "themestyle") } switch paymentMode->CardTheme.getPaymentMode { | Payment => () @@ -189,7 +189,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime ->Array.map(item => { let (class, dict) = item if dict->Dict.toArray->Array.length > 0 { - Utils.generateStyleSheet(class, dict, "widgetstyle")->ignore + generateStyleSheet(class, dict, "widgetstyle")->ignore } }) ->ignore @@ -243,7 +243,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime logger.setMetadata(metadata) } if dict->getDictIsSome("paymentOptions") { - let paymentOptions = dict->Utils.getDictFromObj("paymentOptions") + let paymentOptions = dict->getDictFromObj("paymentOptions") let clientSecret = getWarningString(paymentOptions, "clientSecret", "", ~logger) setKeys(prev => { @@ -252,7 +252,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime }) logger.setClientSecret(clientSecret) - switch OrcaUtils.getThemePromise(paymentOptions) { + switch getThemePromise(paymentOptions) { | Some(promise) => promise ->then(res => { @@ -267,7 +267,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime }) } } - let newLaunchTime = dict->Utils.getFloat("launchTime", 0.0) + let newLaunchTime = dict->getFloat("launchTime", 0.0) setLaunchTime(_ => newLaunchTime) let initLoadlatency = Date.now() -. newLaunchTime logger.setLogInfo( @@ -293,7 +293,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime ) } } else if dict->getDictIsSome("paymentOptions") { - let paymentOptions = dict->Utils.getDictFromObj("paymentOptions") + let paymentOptions = dict->getDictFromObj("paymentOptions") let clientSecret = getWarningString(paymentOptions, "clientSecret", "", ~logger) setKeys(prev => { @@ -302,7 +302,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime }) logger.setClientSecret(clientSecret) - switch OrcaUtils.getThemePromise(paymentOptions) { + switch getThemePromise(paymentOptions) { | Some(promise) => promise ->then(res => { @@ -326,18 +326,18 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime | Some(val) => setKeys(prev => { ...prev, - clientSecret: Some(val->JSON.Decode.string->Option.getOr("")), + clientSecret: Some(val->getStringFromJson("")), }) setConfig(prev => { ...prev, config: { ...prev.config, - clientSecret: val->JSON.Decode.string->Option.getOr(""), + clientSecret: val->getStringFromJson(""), }, }) | None => () } - switch OrcaUtils.getThemePromise(optionsDict) { + switch getThemePromise(optionsDict) { | Some(promise) => promise ->then(res => { @@ -370,11 +370,11 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime let updatedState: PaymentType.loadType = list == Dict.make()->JSON.Encode.object ? LoadError(list) - : switch list->Utils.getDictFromJson->Dict.get("error") { + : switch list->getDictFromJson->Dict.get("error") { | Some(_) => LoadError(list) | None => let isNonEmptyPaymentMethodList = - list->Utils.getDictFromJson->Utils.getArray("payment_methods")->Array.length > 0 + list->getDictFromJson->getArray("payment_methods")->Array.length > 0 isNonEmptyPaymentMethodList ? Loaded(list) : LoadError(list) } @@ -489,7 +489,7 @@ let make = (~children, ~paymentMode, ~setIntegrateErrorError, ~logger, ~initTime } React.useEffect(() => { - Utils.handlePostMessage([ + handlePostMessage([ ("iframeHeight", (divH +. 1.0)->JSON.Encode.float), ("iframeId", iframeId->JSON.Encode.string), ]) diff --git a/src/MidnightTheme.res b/src/MidnightTheme.res index 4b6c1201c..6c897f34f 100644 --- a/src/MidnightTheme.res +++ b/src/MidnightTheme.res @@ -194,7 +194,7 @@ let midnightRules = theme => "fontWeight": theme.fontWeightLight, "fontSize": theme.fontSizeLg, }, - }->toJson + }->Identity.anyTypeToJson let default = midnight let defaultRules = midnightRules diff --git a/src/Payment.res b/src/Payment.res index 7ef3f0763..2c8b333a0 100644 --- a/src/Payment.res +++ b/src/Payment.res @@ -49,11 +49,13 @@ let make = (~paymentMode, ~integrateError, ~logger) => { let brand = getCardBrand(cardNumber) let maxLength = getMaxLength(cardNumber) let isNotBancontact = selectedOption !== "bancontact_card" && brand == "" - ((brand == "" && !showFields) || !showFields) && isNotBancontact - ? (cardScheme, maxLength) - : (brand, maxLength) + !showFields && isNotBancontact ? (cardScheme, maxLength) : (brand, maxLength) }, (cardNumber, cardScheme, showFields)) + let cardType = React.useMemo1(() => { + cardBrand->getCardType + }, [cardBrand]) + let clientTimeZone = dateTimeFormat().resolvedOptions().timeZone let clientCountry = Utils.getClientCountry(clientTimeZone) @@ -94,7 +96,7 @@ let make = (~paymentMode, ~integrateError, ~logger) => { let changeCardNumber = ev => { let val = ReactEvent.Form.target(ev)["value"] logInputChangeInfo("cardNumber", logger) - let card = val->formatCardNumber(cardBrand->cardType) + let card = val->formatCardNumber(cardType) let clearValue = card->clearSpaces setCardValid(clearValue, setIsCardValid) if cardValid(clearValue, cardBrand) { @@ -293,7 +295,9 @@ let make = (~paymentMode, ~integrateError, ~logger) => { } } - let paymentType = paymentMode->getPaymentMode + let paymentType = React.useMemo1(() => { + paymentMode->getPaymentMode + }, [paymentMode]) React.useEffect0(() => { let handleFun = (ev: Window.event) => { @@ -338,31 +342,23 @@ let make = (~paymentMode, ~integrateError, ~logger) => { Utils.handleMessage(handleDoSubmit, "") }, (cardNumber, cvcNumber, cardExpiry, isCVCValid, isExpiryValid, isCardValid)) - let cardBrandIcon = getCardBrandIcon(cardBrand->cardType, paymentMode->getPaymentMode) - React.useEffect(() => { setCardError(_ => - switch isCardValid { - | Some(val) => val ? "" : localeString.inValidCardErrorText - | None => "" - } + isCardValid->Option.getOr(true) ? "" : localeString.inValidCardErrorText ) None }, [isCardValid]) React.useEffect(() => { setCvcError(_ => - switch isCVCValid { - | Some(val) => val ? "" : localeString.inCompleteCVCErrorText - | None => "" - } + isCVCValid->Option.getOr(true) ? "" : localeString.inCompleteCVCErrorText ) None }, [isCVCValid]) React.useEffect(() => { setExpiryError(_ => - switch (isExpiryValid, isExipryComplete(cardExpiry)) { + switch (isExpiryValid, isExpiryComplete(cardExpiry)) { | (Some(true), true) => "" | (Some(false), true) => localeString.pastExpiryErrorText | (Some(_), false) => localeString.inCompleteExpiryErrorText @@ -370,10 +366,13 @@ let make = (~paymentMode, ~integrateError, ~logger) => { } ) None - }, (isExpiryValid, isExipryComplete(cardExpiry))) + }, (isExpiryValid, isExpiryComplete(cardExpiry))) - let animate = cardBrand->cardType == NOTFOUND ? "animate-slideLeft" : "animate-slideRight" - let icon =
cardBrandIcon
+ let icon = React.useMemo(() => { + let animate = cardType == NOTFOUND ? "animate-slideLeft" : "animate-slideRight" + let cardBrandIcon = getCardBrandIcon(cardType, paymentType) +
cardBrandIcon
+ }, (cardType, paymentType)) let cardProps: CardUtils.cardProps = ( isCardValid, diff --git a/src/Payments/ApplePay.res b/src/Payments/ApplePay.res index cbbbc9ae5..a3a985a23 100644 --- a/src/Payments/ApplePay.res +++ b/src/Payments/ApplePay.res @@ -76,9 +76,9 @@ let make = ( requestBody ->Dict.fromArray ->JSON.Encode.object - ->OrcaUtils.flattenObject(true) - ->OrcaUtils.mergeTwoFlattenedJsonDicts(requiredFieldsBody) - ->OrcaUtils.getArrayOfTupleFromDict + ->flattenObject(true) + ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) + ->getArrayOfTupleFromDict intent( ~bodyArr=requiredFieldsBodyArr, ~confirmParam={ @@ -246,7 +246,7 @@ let make = ( ) setApplePayClicked(_ => true) open Promise - OrcaUtils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) + makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) ->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { @@ -363,38 +363,36 @@ let make = ( }, (areRequiredFieldsValid, areRequiredFieldsEmpty)) useSubmitPaymentData(submitCallback) - { - isWallet - ?
- - {if showApplePay { - if showApplePayLoader { -
-
-
- } else { - - } - } else { - React.null - }} -
- : val - | _ => NONE - }} - list - paymentMethod="wallet" - paymentMethodType="apple_pay" - setRequiredFieldsBody - /> + if isWallet { +
+ + + {if showApplePayLoader { +
+
+
+ } else { + + }} + +
+ } else { + val + | _ => NONE + }} + list + paymentMethod="wallet" + paymentMethodType="apple_pay" + setRequiredFieldsBody + /> } } diff --git a/src/Payments/CardPayment.res b/src/Payments/CardPayment.res index 00f4550cd..528aaee35 100644 --- a/src/Payments/CardPayment.res +++ b/src/Payments/CardPayment.res @@ -144,9 +144,9 @@ let make = ( (isBancontact ? banContactBody : cardBody) ->Dict.fromArray ->JSON.Encode.object - ->OrcaUtils.flattenObject(true) - ->OrcaUtils.mergeTwoFlattenedJsonDicts(requiredFieldsBody) - ->OrcaUtils.getArrayOfTupleFromDict + ->flattenObject(true) + ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) + ->getArrayOfTupleFromDict }, ~confirmParam=confirm.confirmParams, ~handleUserError=false, @@ -288,7 +288,9 @@ let make = (
- CardUtils.cardType} /> + CardUtils.getCardType} + /> {switch (list.mandate_payment, options.terms.card) { diff --git a/src/Payments/GPay.res b/src/Payments/GPay.res index 5cc0bbfba..000c597d9 100644 --- a/src/Payments/GPay.res +++ b/src/Payments/GPay.res @@ -99,9 +99,9 @@ let make = ( gPayBody ->Dict.fromArray ->JSON.Encode.object - ->OrcaUtils.flattenObject(true) - ->OrcaUtils.mergeTwoFlattenedJsonDicts(requiredFieldsBody) - ->OrcaUtils.getArrayOfTupleFromDict + ->flattenObject(true) + ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) + ->getArrayOfTupleFromDict } processPayment(body) } @@ -124,7 +124,7 @@ let make = ( } let getGooglePaymentsClient = () => { - google({"environment": GlobalVars.isProd ? "PRODUCTION" : "TEST"}->toJson) + google({"environment": GlobalVars.isProd ? "PRODUCTION" : "TEST"}->Identity.anyTypeToJson) } let syncPayment = () => { @@ -146,7 +146,7 @@ let make = ( (), ) open Promise - OrcaUtils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment)->then(result => { + makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment)->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { if isInvokeSDKFlow { @@ -192,7 +192,7 @@ let make = ( "buttonSizeMode": "fill", "buttonColor": options.wallets.style.theme == Dark ? "black" : "white", } - obj->toJson + obj->Identity.anyTypeToJson } let addGooglePayButton = () => { let paymentClient = getGooglePaymentsClient() diff --git a/src/Payments/PayPal.res b/src/Payments/PayPal.res index b1f7f4e81..2ffb110ff 100644 --- a/src/Payments/PayPal.res +++ b/src/Payments/PayPal.res @@ -41,7 +41,7 @@ let make = (~list: PaymentMethodsRecord.list) => { ) setPaypalClicked(_ => true) open Promise - OrcaUtils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) + Utils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) ->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { diff --git a/src/Payments/PaymentMethodsRecord.res b/src/Payments/PaymentMethodsRecord.res index b77b5ddff..6fff42908 100644 --- a/src/Payments/PaymentMethodsRecord.res +++ b/src/Payments/PaymentMethodsRecord.res @@ -819,7 +819,7 @@ let getCardNetworks = (dict, str) => { ->Belt.Array.keepMap(JSON.Decode.object) ->Array.map(json => { { - card_network: getString(json, "card_network", "")->CardUtils.cardType, + card_network: getString(json, "card_network", "")->CardUtils.getCardType, eligible_connectors: getStrArray(json, "eligible_connectors"), surcharge_details: json->getSurchargeDetails, } diff --git a/src/Payments/PaymentMethodsWrapper.res b/src/Payments/PaymentMethodsWrapper.res index c1af482ff..6367a0fee 100644 --- a/src/Payments/PaymentMethodsWrapper.res +++ b/src/Payments/PaymentMethodsWrapper.res @@ -88,9 +88,9 @@ let make = ( ) ->Dict.fromArray ->JSON.Encode.object - ->OrcaUtils.flattenObject(true) - ->OrcaUtils.mergeTwoFlattenedJsonDicts(requiredFieldsBody) - ->OrcaUtils.getArrayOfTupleFromDict, + ->flattenObject(true) + ->mergeTwoFlattenedJsonDicts(requiredFieldsBody) + ->getArrayOfTupleFromDict, ~confirmParam=confirm.confirmParams, ~handleUserError=false, ~iframeId, diff --git a/src/Payments/PaypalSDK.res b/src/Payments/PaypalSDK.res index 2ea9392ef..8e3e28dc1 100644 --- a/src/Payments/PaypalSDK.res +++ b/src/Payments/PaypalSDK.res @@ -44,7 +44,7 @@ let make = (~sessionObj: SessionsType.token, ~list: PaymentMethodsRecord.list) = (), ) open Promise - OrcaUtils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) + Utils.makeOneClickHandlerPromise(sdkHandleOneClickConfirmPayment) ->then(result => { let result = result->JSON.Decode.bool->Option.getOr(false) if result { diff --git a/src/Payments/QRCodeDisplay.res b/src/Payments/QRCodeDisplay.res index 012f9fa75..4af8ac78b 100644 --- a/src/Payments/QRCodeDisplay.res +++ b/src/Payments/QRCodeDisplay.res @@ -41,7 +41,7 @@ let make = () => { ->Dict.toArray ->Array.forEach(entries => { let (x, val) = entries - Dict.set(headers, x, val->JSON.Decode.string->Option.getOr("")) + Dict.set(headers, x, val->getStringFromJson("")) }) let expiryTime = metaDataDict->getString("expiryTime", "")->Belt.Float.fromString->Option.getOr(0.0) diff --git a/src/SoftTheme.res b/src/SoftTheme.res index 8e5ffd925..4dc0e534a 100644 --- a/src/SoftTheme.res +++ b/src/SoftTheme.res @@ -180,7 +180,7 @@ let softRules = theme => "fontWeight": theme.fontWeightLight, "fontSize": theme.fontSizeLg, }, - }->toJson + }->Identity.anyTypeToJson let default = soft let defaultRules = softRules diff --git a/src/ThreeDSAuth.res b/src/ThreeDSAuth.res index 6fa130721..f9495e84a 100644 --- a/src/ThreeDSAuth.res +++ b/src/ThreeDSAuth.res @@ -11,7 +11,7 @@ let make = () => { handlePostMessage([("iframeMountedCallback", true->JSON.Encode.bool)]) let handle = (ev: Window.event) => { let json = ev.data->JSON.parseExn - let dict = json->Utils.getDictFromJson + let dict = json->getDictFromJson if dict->Dict.get("fullScreenIframeMounted")->Option.isSome { let metadata = dict->getJsonObjectFromDict("metadata") let metaDataDict = metadata->JSON.Decode.object->Option.getOr(Dict.make()) @@ -66,7 +66,7 @@ let make = () => { | Some(elem) => if transStatus === "C" { setloader(_ => false) - let form = elem->OrcaUtils.makeForm(acsUrl, "3dsChallenge") + let form = elem->makeForm(acsUrl, "3dsChallenge") let input = Types.createElement("input") input.name = "creq" input.value = creq @@ -74,7 +74,7 @@ let make = () => { form.appendChild(input) form.submit() } else { - let form1 = elem->OrcaUtils.makeForm(threeDsAuthoriseUrl, "3dsFrictionLess") + let form1 = elem->makeForm(threeDsAuthoriseUrl, "3dsFrictionLess") form1.submit() } | None => () @@ -82,7 +82,7 @@ let make = () => { resolve(json) }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException LoggerUtils.handleLogging( ~optLogger=Some(logger), ~eventName=DISPLAY_THREE_DS_SDK, diff --git a/src/Types/CardThemeType.res b/src/Types/CardThemeType.res index 40d7b0526..633a94650 100644 --- a/src/Types/CardThemeType.res +++ b/src/Types/CardThemeType.res @@ -1,5 +1,4 @@ type theme = Default | Brutal | Midnight | Soft | Charcoal | NONE -external toJson: 'a => JSON.t = "%identity" @val external navigator: 'a = "navigator" type showLoader = Auto | Always | Never diff --git a/src/Types/GooglePayType.res b/src/Types/GooglePayType.res index f30260fb8..23ff7a9ed 100644 --- a/src/Types/GooglePayType.res +++ b/src/Types/GooglePayType.res @@ -1,6 +1,5 @@ open Utils @val @scope("Object") external assign: (JSON.t, JSON.t, JSON.t) => JSON.t = "assign" -external toSome: JSON.t => 'a = "%identity" type transactionInfo = { countryCode: string, currencyCode: string, @@ -113,16 +112,16 @@ let jsonToPaymentRequestDataType: (paymentDataRequest, Dict.t) => paymen ) => { paymentRequest.allowedPaymentMethods = jsonDict - ->Utils.getArray("allowed_payment_methods") - ->Array.map(json => Utils.transformKeys(json, Utils.CamelCase)) + ->getArray("allowed_payment_methods") + ->Array.map(json => transformKeys(json, CamelCase)) paymentRequest.transactionInfo = jsonDict - ->Utils.getJsonFromDict("transaction_info", JSON.Encode.null) - ->Utils.transformKeys(Utils.CamelCase) + ->getJsonFromDict("transaction_info", JSON.Encode.null) + ->transformKeys(CamelCase) paymentRequest.merchantInfo = jsonDict - ->Utils.getJsonFromDict("merchant_info", JSON.Encode.null) - ->Utils.transformKeys(Utils.CamelCase) + ->getJsonFromDict("merchant_info", JSON.Encode.null) + ->transformKeys(CamelCase) paymentRequest } diff --git a/src/Types/PaymentType.res b/src/Types/PaymentType.res index b37b182dc..b17ca0f09 100644 --- a/src/Types/PaymentType.res +++ b/src/Types/PaymentType.res @@ -594,7 +594,7 @@ let getLayoutValues = (val, logger) => { ObjectLayout({ let layoutType = getWarningString(json, "type", "tabs", ~logger) unknownKeysWarning( - ["defaultCollapsed", "radios", "spacedAccordionItems", "type"], + ["defaultCollapsed", "radios", "spacedAccordionItems", "type", "maxAccordionItems"], json, "options.layout", ~logger, diff --git a/src/Utilities/DynamicFieldsUtils.res b/src/Utilities/DynamicFieldsUtils.res index 1c0af792d..c1cc62f12 100644 --- a/src/Utilities/DynamicFieldsUtils.res +++ b/src/Utilities/DynamicFieldsUtils.res @@ -136,7 +136,7 @@ let useRequiredFieldsEmptyAndValid = ( | AddressCountry(countryArr) => country !== "" || countryArr->Array.length === 0 | BillingName => checkIfNameIsValid(requiredFields, paymentMethodFields, billingName) | AddressLine1 => line1.value !== "" - | AddressLine2 => billingAddress.isUseBillingAddress ? true : line2.value !== "" + | AddressLine2 => billingAddress.isUseBillingAddress || line2.value !== "" | Bank => selectedBank !== "" || bankNames->Array.length === 0 | PhoneNumber => phone.value !== "" | StateAndCity => state.value !== "" && city.value !== "" @@ -161,46 +161,44 @@ let useRequiredFieldsEmptyAndValid = ( }) setAreRequiredFieldsValid(_ => areRequiredFieldsValid) - let areRequiredFieldsEmpty = fieldsArrWithBillingAddress->Array.reduce(false, ( - acc, - paymentMethodFields, - ) => { - acc || - switch paymentMethodFields { - | Email => email.value === "" - | FullName => fullName.value === "" - | Country => country === "" && countryNames->Array.length > 0 - | AddressCountry(countryArr) => country === "" && countryArr->Array.length > 0 - | BillingName => billingName.value === "" - | AddressLine1 => line1.value === "" - | AddressLine2 => billingAddress.isUseBillingAddress ? false : line2.value === "" - | Bank => selectedBank === "" && bankNames->Array.length > 0 - | StateAndCity => city.value === "" || state.value === "" - | CountryAndPincode(countryArr) => - (country === "" && countryArr->Array.length > 0) || postalCode.value === "" - | PhoneNumber => phone.value === "" - | AddressCity => city.value === "" - | AddressPincode => postalCode.value === "" - | AddressState => state.value === "" - | BlikCode => blikCode.value === "" - | Currency(currencyArr) => currency === "" && currencyArr->Array.length > 0 - | CardNumber => cardNumber === "" - | CardExpiryMonth => - let (month, _) = CardUtils.getExpiryDates(cardExpiry) - month === "" - | CardExpiryYear => - let (_, year) = CardUtils.getExpiryDates(cardExpiry) - year === "" - | CardExpiryMonthAndYear => - let (month, year) = CardUtils.getExpiryDates(cardExpiry) - month === "" || year === "" - | CardCvc => cvcNumber === "" - | CardExpiryAndCvc => - let (month, year) = CardUtils.getExpiryDates(cardExpiry) - month === "" || year === "" || cvcNumber === "" - | _ => false - } - }) + let areRequiredFieldsEmpty = + fieldsArrWithBillingAddress->Array.reduce(false, (acc, paymentMethodFields: PaymentMethodsRecord.paymentMethodsFields) => { + acc || + switch (paymentMethodFields) { + | Email => email.value === "" + | FullName => fullName.value === "" + | Country => country === "" && countryNames->Array.length > 0 + | AddressCountry(countryArr) => country === "" && countryArr->Array.length > 0 + | BillingName => billingName.value === "" + | AddressLine1 => line1.value === "" + | AddressLine2 => !billingAddress.isUseBillingAddress && line2.value === "" + | Bank => selectedBank === "" && bankNames->Array.length > 0 + | StateAndCity => city.value === "" || state.value === "" + | CountryAndPincode(countryArr) => + (country === "" && countryArr->Array.length > 0) || postalCode.value === "" + | PhoneNumber => phone.value === "" + | AddressCity => city.value === "" + | AddressPincode => postalCode.value === "" + | AddressState => state.value === "" + | BlikCode => blikCode.value === "" + | Currency(currencyArr) => currency === "" && currencyArr->Array.length > 0 + | CardNumber => cardNumber === "" + | CardExpiryMonth => + let (month, _) = CardUtils.getExpiryDates(cardExpiry) + month === "" + | CardExpiryYear => + let (_, year) = CardUtils.getExpiryDates(cardExpiry) + year === "" + | CardExpiryMonthAndYear => + let (month, year) = CardUtils.getExpiryDates(cardExpiry) + month === "" || year === "" + | CardCvc => cvcNumber === "" + | CardExpiryAndCvc => + let (month, year) = CardUtils.getExpiryDates(cardExpiry) + month === "" || year === "" || cvcNumber === "" + | _ => false + } + }) setAreRequiredFieldsEmpty(_ => areRequiredFieldsEmpty) None }, ( diff --git a/src/Utilities/Identity.res b/src/Utilities/Identity.res new file mode 100644 index 000000000..f8e1ca3da --- /dev/null +++ b/src/Utilities/Identity.res @@ -0,0 +1,3 @@ +external anyTypeToJson: 'a => JSON.t = "%identity" +external unsafeToJsExn: exn => Exn.t = "%identity" +external jsonToNullableJson: JSON.t => Nullable.t = "%identity" diff --git a/src/Utilities/PaymentHelpers.res b/src/Utilities/PaymentHelpers.res index 86d32e11d..06a0c310b 100644 --- a/src/Utilities/PaymentHelpers.res +++ b/src/Utilities/PaymentHelpers.res @@ -1,4 +1,5 @@ open Utils +open Identity @val @scope(("window", "parent", "location")) external href: string = "href" @@ -9,8 +10,7 @@ type url = {searchParams: searchParams, href: string} open LoggerUtils type payment = Card | BankTransfer | BankDebits | KlarnaRedirect | Gpay | Applepay | Paypal | Other -let closePaymentLoaderIfAny = () => - Utils.handlePostMessage([("fullscreen", false->JSON.Encode.bool)]) +let closePaymentLoaderIfAny = () => handlePostMessage([("fullscreen", false->JSON.Encode.bool)]) let retrievePaymentIntent = ( clientSecret, @@ -126,7 +126,7 @@ let threeDsMethod = (url, threeDsMethodData, ~optLogger) => { } }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException Console.log2("Unable to call 3ds method ", exceptionMessage) logApi( ~optLogger, @@ -200,7 +200,7 @@ let threeDsAuth = (~clientSecret, ~optLogger, ~threeDsMethodComp, ~headers) => { } }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException Console.log2("Unable to call 3ds auth ", exceptionMessage) logApi( ~optLogger, @@ -256,7 +256,7 @@ let rec intentCall = ( ~headers: Dict.t=?, ~method: Fetch.method, unit, - ) => OrcaPaymentPage.Promise.t, + ) => Promise.t, ~uri, ~headers, ~bodyStr, @@ -321,8 +321,8 @@ let rec intentCall = ( | _ => bodyStr ->JSON.parseExn - ->Utils.getDictFromJson - ->Utils.getString("payment_method_type", "") + ->getDictFromJson + ->getString("payment_method_type", "") } handleLogging( ~optLogger, @@ -368,7 +368,7 @@ let rec intentCall = ( ->catch(err => { Promise.make( (resolve, _) => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, @@ -478,7 +478,7 @@ let rec intentCall = ( handleOpenUrl(intent.nextAction.redirectToUrl) } else if intent.nextAction.type_ == "display_bank_transfer_information" { let metadata = switch intent.nextAction.bank_transfer_steps_and_charges_details { - | Some(obj) => obj->Utils.getDictFromJson + | Some(obj) => obj->getDictFromJson | None => Dict.make() } let dict = deepCopyDict(metadata) @@ -549,7 +549,7 @@ let rec intentCall = ( ->Belt.Option.flatMap(x => x->Dict.get("three_ds_method_data_submission")) ->Option.getOr(Dict.make()->JSON.Encode.object) ->JSON.Decode.bool - ->Utils.getBoolValue + ->getBoolValue let headerObj = Dict.make() headers->Array.forEach( @@ -594,16 +594,16 @@ let rec intentCall = ( } } else if intent.nextAction.type_ == "third_party_sdk_session_token" { let session_token = switch intent.nextAction.session_token { - | Some(token) => token->Utils.getDictFromJson + | Some(token) => token->getDictFromJson | None => Dict.make() } - let walletName = session_token->Utils.getString("wallet_name", "") + let walletName = session_token->getString("wallet_name", "") let message = switch walletName { | "apple_pay" => [ ("applePayButtonClicked", true->JSON.Encode.bool), - ("applePayPresent", session_token->toJson), + ("applePayPresent", session_token->anyTypeToJson), ] - | "google_pay" => [("googlePayThirdPartyFlow", session_token->toJson)] + | "google_pay" => [("googlePayThirdPartyFlow", session_token->anyTypeToJson)] | _ => [] } @@ -640,16 +640,16 @@ let rec intentCall = ( } else if intent.status == "processing" { if intent.nextAction.type_ == "third_party_sdk_session_token" { let session_token = switch intent.nextAction.session_token { - | Some(token) => token->Utils.getDictFromJson + | Some(token) => token->getDictFromJson | None => Dict.make() } - let walletName = session_token->Utils.getString("wallet_name", "") + let walletName = session_token->getString("wallet_name", "") let message = switch walletName { | "apple_pay" => [ ("applePayButtonClicked", true->JSON.Encode.bool), - ("applePayPresent", session_token->toJson), + ("applePayPresent", session_token->anyTypeToJson), ] - | "google_pay" => [("googlePayThirdPartyFlow", session_token->toJson)] + | "google_pay" => [("googlePayThirdPartyFlow", session_token->anyTypeToJson)] | _ => [] } @@ -704,7 +704,7 @@ let rec intentCall = ( let url = urlSearch(confirmParam.return_url) url.searchParams.set("payment_intent_client_secret", clientSecret) url.searchParams.set("status", "failed") - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, @@ -870,7 +870,7 @@ let usePaymentIntent = (optLogger: option, paymentType: p let callIntent = body => { let maskedPayload = - body->OrcaUtils.safeParseOpt->Option.getOr(JSON.Encode.null)->maskPayload->JSON.stringify + body->safeParseOpt->Option.getOr(JSON.Encode.null)->maskPayload->JSON.stringify let loggerPayload = [ ("payload", maskedPayload->JSON.Encode.string), @@ -906,7 +906,7 @@ let usePaymentIntent = (optLogger: option, paymentType: p ~value="", ~internalMetadata=loggerPayload, ~eventName=PAYMENT_ATTEMPT, - ~paymentMethod=json->JSON.Decode.string->Option.getOr(""), + ~paymentMethod=json->getStringFromJson(""), (), ) } @@ -1067,7 +1067,7 @@ let fetchSessions = ( } }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, @@ -1141,7 +1141,7 @@ let fetchPaymentMethodList = ( } }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException logApi( ~optLogger=Some(logger), ~url=uri, @@ -1215,7 +1215,7 @@ let fetchCustomerDetails = ( } }) ->catch(err => { - let exceptionMessage = err->Utils.formatException + let exceptionMessage = err->formatException logApi( ~optLogger, ~url=uri, diff --git a/src/Utilities/Utils.res b/src/Utilities/Utils.res index fabbba72b..af84cfe38 100644 --- a/src/Utilities/Utils.res +++ b/src/Utilities/Utils.res @@ -4,8 +4,6 @@ type parent @val external window: window = "window" @val @scope("window") external iframeParent: parent = "parent" type event = {data: string} -external eventToJson: event => JSON.t = "%identity" -external toJson: 'a => JSON.t = "%identity" external dictToObj: Dict.t<'a> => {..} = "%identity" @module("./Phone_number.json") @@ -49,6 +47,10 @@ let getString = (dict, key, default) => { getOptionString(dict, key)->Option.getOr(default) } +let getStringFromJson = (json, default) => { + json->JSON.Decode.string->Option.getOr(default) +} + let getInt = (dict, key, default: int) => { dict ->Dict.get(key) @@ -190,14 +192,12 @@ let getStrArray = (dict, key) => { dict ->getOptionalArrayFromDict(key) ->Option.getOr([]) - ->Array.map(json => json->JSON.Decode.string->Option.getOr("")) + ->Array.map(json => json->getStringFromJson("")) } let getOptionalStrArray: (Dict.t, string) => option> = (dict, key) => { switch dict->getOptionalArrayFromDict(key) { | Some(val) => - val->Array.length === 0 - ? None - : Some(val->Array.map(json => json->JSON.Decode.string->Option.getOr(""))) + val->Array.length === 0 ? None : Some(val->Array.map(json => json->getStringFromJson(""))) | None => None } } @@ -467,7 +467,8 @@ let isAllValid = ( ) => { card->getBoolValue && cvc->getBoolValue && - expiry->getBoolValue && {paymentMode == "payment" ? true : zip} + expiry->getBoolValue && + (paymentMode == "payment" || zip) } let getCountryPostal = (countryCode, postalCodes: array) => { @@ -658,7 +659,7 @@ let handlePostMessageEvents = ( ~complete, ~empty, ~paymentType, - ~loggerState: OrcaPaymentPage.OrcaLogger.loggerMake, + ~loggerState: OrcaLogger.loggerMake, ~savedMethod=false, ) => { if complete && paymentType !== "" { @@ -871,7 +872,7 @@ let arrayJsonToCamelCase = arr => { }) } let formatException = exc => { - exc->toJson + exc->Identity.anyTypeToJson } let getArrayValFromJsonDict = (dict, key, arrayKey) => { @@ -899,3 +900,337 @@ let callbackFuncForExtractingValFromDict = key => { } let brandIconSize = 28 + +let getClasses = (options, key) => { + let classes = options->getDictFromObj("classes") + classes->getString(key, "") +} + +let safeParseOpt = st => { + try { + JSON.parseExn(st)->Some + } catch { + | _ => None + } +} +let safeParse = st => { + safeParseOpt(st)->Option.getOr(JSON.Encode.null) +} + +let getArrayOfTupleFromDict = dict => { + dict + ->Dict.keysToArray + ->Array.map(key => (key, Dict.get(dict, key)->Option.getOr(JSON.Encode.null))) +} + +let getOptionalJsonFromJson = (json, str) => { + json->JSON.Decode.object->Option.getOr(Dict.make())->Dict.get(str) +} + +let getStringFromOptionalJson = (json, default) => { + json->Option.flatMap(JSON.Decode.string)->Option.getOr(default) +} + +let getBoolFromJson = (json, default) => { + json->Option.flatMap(JSON.Decode.bool)->Option.getOr(default) +} + +let getOptionalJson = (json, str) => { + json + ->JSON.Decode.object + ->Option.flatMap(x => x->Dict.get("data")) + ->Option.getOr(Dict.make()->JSON.Encode.object) + ->JSON.Decode.object + ->Option.getOr(Dict.make()) + ->Dict.get(str) +} + +let rec setNested = (dict, keys, value) => { + switch keys[0] { + | Some(firstKey) => + if keys->Array.length === 1 { + Dict.set(dict, firstKey, value) + } else { + let subDict = switch Dict.get(dict, firstKey) { + | Some(json) => + switch json->JSON.Decode.object { + | Some(obj) => obj + | None => dict + } + | None => + let subDict = Dict.make() + dict->Dict.set(firstKey, subDict->JSON.Encode.object) + subDict + } + let remainingKeys = keys->Array.sliceToEnd(~start=1) + setNested(subDict, remainingKeys, value) + } + | None => () + } +} + +let unflattenObject = obj => { + let newDict = Dict.make() + + switch obj->JSON.Decode.object { + | Some(dict) => + dict + ->Dict.toArray + ->Array.forEach(entry => { + let (key, value) = entry + setNested(newDict, key->String.split("."), value) + }) + | None => () + } + newDict +} + +let mergeTwoFlattenedJsonDicts = (dict1, dict2) => { + dict1 + ->Dict.toArray + ->Array.concat(dict2->Dict.toArray) + ->Dict.fromArray + ->JSON.Encode.object + ->unflattenObject +} + +open Identity + +let rec flattenObject = (obj, addIndicatorForObject) => { + let newDict = Dict.make() + switch obj->JSON.Decode.object { + | Some(obj) => + obj + ->Dict.toArray + ->Array.forEach(entry => { + let (key, value) = entry + + if value->jsonToNullableJson->Js.Nullable.isNullable { + Dict.set(newDict, key, value) + } else { + switch value->JSON.Decode.object { + | Some(_valueObj) => { + if addIndicatorForObject { + Dict.set(newDict, key, JSON.Encode.object(Dict.make())) + } + + let flattenedSubObj = flattenObject(value, addIndicatorForObject) + + flattenedSubObj + ->Dict.toArray + ->Array.forEach(subEntry => { + let (subKey, subValue) = subEntry + Dict.set(newDict, `${key}.${subKey}`, subValue) + }) + } + + | None => Dict.set(newDict, key, value) + } + } + }) + | _ => () + } + newDict +} + +let rec flattenObjectWithStringifiedJson = (obj, addIndicatorForObject, keepParent) => { + let newDict = Dict.make() + switch obj->JSON.Decode.object { + | Some(obj) => + obj + ->Dict.toArray + ->Array.forEach(entry => { + let (key, value) = entry + + if value->jsonToNullableJson->Js.Nullable.isNullable { + Dict.set(newDict, key, value) + } else { + switch value->getStringFromJson("")->safeParse->JSON.Decode.object { + | Some(_valueObj) => { + if addIndicatorForObject { + Dict.set(newDict, key, JSON.Encode.object(Dict.make())) + } + + let flattenedSubObj = flattenObjectWithStringifiedJson( + value->getStringFromJson("")->safeParse, + addIndicatorForObject, + keepParent, + ) + + flattenedSubObj + ->Dict.toArray + ->Array.forEach(subEntry => { + let (subKey, subValue) = subEntry + let keyN = keepParent ? `${key}.${subKey}` : subKey + Dict.set(newDict, keyN, subValue) + }) + } + + | None => Dict.set(newDict, key, value) + } + } + }) + | _ => () + } + newDict +} + +let rec flatten = (obj, addIndicatorForObject) => { + let newDict = Dict.make() + switch obj->JSON.Classify.classify { + | Object(obj) => + obj + ->Dict.toArray + ->Array.forEach(entry => { + let (key, value) = entry + + if value->jsonToNullableJson->Js.Nullable.isNullable { + Dict.set(newDict, key, value) + } else { + switch value->JSON.Classify.classify { + | Object(_valueObjDict) => { + if addIndicatorForObject { + Dict.set(newDict, key, JSON.Encode.object(Dict.make())) + } + + let flattenedSubObj = flatten(value, addIndicatorForObject) + + flattenedSubObj + ->Dict.toArray + ->Array.forEach(subEntry => { + let (subKey, subValue) = subEntry + Dict.set(newDict, `${key}.${subKey}`, subValue) + }) + } + + | Array(dictArray) => { + let stringArray = [] + let arrayArray = [] + dictArray->Array.forEachWithIndex((item, index) => { + switch item->JSON.Classify.classify { + | String(_str) => + let _ = stringArray->Array.push(item) + | Object(_obj) => { + let flattenedSubObj = flatten(item, addIndicatorForObject) + flattenedSubObj + ->Dict.toArray + ->Array.forEach( + subEntry => { + let (subKey, subValue) = subEntry + Dict.set(newDict, `${key}[${index->Int.toString}].${subKey}`, subValue) + }, + ) + } + + | _ => + let _ = arrayArray->Array.push(item) + } + }) + if stringArray->Array.length > 0 { + Dict.set(newDict, key, stringArray->JSON.Encode.array) + } + if arrayArray->Array.length > 0 { + Dict.set(newDict, key, arrayArray->JSON.Encode.array) + } + } + + | _ => Dict.set(newDict, key, value) + } + } + }) + | _ => () + } + newDict +} + +let eventHandlerFunc = ( + condition: Types.event => bool, + eventHandler, + evType: Types.eventType, + activity, +) => { + let changeHandler = ev => { + if ev->condition { + switch evType { + | Change + | Click + | Ready + | Focus + | ConfirmPayment + | OneClickConfirmPayment + | Blur => + switch eventHandler { + | Some(eH) => eH(Some(ev.data)) + | None => () + } + | _ => () + } + } + } + EventListenerManager.addSmartEventListener("message", changeHandler, activity) +} + +let makeIframe = (element, url) => { + open Types + Promise.make((resolve, _) => { + let iframe = createElement("iframe") + iframe.id = "orca-fullscreen" + iframe.src = url + iframe.name = "fullscreen" + iframe.style = "position: fixed; inset: 0; width: 100vw; height: 100vh; border: 0; z-index: 422222133323; " + iframe.onload = () => { + resolve(Dict.make()) + } + element->appendChild(iframe) + }) +} +let makeForm = (element, url, id) => { + open Types + let form = createElement("form") + form.id = id + form.name = id + form.action = url + form.method = "POST" + form.enctype = "application/x-www-form-urlencoded;charset=UTF-8" + form.style = "display: hidden; " + element->appendChild(form) + form +} + +let getThemePromise = dict => { + let theme = + dict + ->getJsonObjectFromDict("appearance") + ->getDictFromJson + ->getString("theme", "default") + + switch theme { + | "default" => None + | "brutal" => Some(ThemeImporter.importTheme("../BrutalTheme.bs.js")) + | "midnight" => Some(ThemeImporter.importTheme("../MidnightTheme.bs.js")) + | "charcoal" => Some(ThemeImporter.importTheme("../CharcoalTheme.bs.js")) + | "soft" => Some(ThemeImporter.importTheme("../SoftTheme.bs.js")) + | "none" => Some(ThemeImporter.importTheme("../NoTheme.bs.js")) + | _ => None + } +} + +let makeOneClickHandlerPromise = sdkHandleOneClickConfirmPayment => { + open EventListenerManager + Promise.make((resolve, _) => { + if sdkHandleOneClickConfirmPayment { + resolve(JSON.Encode.bool(true)) + } else { + let handleMessage = (event: Types.event) => { + let json = event.data->anyTypeToJson->getStringFromJson("")->safeParse + + let dict = json->getDictFromJson + if dict->Dict.get("oneClickDoSubmit")->Option.isSome { + resolve(dict->Dict.get("oneClickDoSubmit")->Option.getOr(true->JSON.Encode.bool)) + } + } + addSmartEventListener("message", handleMessage, "onOneClickHandlerPaymentConfirm") + handleOnConfirmPostMessage(~targetOrigin="*", ~isOneClick=true, ()) + } + }) +} diff --git a/src/libraries/Promise.res b/src/libraries/Promise.res index dc1044977..8b7707576 100644 --- a/src/libraries/Promise.res +++ b/src/libraries/Promise.res @@ -1,7 +1,6 @@ type t<+'a> = Promise.t<'a> exception JsError(Exn.t) -external unsafeToJsExn: exn => Exn.t = "%identity" @new external make: ((@uncurry 'a => unit, 'e => unit) => unit) => t<'a> = "Promise" @@ -45,7 +44,7 @@ let catch = (promise, callback) => { let v = if Exn.isCamlExceptionOrOpenVariant(err) { err } else { - JsError(unsafeToJsExn(err)) + JsError(Identity.unsafeToJsExn(err)) } callback(v) }) diff --git a/src/libraries/Promise.resi b/src/libraries/Promise.resi index 6d0a36d25..acfa8085f 100644 --- a/src/libraries/Promise.resi +++ b/src/libraries/Promise.resi @@ -1,6 +1,5 @@ type t<'a> = RescriptCore.Promise.t<'a> type exn += JsError(RescriptCore.Exn.t) -external unsafeToJsExn: exn => RescriptCore.Exn.t = "%identity" @new external make: ((@uncurry 'a => unit, 'e => unit) => unit) => t<'a> = "Promise" @val @scope("Promise") diff --git a/src/orca-loader/Elements.res b/src/orca-loader/Elements.res index b5164d21d..75aaac4fa 100644 --- a/src/orca-loader/Elements.res +++ b/src/orca-loader/Elements.res @@ -1,16 +1,12 @@ open Types open ErrorUtils - +open Identity open Utils open EventListenerManager - open ApplePayTypes -external objToJson: {..} => JSON.t = "%identity" -external eventToJson: Types.eventData => JSON.t = "%identity" - type trustPayFunctions = { - finishApplePaymentV2: (string, ApplePayTypes.paymentRequestData) => Promise.t, + finishApplePaymentV2: (string, paymentRequestData) => Promise.t, executeGooglePayment: (string, GooglePayType.paymentDataRequest) => Promise.t, } @new external trustPayApi: JSON.t => trustPayFunctions = "TrustPayApi" @@ -258,7 +254,7 @@ let make = ( ]->Dict.fromArray let handleApplePayMounted = (event: Types.event) => { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson if dict->Dict.get("applePayMounted")->Option.isSome { @@ -283,7 +279,7 @@ let make = ( } let handleGooglePayThirdPartyFlow = (event: Types.event) => { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson switch dict->Dict.get("googlePayThirdPartyFlow") { @@ -298,7 +294,7 @@ let make = ( let paymentDataRequest = GooglePayType.assign2( Dict.make()->JSON.Encode.object, - baseDetails->objToJson, + baseDetails->anyTypeToJson, ) let googlePayRequest = @@ -319,14 +315,14 @@ let make = ( switch connector { | "trustpay" => { let secrets = - googlePayThirdPartySession->Utils.getJsonFromDict("secrets", JSON.Encode.null) + googlePayThirdPartySession->getJsonFromDict("secrets", JSON.Encode.null) - let payment = secrets->Utils.getDictFromJson->Utils.getString("payment", "") + let payment = secrets->getDictFromJson->getString("payment", "") let trustpay = trustPayApi(secrets) let polling = - Utils.delay(2000)->then(_ => + delay(2000)->then(_ => PaymentHelpers.pollRetrievePaymentIntent( clientSecret, headers, @@ -339,7 +335,7 @@ let make = ( payment, googlePayRequest, ) - let timeOut = Utils.delay(600000)->then(_ => { + let timeOut = delay(600000)->then(_ => { let errorMsg = [("error", "Request Timed Out"->JSON.Encode.string)] ->Dict.fromArray @@ -361,7 +357,7 @@ let make = ( resolve() }) ->catch(err => { - let exceptionMessage = err->Utils.formatException->JSON.stringify + let exceptionMessage = err->formatException->JSON.stringify logger.setLogInfo( ~value=exceptionMessage, ~eventName=GOOGLE_PAY_FLOW, @@ -455,7 +451,7 @@ let make = ( handleApplePayMessages := ( (event: Types.event) => { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson switch dict->Dict.get("applePayButtonClicked") { | Some(val) => @@ -512,7 +508,7 @@ let make = ( ->Dict.get("payment_request_data") ->Option.flatMap(JSON.Decode.object) ->Option.getOr(Dict.make()) - ->ApplePayTypes.jsonToPaymentRequestDataType + ->jsonToPaymentRequestDataType let payment = secrets @@ -603,7 +599,7 @@ let make = ( } ssn.onpaymentauthorized = event => { - ssn.completePayment({"status": ssn.\"STATUS_SUCCESS"}->objToJson) + ssn.completePayment({"status": ssn.\"STATUS_SUCCESS"}->anyTypeToJson) applePaySessionRef := Nullable.null processPayment(event.payment.token) } @@ -664,15 +660,15 @@ let make = ( } let paymentDataRequest = GooglePayType.assign2( Dict.make()->JSON.Encode.object, - baseRequest->toJson, + baseRequest->anyTypeToJson, ) let payRequest = GooglePayType.assign( Dict.make()->JSON.Encode.object, - baseRequest->toJson, + baseRequest->anyTypeToJson, { "allowedPaymentMethods": gpayobj.allowed_payment_methods->arrayJsonToCamelCase, - }->toJson, + }->anyTypeToJson, ) paymentDataRequest.allowedPaymentMethods = gpayobj.allowed_payment_methods->arrayJsonToCamelCase @@ -684,7 +680,7 @@ let make = ( "environment": publishableKey->String.startsWith("pk_prd_") ? "PRODUCTION" : "TEST", - }->toJson, + }->anyTypeToJson, ) gPayClient.isReadyToPay(payRequest) @@ -697,7 +693,7 @@ let make = ( }) ->catch(err => { logger.setLogInfo( - ~value=err->toJson->JSON.stringify, + ~value=err->anyTypeToJson->JSON.stringify, ~eventName=GOOGLE_PAY_FLOW, ~paymentMethod="GOOGLE_PAY", ~logType=DEBUG, @@ -708,25 +704,25 @@ let make = ( ->ignore let handleGooglePayMessages = (event: Types.event) => { - let evJson = event.data->eventToJson + let evJson = event.data->anyTypeToJson let gpayClicked = evJson - ->OrcaUtils.getOptionalJsonFromJson("GpayClicked") - ->OrcaUtils.getBoolfromjson(false) + ->getOptionalJsonFromJson("GpayClicked") + ->getBoolFromJson(false) if gpayClicked { setTimeout(() => { - gPayClient.loadPaymentData(paymentDataRequest->toJson) + gPayClient.loadPaymentData(paymentDataRequest->anyTypeToJson) ->then( json => { logger.setLogInfo( - ~value=json->toJson->JSON.stringify, + ~value=json->anyTypeToJson->JSON.stringify, ~eventName=GOOGLE_PAY_FLOW, ~paymentMethod="GOOGLE_PAY", ~logType=DEBUG, (), ) - let msg = [("gpayResponse", json->toJson)]->Dict.fromArray + let msg = [("gpayResponse", json->anyTypeToJson)]->Dict.fromArray mountedIframeRef->Window.iframePostMessage(msg) resolve() }, @@ -734,14 +730,14 @@ let make = ( ->catch( err => { logger.setLogInfo( - ~value=err->toJson->JSON.stringify, + ~value=err->anyTypeToJson->JSON.stringify, ~eventName=GOOGLE_PAY_FLOW, ~paymentMethod="GOOGLE_PAY", ~logType=DEBUG, (), ) - let msg = [("gpayError", err->toJson)]->Dict.fromArray + let msg = [("gpayError", err->anyTypeToJson)]->Dict.fromArray mountedIframeRef->Window.iframePostMessage(msg) resolve() }, diff --git a/src/orca-loader/Hyper.res b/src/orca-loader/Hyper.res index 8fc2fa041..372e194ec 100644 --- a/src/orca-loader/Hyper.res +++ b/src/orca-loader/Hyper.res @@ -3,8 +3,7 @@ open ErrorUtils open LoggerUtils open Utils open EventListenerManager - -external eventToJson: Types.eventData => JSON.t = "%identity" +open Identity let checkAndAppend = (selector, child) => { if Nullable.toOption(CommonHooks.querySelector(selector)) == None { @@ -97,7 +96,7 @@ let make = (publishableKey, options: option, analyticsInfo: option { let handleOnReady = (event: Types.event) => { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson if ( dict @@ -293,7 +292,7 @@ let make = (publishableKey, options: option, analyticsInfo: optionPromise.then(readyTimestamp => { let handleMessage = (event: Types.event) => { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson switch dict->Dict.get("submitSuccessful") { | Some(val) => @@ -364,7 +363,7 @@ let make = (publishableKey, options: option, analyticsInfo: option { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson switch dict->Dict.get("handleSdkConfirm") { | Some(payload) => confirmPayment(payload)->ignore @@ -431,7 +430,7 @@ let make = (publishableKey, options: option, analyticsInfo: option { - let json = event.data->eventToJson + let json = event.data->anyTypeToJson let dict = json->getDictFromJson switch dict->Dict.get("submitSuccessful") { | Some(val) => diff --git a/src/orca-loader/LoaderPaymentElement.res b/src/orca-loader/LoaderPaymentElement.res index 106588f67..0e3e2cd9e 100644 --- a/src/orca-loader/LoaderPaymentElement.res +++ b/src/orca-loader/LoaderPaymentElement.res @@ -1,10 +1,7 @@ open Types open Utils open EventListenerManager - -open OrcaUtils - -external eventToJson: Types.eventData => JSON.t = "%identity" +open Identity @val @scope(("navigator", "clipboard")) external writeText: string => Promise.t<'a> = "writeText" @@ -146,14 +143,14 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = let fullscreenMetadata = ref(Dict.make()->JSON.Encode.object) let optionsDict = options->getDictFromJson let handle = (ev: Types.event) => { - let eventDataObject = ev.data->eventToJson + let eventDataObject = ev.data->anyTypeToJson let iframeHeight = eventDataObject->getOptionalJsonFromJson("iframeHeight") if iframeHeight->Option.isSome { let iframeId = eventDataObject ->getOptionalJsonFromJson("iframeId") - ->getStringfromOptionaljson("no-element") + ->getStringFromOptionalJson("no-element") iframeHeightRef := iframeHeight->Option.getOr(JSON.Encode.null)->Utils.getFloatFromJson(200.0) if iframeId === localSelectorString { @@ -177,15 +174,15 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = switch eventDataObject->getOptionalJsonFromJson("openurl") { | Some(val) => { - let url = val->getStringfromjson("") + let url = val->getStringFromJson("") Window.Location.replace(url) } | None => () } - let isCopy = eventDataObject->getOptionalJsonFromJson("copy")->getBoolfromjson(false) + let isCopy = eventDataObject->getOptionalJsonFromJson("copy")->getBoolFromJson(false) let text = - eventDataObject->getOptionalJsonFromJson("copyDetails")->getStringfromOptionaljson("") + eventDataObject->getOptionalJsonFromJson("copyDetails")->getStringFromOptionalJson("") if isCopy { open Promise writeText(text) @@ -197,7 +194,7 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = let combinedHyperClasses = eventDataObject->getOptionalJsonFromJson("concatedString") if combinedHyperClasses->Option.isSome { - let id = eventDataObject->getOptionalJsonFromJson("id")->getStringfromOptionaljson("") + let id = eventDataObject->getOptionalJsonFromJson("id")->getStringFromOptionalJson("") let decodeStringTest = combinedHyperClasses->Option.flatMap(JSON.Decode.string) switch decodeStringTest { @@ -218,11 +215,11 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = let param = eventDataObject->getOptionalJsonFromJson("param") let metadata = eventDataObject->getOptionalJsonFromJson("metadata") let iframeID = - eventDataObject->getOptionalJsonFromJson("iframeId")->getStringfromOptionaljson("") + eventDataObject->getOptionalJsonFromJson("iframeId")->getStringFromOptionalJson("") if fullscreenIframe->Option.isSome { - fullscreen := fullscreenIframe->getBoolfromjson(false) - fullscreenParam := param->getStringfromOptionaljson("") + fullscreen := fullscreenIframe->getBoolFromJson(false) + fullscreenParam := param->getStringFromOptionalJson("") fullscreenMetadata := metadata ->Option.flatMap(JSON.Decode.object) @@ -246,7 +243,7 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = ? { if iframeID == localSelectorString { let handleFullScreenCallback = (ev: Types.event) => { - let json = ev.data->eventToJson + let json = ev.data->anyTypeToJson let dict = json->Utils.getDictFromJson if dict->Dict.get("iframeMountedCallback")->Option.isSome { let fullScreenEle = Window.querySelector(`#orca-fullscreen`) @@ -295,7 +292,7 @@ let make = (componentType, options, setIframeRef, iframeRef, mountPostMessage) = addSmartEventListener("message", handle, `onMount-${componentType}`) let oElement = Window.querySelector(selector) - let classesBase = optionsDict->OrcaUtils.getClasses("base") + let classesBase = optionsDict->getClasses("base") let additionalIframeStyle = componentType->Utils.isOtherElements ? "height: 2rem;" : "" switch oElement->Nullable.toOption { | Some(elem) => { diff --git a/src/orca-loader/OrcaUtils.res b/src/orca-loader/OrcaUtils.res deleted file mode 100644 index 7f1510655..000000000 --- a/src/orca-loader/OrcaUtils.res +++ /dev/null @@ -1,356 +0,0 @@ -open Utils -external toNullable: JSON.t => Nullable.t = "%identity" -external eventToJson: Types.eventData => JSON.t = "%identity" -let safeParseOpt = st => { - try { - JSON.parseExn(st)->Some - } catch { - | _e => None - } -} -let safeParse = st => { - safeParseOpt(st)->Option.getOr(JSON.Encode.null) -} - -let rec flattenObject = (obj, addIndicatorForObject) => { - let newDict = Dict.make() - switch obj->JSON.Decode.object { - | Some(obj) => - obj - ->Dict.toArray - ->Array.forEach(entry => { - let (key, value) = entry - - if value->toNullable->Js.Nullable.isNullable { - Dict.set(newDict, key, value) - } else { - switch value->JSON.Decode.object { - | Some(_valueObj) => { - if addIndicatorForObject { - Dict.set(newDict, key, JSON.Encode.object(Dict.make())) - } - - let flattenedSubObj = flattenObject(value, addIndicatorForObject) - - flattenedSubObj - ->Dict.toArray - ->Array.forEach(subEntry => { - let (subKey, subValue) = subEntry - Dict.set(newDict, `${key}.${subKey}`, subValue) - }) - } - - | None => Dict.set(newDict, key, value) - } - } - }) - | _ => () - } - newDict -} - -let rec flattenObjectWithStringifiedJson = (obj, addIndicatorForObject, keepParent) => { - let newDict = Dict.make() - switch obj->JSON.Decode.object { - | Some(obj) => - obj - ->Dict.toArray - ->Array.forEach(entry => { - let (key, value) = entry - - if value->toNullable->Js.Nullable.isNullable { - Dict.set(newDict, key, value) - } else { - switch value->JSON.Decode.string->Option.getOr("")->safeParse->JSON.Decode.object { - | Some(_valueObj) => { - if addIndicatorForObject { - Dict.set(newDict, key, JSON.Encode.object(Dict.make())) - } - - let flattenedSubObj = flattenObjectWithStringifiedJson( - value->JSON.Decode.string->Option.getOr("")->safeParse, - addIndicatorForObject, - keepParent, - ) - - flattenedSubObj - ->Dict.toArray - ->Array.forEach(subEntry => { - let (subKey, subValue) = subEntry - let keyN = keepParent ? `${key}.${subKey}` : subKey - Dict.set(newDict, keyN, subValue) - }) - } - - | None => Dict.set(newDict, key, value) - } - } - }) - | _ => () - } - newDict -} -let rec flatten = (obj, addIndicatorForObject) => { - let newDict = Dict.make() - switch obj->JSON.Classify.classify { - | Object(obj) => - obj - ->Dict.toArray - ->Array.forEach(entry => { - let (key, value) = entry - - if value->toNullable->Js.Nullable.isNullable { - Dict.set(newDict, key, value) - } else { - switch value->JSON.Classify.classify { - | Object(_valueObjDict) => { - if addIndicatorForObject { - Dict.set(newDict, key, JSON.Encode.object(Dict.make())) - } - - let flattenedSubObj = flatten(value, addIndicatorForObject) - - flattenedSubObj - ->Dict.toArray - ->Array.forEach(subEntry => { - let (subKey, subValue) = subEntry - Dict.set(newDict, `${key}.${subKey}`, subValue) - }) - } - - | Array(dictArray) => { - let stringArray = [] - let arrayArray = [] - dictArray->Array.forEachWithIndex((item, index) => { - switch item->JSON.Classify.classify { - | String(_str) => - let _ = stringArray->Array.push(item) - | Object(_obj) => { - let flattenedSubObj = flatten(item, addIndicatorForObject) - flattenedSubObj - ->Dict.toArray - ->Array.forEach( - subEntry => { - let (subKey, subValue) = subEntry - Dict.set(newDict, `${key}[${index->Int.toString}].${subKey}`, subValue) - }, - ) - } - - | _ => - let _ = arrayArray->Array.push(item) - } - }) - if stringArray->Array.length > 0 { - Dict.set(newDict, key, stringArray->JSON.Encode.array) - } - if arrayArray->Array.length > 0 { - Dict.set(newDict, key, arrayArray->JSON.Encode.array) - } - } - - | _ => Dict.set(newDict, key, value) - } - } - }) - | _ => () - } - newDict -} - -let rec setNested = (dict, keys, value) => { - switch keys[0] { - | Some(firstKey) => - if keys->Array.length === 1 { - Dict.set(dict, firstKey, value) - } else { - let subDict = switch Dict.get(dict, firstKey) { - | Some(json) => - switch json->JSON.Decode.object { - | Some(obj) => obj - | None => dict - } - | None => - let subDict = Dict.make() - dict->Dict.set(firstKey, subDict->JSON.Encode.object) - subDict - } - let remainingKeys = keys->Array.sliceToEnd(~start=1) - setNested(subDict, remainingKeys, value) - } - | None => () - } -} - -let unflattenObject = obj => { - let newDict = Dict.make() - - switch obj->JSON.Decode.object { - | Some(dict) => - dict - ->Dict.toArray - ->Array.forEach(entry => { - let (key, value) = entry - setNested(newDict, key->String.split("."), value) - }) - | None => () - } - newDict -} - -let getEventDataObj = ev => { - ev - ->JSON.Decode.object - ->Option.flatMap(x => x->Dict.get("data")) - ->Option.getOr(Dict.make()->JSON.Encode.object) -} - -let getStrValueFromEventDataObj = (ev, key) => { - let obj = ev->getEventDataObj - obj - ->JSON.Decode.object - ->Option.flatMap(x => x->Dict.get(key)) - ->Option.flatMap(JSON.Decode.string) - ->Option.getOr("") -} - -let getBoolValueFromEventDataObj = (ev, key) => { - let obj = ev->getEventDataObj - obj - ->JSON.Decode.object - ->Option.flatMap(x => x->Dict.get(key)) - ->Option.flatMap(JSON.Decode.bool) - ->Option.getOr(false) -} - -let getClasses = (options, key) => { - let classes = options->getDictFromObj("classes") - classes->getString(key, "") -} - -let eventHandlerFunc = ( - condition: Types.event => bool, - eventHandler, - evType: Types.eventType, - activity, -) => { - let changeHandler = ev => { - if ev->condition { - switch evType { - | Change - | Click - | Ready - | Focus - | ConfirmPayment - | OneClickConfirmPayment - | Blur => - switch eventHandler { - | Some(eH) => eH(Some(ev.data)) - | None => () - } - | _ => () - } - } - } - EventListenerManager.addSmartEventListener("message", changeHandler, activity) -} - -let makeIframe = (element, url) => { - open Types - Promise.make((resolve, _) => { - let iframe = createElement("iframe") - iframe.id = "orca-fullscreen" - iframe.src = url - iframe.name = "fullscreen" - iframe.style = "position: fixed; inset: 0; width: 100vw; height: 100vh; border: 0; z-index: 422222133323; " - iframe.onload = () => { - resolve(Dict.make()) - } - element->appendChild(iframe) - }) -} -let makeForm = (element, url, id) => { - open Types - let form = createElement("form") - form.id = id - form.name = id - form.action = url - form.method = "POST" - form.enctype = "application/x-www-form-urlencoded;charset=UTF-8" - form.style = "display: hidden; " - element->appendChild(form) - form -} - -let getOptionalJson = (ev, str) => { - ev->getEventDataObj->JSON.Decode.object->Option.getOr(Dict.make())->Dict.get(str) -} - -let getOptionalJsonFromJson = (ev, str) => { - ev->JSON.Decode.object->Option.getOr(Dict.make())->Dict.get(str) -} - -let getStringfromOptionaljson = (json: option, default: string) => { - json->Option.flatMap(JSON.Decode.string)->Option.getOr(default) -} - -let getBoolfromjson = (json: option, default: bool) => { - json->Option.flatMap(JSON.Decode.bool)->Option.getOr(default) -} - -let getStringfromjson = (json: JSON.t, default: string) => { - json->JSON.Decode.string->Option.getOr(default) -} - -let getThemePromise = dict => { - let theme = - dict - ->Utils.getJsonObjectFromDict("appearance") - ->Utils.getDictFromJson - ->Utils.getString("theme", "default") - - switch theme { - | "default" => None - | "brutal" => Some(ThemeImporter.importTheme("../BrutalTheme.bs.js")) - | "midnight" => Some(ThemeImporter.importTheme("../MidnightTheme.bs.js")) - | "charcoal" => Some(ThemeImporter.importTheme("../CharcoalTheme.bs.js")) - | "soft" => Some(ThemeImporter.importTheme("../SoftTheme.bs.js")) - | "none" => Some(ThemeImporter.importTheme("../NoTheme.bs.js")) - | _ => None - } -} - -let mergeTwoFlattenedJsonDicts = (dict1, dict2) => { - dict1 - ->Dict.toArray - ->Array.concat(dict2->Dict.toArray) - ->Dict.fromArray - ->JSON.Encode.object - ->unflattenObject -} - -let getArrayOfTupleFromDict = dict => { - dict - ->Dict.keysToArray - ->Array.map(key => (key, Dict.get(dict, key)->Option.getOr(JSON.Encode.null))) -} - -let makeOneClickHandlerPromise = sdkHandleOneClickConfirmPayment => { - open EventListenerManager - Promise.make((resolve, _) => { - if sdkHandleOneClickConfirmPayment { - resolve(JSON.Encode.bool(true)) - } else { - let handleMessage = (event: Types.event) => { - let json = event.data->eventToJson->getStringfromjson("")->safeParse - - let dict = json->Utils.getDictFromJson - if dict->Dict.get("oneClickDoSubmit")->Option.isSome { - resolve(dict->Dict.get("oneClickDoSubmit")->Option.getOr(true->JSON.Encode.bool)) - } - } - addSmartEventListener("message", handleMessage, "onOneClickHandlerPaymentConfirm") - Utils.handleOnConfirmPostMessage(~targetOrigin="*", ~isOneClick=true, ()) - } - }) -} diff --git a/src/orca-loader/PaymentSessionMethods.res b/src/orca-loader/PaymentSessionMethods.res index 65bd177cf..78512e758 100644 --- a/src/orca-loader/PaymentSessionMethods.res +++ b/src/orca-loader/PaymentSessionMethods.res @@ -1,7 +1,5 @@ open Types -external customerSavedPaymentMethodsToJson: getCustomerSavedPaymentMethods => JSON.t = "%identity" - let getCustomerSavedPaymentMethods = ( ~clientSecret, ~publishableKey, @@ -135,7 +133,7 @@ let getCustomerSavedPaymentMethods = ( getCustomerDefaultSavedPaymentMethodData, confirmWithCustomerDefaultPaymentMethod, } - ->customerSavedPaymentMethodsToJson + ->Identity.anyTypeToJson ->resolve | None => { let updatedCustomerDetails = diff --git a/src/orca-log-catcher/ErrorBoundary.res b/src/orca-log-catcher/ErrorBoundary.res index 03c5ce8e4..cb9a5bbfc 100644 --- a/src/orca-log-catcher/ErrorBoundary.res +++ b/src/orca-log-catcher/ErrorBoundary.res @@ -1,4 +1,3 @@ -external errorToJson: Sentry.ErrorBoundary.fallbackArg => JSON.t = "%identity" type errorLevel = Top | RequestButton | PaymentMethod let errorIcon = { @@ -113,7 +112,7 @@ module ErrorCard = { sessionId: "", source: "orca-elements", version: GlobalVars.repoVersion, - value: error->errorToJson->JSON.stringify, + value: error->Identity.anyTypeToJson->JSON.stringify, internalMetadata: "", category: USER_ERROR, paymentId: "",