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D,KAIlB5O,EAAKiP,iCAsBMC,EAAgC,IAAY,OAAD,6BAEtD,MAAMC,QAAuB,qBAAsBC,OAAOnF,QAI1D,IAAKkF,EACH,OAGF,MAAME,EAAgBF,EAAeG,aAAaC,gBAC5CpB,EAAcgB,EAAeK,iBAAiBC,cAG9CzP,QAAmC,qCACnCA,EAAKiP,gCACX,MAGMS,EAAU,IAAI,IACdC,EAA0C,CAC9CxB,YAAAA,EACAyB,UANgB,IASZC,EAAuBR,GAAgB,IAAIS,MAAOC,UAAY,IASpE,OARAL,EAAQM,IAAI,mBAAsCL,EAAqB,CACrE/N,KAAM,IACNsD,OAAQ,mBACR+K,QAAQ,EACRC,SAAU,OACVC,OAAQN,IAGHF,KAGIS,EAA8B,KACzC,MACMT,GADU,IAAI,KACgBU,IAClC,oBAQF,OAJEV,GACA,cAAeA,GACf,gBAAiBA,EAEEA,EAAsB","sources":["webpack://leadsbridge/./src/components/ConnectedPopupWindow/utils.ts","webpack://leadsbridge/./src/dataTracking/utils.ts","webpack://leadsbridge/./src/features/auth/bridgeByUrl/utils.ts","webpack://leadsbridge/./src/features/nbee/FieldsMappingForm/SendTestLeadSubForm/utils.ts","webpack://leadsbridge/./src/features/nbee/FieldsMappingForm/utils.ts","webpack://leadsbridge/./src/features/nbee/IncomingDataContent/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/AppAuthCredentialForm/fields/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/AppAuthCredentialForm/utils.ts","webpack://leadsbridge/./src/features/nbee/IntegrationCredentialsContent/utils.ts","webpack://leadsbridge/./src/features/nbee/SimpleBridgeBuilderForm/fields/AppSelector/utils.ts","webpack://leadsbridge/./src/features/nbee/SimpleBridgeBuilderForm/fields/IntegrationSettings/utils.ts","webpack://leadsbridge/./src/features/nbee/utils.ts","webpack://leadsbridge/./src/pages/BridgeByUrlCallback/utils.ts","webpack://leadsbridge/./src/services/apiAuthClient/utils.ts"],"sourcesContent":["import { useEffect, useState, MutableRefObject } from 'react'\n\ntype LbMessageEvent = {\n isLbMessage: boolean\n [key: string]: unknown\n}\n\nexport const calculateToCenterWindow = (w: number, h: number) => {\n const dualScreenLeft =\n window.screenLeft !== undefined ? window.screenLeft : window.screenX\n const dualScreenTop =\n window.screenTop !== undefined ? window.screenTop : window.screenY\n const width = window.innerWidth\n ? window.innerWidth\n : document.documentElement.clientWidth\n ? document.documentElement.clientWidth\n : screen.width\n const height = window.innerHeight\n ? window.innerHeight\n : document.documentElement.clientHeight\n ? document.documentElement.clientHeight\n : screen.height\n const systemZoom = width / window.screen.availWidth\n const left = (width - w) / 2 / systemZoom + dualScreenLeft\n const top = (height - h) / 2 / systemZoom + dualScreenTop\n\n return {\n left,\n top,\n }\n}\n\n// Send initial data to popup\nexport const postInitialDataToPopup = ({\n initialData,\n popup,\n}: {\n initialData?: any\n popup: Window\n}) => {\n if (!initialData) {\n return\n }\n\n const message: LbMessageEvent = {\n ...initialData,\n isLbMessage: true,\n }\n\n const targetOrigin =\n process.env.REACT_APP_BASE_URL || 'https://app.leadsbridge.com'\n\n // better to dalay the postMessage to be sure popup is properly loaded\n setTimeout(() => {\n popup.postMessage(message, targetOrigin)\n }, 1500)\n}\n\nconst allowedOrigins = (\n process.env.REACT_APP_ALLOWED_ORIGINS || 'https://app.leadsbridge.com'\n)\n .split(',')\n .map((origin) => origin.trim())\n .filter(Boolean)\n\n// Listen for message returned from popup\nexport const usePopupMessageReceiver = (\n popup: MutableRefObject<Window | null>\n) => {\n const [dataFromPopup, setDataFromPopup] = useState<Record<string, any>>()\n\n const messageReceiverFn = function (event: MessageEvent<LbMessageEvent>) {\n if (!allowedOrigins.includes(event.origin)) {\n console.warn(`Received message from unauthorized origin: ${event.origin}`)\n return\n }\n\n if (event.data.isLbMessage) {\n // console.log('Data received back from popup: ', event.data)\n setDataFromPopup(event.data)\n }\n }\n useEffect(() => {\n if (popup) {\n window.addEventListener('message', messageReceiverFn)\n }\n return () => window.removeEventListener('message', messageReceiverFn)\n }, [popup])\n\n return {\n dataFromPopup,\n }\n}\n\nexport const makePopupFeatures = (\n widthPx: number,\n heightPx: number\n): string => {\n const positionValues = calculateToCenterWindow(widthPx, heightPx)\n\n const params: Record<string, string | number> = {\n scrollbars: 'no',\n resizable: 'no',\n status: 'no',\n toolbar: 'no',\n menubar: 'no',\n width: widthPx,\n height: heightPx,\n left: positionValues.left,\n top: positionValues.top,\n }\n\n return Object.keys(params)\n .map((k) => `${k}=${params[k]}`)\n .join(',')\n}\n\n// Calculate dynamic popup sizes to avoid overflow scrollbar\nconst defaultPopupWeight = 900\nconst defaultPopupHeight = 700\n\nexport const getPopupWeight = () => {\n const currentWidth = window.screen.availWidth\n if (currentWidth < defaultPopupWeight) {\n return (95 * currentWidth) / 100\n } else {\n return defaultPopupWeight\n }\n}\n\nexport const getPopupHeight = () => {\n const currentHeight = window.screen.availHeight\n if (currentHeight < defaultPopupHeight) {\n return (90 * currentHeight) / 100\n } else {\n return defaultPopupHeight\n }\n}\n","import { CognitoUserInterface } from '@aws-amplify/ui-components'\nimport { BridgeFormValues, AppConfigurationType } from 'Nbee'\nimport { matchPath } from 'react-router'\nimport { appRoutes } from '@app/routes'\nimport { TrackingStep } from 'DataTracking'\n\nexport const extractUserIdFromCognitoUser = (user?: CognitoUserInterface) => {\n const slaveUserId: string =\n user && user.attributes && user.attributes['custom:legacySlaveUserId']\n ? 'SUID-' + user.attributes['custom:legacySlaveUserId']\n : 'SUID-0'\n\n const mainUserId: string =\n user && user.attributes && user.attributes['custom:legacyUserId']\n ? 'UID-' + user.attributes['custom:legacyUserId']\n : 'UID-0'\n\n const userId = slaveUserId === 'SUID-0' ? mainUserId : slaveUserId\n const accountId: string =\n user?.attributes && user.attributes['custom:legacyUserId']\n\n return {\n userId,\n accountId,\n }\n}\n\nexport const extractEmailFromCognitoUser = (\n user?: CognitoUserInterface\n): {\n email: string | undefined\n} => {\n const cognitoEmail: string | undefined =\n user && user.attributes && user.attributes.email\n // when doing social authentication we'll receive an email that contains `+EXTERNAL`, we need to strip that text out to avoid sending dups to segment\n const email = cognitoEmail?.replace('+EXTERNAL', '')\n\n return {\n email,\n }\n}\n\nexport const makeNbeeTrackingParams = (\n formValues: BridgeFormValues,\n type?: AppConfigurationType\n) => {\n // in case a type (source or destination) is passed, we can add more info\n const currentAppParams = type\n ? {\n appId: formValues[type].appId,\n appName: formValues.ui && formValues.ui[type]?.selectedAppName,\n integrationId: formValues[type].integrationId,\n integrationName:\n formValues.ui && formValues.ui[type]?.selectedIntegrationName,\n }\n : {}\n\n return {\n sourceAppId: formValues.source.appId,\n sourceAppName: formValues.ui?.source?.selectedAppName,\n destinationAppId: formValues.destination.appId,\n destinationAppName: formValues.ui?.destination?.selectedAppName,\n bridgeId: formValues.ui?.bridgeId,\n bridgeName: formValues.name,\n ...currentAppParams,\n }\n}\n\nexport const makePricingTrackingStep = (\n locationPathname: string\n): TrackingStep | undefined => {\n const isInPricing = matchPath(locationPathname, {\n path: appRoutes.pricing.path,\n exact: true,\n })\n const isInCheckout = matchPath(locationPathname, {\n path: appRoutes.checkout.path,\n exact: true,\n })\n\n return isInPricing ? 'Table' : isInCheckout ? 'Checkout' : undefined\n}\n","import { BbuPartnersName } from '@app/enums/bridgeByUrl'\n\nconst invalidBbuUrlErrors: Record<\n BbuPartnersName,\n { message: string; link: string; linkText: string }\n> = {\n [BbuPartnersName.facebookConversionLeads]: {\n message:\n 'Your URL is not valid, please check again from App Store or contact support.',\n link: 'https://business.facebook.com/events_manager2/',\n linkText: 'Go back to Meta Events Manager',\n },\n [BbuPartnersName.facebook]: {\n message:\n 'Your URL is not valid, please check again from App Store or contact support.',\n link: 'https://business.facebook.com/business/app-store/',\n linkText: 'Go back to Meta Business App Store',\n },\n [BbuPartnersName.tiktok]: {\n message:\n 'Your URL is not valid, please check again from your TikTok for Business dashboard or contact support.',\n link: 'https://www.tiktok.com/business/it/apps/tiktok',\n linkText: 'Go back to TikTok',\n },\n [BbuPartnersName.app]: {\n message: 'Your URL is not valid, please contact support.',\n link: 'https://www.leadsbridge.com',\n linkText: 'Go back to LeadsBridge',\n },\n}\n\n// generic messages added as fallback, if partnerName is not one of the allowed partners you should not reach this error block\nexport const getInvalidBbuUrlErrors = (partnerName: BbuPartnersName) =>\n invalidBbuUrlErrors[partnerName] || {\n message: 'Your URL is not valid, please contact support.',\n link: 'https://leadsbridge.com/contact-us/',\n linkText: 'Contact support',\n }\n","import { BridgeFormValues, MappedField } from 'Nbee'\nimport {\n ApiBridgeFieldDefinition,\n ApiTestFieldsMappingErrorItem,\n ApiTestFieldsMappingRequestBody,\n ApiTestableFieldsResponse,\n} from 'BackendApi'\nimport { FormikErrors } from 'formik'\n\nexport const tranformApiResponseToFormValues = (\n apiResponse: ApiTestableFieldsResponse\n) =>\n (apiResponse?.data || []).map((field) => ({\n id: field.id,\n label: field.label,\n value: field.lastValue,\n }))\n\n// We use this function to adapt formik state to performa API post request\n// to test fields mapping\nexport const transformFormValuesToTestMappingRequest = (\n fieldsMappingValues?: MappedField[]\n): ApiTestFieldsMappingRequestBody => {\n // Filter to ensure every field has a destinationFieldId defined\n const validFields = (fieldsMappingValues || []).filter(\n (field): field is MappedField & { destinationFieldId: string } =>\n !!field.destinationFieldId\n )\n\n // Now TypeScript knows destinationFieldId is guaranteed to be a string\n return validFields.map((field) => ({\n destinationFieldId: field.destinationFieldId,\n mappingType: field.mappingType,\n // Assuming you need to transform each MappedFieldMapping to ApiMappedField\n mapping: [...field.mapping],\n }))\n}\n\n// transform api response (test fields mapping) into a formik error state\nexport const fromApiTestReponseToFormErrors = (\n destinationFields: ApiBridgeFieldDefinition[],\n apiResult: ApiTestFieldsMappingErrorItem[]\n) => {\n const errors = destinationFields.map((field) => {\n const hasError = apiResult.find(\n ({ destinationFieldId }) => destinationFieldId === field.id\n )\n if (hasError) {\n return hasError.mapping.some((i) => i.sourceFieldId)\n ? {\n sourceFieldId: hasError.message,\n }\n : { destinationText: hasError.message }\n }\n return null\n })\n\n // some weird casting here since our error structure is more complex than formik built-in\n return {\n fieldsMapping: errors as any,\n } as FormikErrors<BridgeFormValues>\n}\n","import { MappedField, MappedFieldMapping } from 'Nbee'\n\nexport const isFieldMappingEmpty = (mapping: MappedFieldMapping): boolean =>\n !(mapping.sourceFieldId || mapping.text || mapping.formula?.id)\n\nexport const isFieldMapped = (field: MappedField): boolean =>\n field.mapping.some((m) => !isFieldMappingEmpty(m))\n\nexport const isFieldUnmapped = (field: MappedField): boolean =>\n !isFieldMapped(field)\n\nexport const getShowUnmappedInitialState = (\n fieldsMappingValues?: MappedField[]\n): boolean => {\n // to understand if the initial state for showUnmapped is true or false, we need to check\n // if all required fields are already mapped.\n const requiredFields = (fieldsMappingValues || []).filter((f) => f.isRequired)\n\n // when we have no required fields\n if (!requiredFields.length) {\n const allAreUnmapped = (fieldsMappingValues || []).every(\n (f) => !isFieldMapped(f)\n )\n // if all fields are not mapped, we need to return true and show unmapped field as initial state\n // instead is something is mapped we return false so that we don't show unmapped field as initial state, but we only show the mapped ones\n return allAreUnmapped\n }\n\n // we proceed to check the case where we have required fields\n const allRequiredAreMapped = requiredFields.length\n ? requiredFields.every((f) => isFieldMapped(f))\n : false\n\n // if all required fields are already mapped we can hide the not mapped fields\n return !allRequiredAreMapped\n}\n","import { App } from 'Nbee'\n\nexport const getListenerAppName = (appData: App | null | undefined): string => {\n const id = appData?.id || 0\n if (id === 1191) return 'your webhook system'\n if (id === 1208) return 'your email system'\n\n return appData?.name ?? ''\n}\n","import { IntegrationFormFieldType } from 'Nbee'\nimport { ApiAppSettingTypes } from 'BackendApi'\n\nexport const fieldsForSmartSelect: IntegrationFormFieldType[] = ['dropdown']\nexport const fieldsForSmartCreatableSelect: ApiAppSettingTypes[] = ['tags']\nexport const fieldsForSmartVerifyEmail: ApiAppSettingTypes[] = [\n 'validate_email',\n 'validate_email_multi',\n]\nexport const fieldsForDomain: IntegrationFormFieldType[] = [\n 'domain',\n 'subdomain',\n]\nexport const fieldsForToggle: IntegrationFormFieldType[] = ['toggle']\nexport const fieldsForInput: IntegrationFormFieldType[] = [\n 'text',\n 'number',\n 'password',\n 'textarea',\n 'datetime',\n 'code',\n 'email',\n 'url',\n]\n","import {\n ApiAppSchemaField,\n ApiAppSchemaFieldTypes,\n ApiIntegration,\n ApiSaveIntegrationRequestBody,\n ApiSettingValue,\n ApiSettingAcceptedValues,\n} from 'BackendApi'\nimport { IntegrationFormField, IntegrationFormValues } from 'Nbee'\nimport { PersistentSessionStorageKeys } from '@app/enums/persistentLocalStorageKeys'\n\nconst emptyValueByType: Record<\n ApiAppSchemaFieldTypes,\n ApiSettingAcceptedValues\n> = {\n password: '',\n textarea: '',\n code: '',\n number: '',\n datetime: '',\n domain: '',\n dropdown: '',\n email: '',\n text: '',\n tags: [],\n url: '',\n subdomain: '',\n toggle: false,\n validate_email: '',\n validate_email_multi: '',\n google_picker: '',\n}\n\n// we set a default value if api returns it only if field has not child, in this way we avoid infinite refetching loop\n// if no default value is provided we set an empty value depending of the type of the field\nconst getDefaultFromApi = (field: ApiAppSchemaField) =>\n field.default || field.default === 0\n ? field.default\n : emptyValueByType[field.type] ?? ''\n\nexport const makeIntegrationFormItemFromApiSchemaField = ({\n field,\n existingField,\n}: {\n field: ApiAppSchemaField\n existingField?: ApiSettingValue\n}): IntegrationFormField => {\n // const existingIntegration\n return {\n id: field.id,\n value: existingField?.value ?? getDefaultFromApi(field),\n label: field.label,\n type: field.type,\n isRequired: field.required,\n selectValues: field.data,\n hide: field.hide,\n default: field.default,\n tooltip: field.tooltip,\n docUrl: field.docUrl,\n hasChild: field.hasChild,\n format: field.format,\n refreshable: field.refreshable,\n }\n}\n\nexport const makeIntegrationFormInitialValues = (\n appAuthSchema: ApiAppSchemaField[],\n appName: string,\n existingIntegration?: ApiIntegration\n): IntegrationFormValues => {\n return {\n name: existingIntegration?.name || '',\n credentials: appAuthSchema.map((field) => {\n const existingField = (existingIntegration?.credentials || []).find(\n ({ key }) => {\n return key === field.id\n }\n )\n return makeIntegrationFormItemFromApiSchemaField({ field, existingField })\n }),\n ui: {\n existingIntegrationCredentials: existingIntegration?.credentials || [],\n },\n }\n}\n\nexport const transformIntegrationFormValuesToApiSaveRequestBody = (\n formValues: IntegrationFormValues,\n appId: number\n): ApiSaveIntegrationRequestBody => {\n /**\n * TRANSFORM EMPTY STRING ARRAYS INTO EMPTY ARRAYS\n * This function removes any array fields that only contain an empty string.\n * We add these empty strings to fields with email validation types (e.g. cc and bcc)\n * in order to render the corresponding Email Validation component.\n * However, the API does not accept these empty strings, so we remove them before\n * sending the form data to the API whenever users do not add any value to these fields.\n */\n\n const credentials = (formValues.credentials || []).map(\n ({ id, value, type }) => {\n if (\n type === 'validate_email_multi' &&\n Array.isArray(value) &&\n value.length === 1 &&\n value[0] === ''\n ) {\n return {\n key: id,\n value: [],\n }\n }\n return {\n key: id,\n value,\n }\n }\n )\n\n return {\n name: formValues.name,\n integrationId: formValues.integrationId,\n appId,\n credentials,\n }\n}\n\ntype RedirectParamsCredentials = Record<\n IntegrationFormField['id'],\n IntegrationFormField['value']\n>\n\nconst prepareCredentialObject = (credentials: IntegrationFormField[]) => {\n return credentials.reduce((acc, field) => {\n return {\n ...acc,\n [field.id]: field.value,\n }\n }, {} as RedirectParamsCredentials)\n}\n\nconst storeCredentials = (credentials: IntegrationFormField[]) => {\n const credentialsAsObject = prepareCredentialObject(credentials)\n sessionStorage.setItem(\n PersistentSessionStorageKeys.integrationAuthFlowCredentials,\n JSON.stringify(credentialsAsObject)\n )\n}\n\nexport const retrieveStoredCredentials = (): Record<string, any> => {\n const storedCredentials = sessionStorage.getItem(\n PersistentSessionStorageKeys.integrationAuthFlowCredentials\n )\n\n try {\n const parsedCredentials: Record<string, any> = JSON.parse(\n storedCredentials || '{}'\n )\n return parsedCredentials\n } catch {\n return []\n }\n}\n\nconst encodeUriParamsForV1 = (obj: RedirectParamsCredentials) =>\n window.btoa(JSON.stringify(obj))\n\nexport const decodeUriParamsFromV1 = (encodedValue?: string) => {\n try {\n return JSON.parse(window.atob(encodedValue || '{}'))\n } catch {\n return null\n }\n}\n\nexport const startOAuthFlow = ({\n credentials,\n redirectUri,\n appId,\n integrationId,\n isLegacy,\n}: {\n credentials: IntegrationFormField[]\n redirectUri: string\n appId: number\n integrationId?: number\n isLegacy: boolean\n}) => {\n // first thing we store the appId to session storage, so we can get it later\n sessionStorage.setItem(\n PersistentSessionStorageKeys.integrationAuthFlowAppId,\n `${appId}`\n )\n\n if (integrationId) {\n sessionStorage.setItem('instanceId', `${integrationId}`)\n }\n\n // ONLY LEGACY\n\n if (isLegacy) {\n // then we prepare an object to be encoded and sent as query string\n const credentialsAsObject = prepareCredentialObject(credentials)\n const encodedCredentials = encodeUriParamsForV1(credentialsAsObject)\n\n // we build the url and redirect the user to v1 who will create the integration\n // and will return a legacy integration id (v1)\n const uriHasQueryStringParams = redirectUri.includes('?')\n const oauthRedirectUri = `${redirectUri}${\n uriHasQueryStringParams ? '&' : '?'\n }providerId=${appId}¶ms=${encodedCredentials}`\n\n // if `integrationId` is passed it means we are editing an existing integration, so we need to add it to the redirect url\n // in this way v1 will now that is an edit and it won't create a new integration (SB-427)\n window.location.href = integrationId\n ? `${oauthRedirectUri}&instanceId=${integrationId}`\n : oauthRedirectUri\n } else {\n // then we store the credentials to session storage, so we can get it later\n storeCredentials(credentials)\n\n window.location.href = redirectUri\n /* window.location.href =\n '/integration/oauth2/callback?code=4/0AdQt8qiPlchf8d02DuQmZZsPgIpdPg6RerbPQFudHaKNpbZT0G4WAelBKCUiy-t8emtMJA&options=test&otherParam=test2' */\n }\n}\n","type PostMessageData = {\n isLbMessage: true\n integrationId: number\n integrationName: string\n}\n\nexport const sendIntegrationDataToParentWindow = (\n newIntegrationId: number,\n newIntegrationName: string\n) => {\n const parentWindow = window.opener\n if (!parentWindow) {\n return\n }\n\n const message: PostMessageData = {\n isLbMessage: true,\n integrationId: newIntegrationId,\n integrationName: newIntegrationName,\n }\n\n setTimeout(() => {\n // just be sure all segment events have been sent, before killing this window from the parent\n parentWindow.postMessage(message, '*')\n }, 300)\n}\n","import { App } from 'Nbee'\nimport { SelectValue } from '@components/Form/InputSmartSelect'\n\nexport const tranformApiAppsToSelectOptions = (\n apiApps?: App[]\n): SelectValue[] =>\n (apiApps || []).map((app) => ({\n value: `${app.id}`,\n parentAppId: app.parentAppId,\n label: app.name,\n logoUri: app.logoUriSmall,\n }))\n\nexport const getAppOptionFromAppId = (\n appId?: number,\n allOptions?: SelectValue[]\n) => (allOptions || []).find((option) => option.value === `${appId}`)\n","import { ApiAppSetting, ApiAppSettingTypes } from 'BackendApi'\nimport { SelectValue } from '@components/Form/InputSmartSelect'\nimport {\n AppConfigurationType,\n AppIntegrationSetting,\n BridgeFormValues,\n} from 'Nbee'\nimport FacebookService from '@app/services/FacebookService'\nimport { FormikErrors, FormikTouched } from 'formik'\nimport { InputFeedbackStatus } from '@components/Basic/InputFeedback'\n\n/*\n * Grouping setting field types to render specific components\n * example if in future we need to handle type `datatime` with a component\n * that is not a simple input (maybe a datetime-picker) we can take it off\n * from the `fieldsForInput` array and move it into a new one that will be handle\n * inside the main `IntegrationSettings` component\n */\nexport const fieldsForGooglePicker: ApiAppSettingTypes[] = ['google_picker']\n\nexport const fieldsForSmartSelect: ApiAppSettingTypes[] = ['dropdown']\nexport const fieldsForSmartCreatableSelect: ApiAppSettingTypes[] = ['tags']\nexport const fieldsForToggle: ApiAppSettingTypes[] = ['toggle']\nexport const fieldsForInput: ApiAppSettingTypes[] = [\n 'text',\n 'number',\n 'password',\n 'domain',\n 'textarea',\n 'datetime',\n 'code',\n 'email',\n 'url',\n 'subdomain',\n]\n\n/*\n * Helper to transorm formik value into react-select format\n */\nexport const transformSettingDataInSelectOptions = (\n settingData?: { id: string | number; text: string }[]\n): SelectValue[] =>\n (settingData || []).map(({ id, text }) => ({\n value: id,\n label: text,\n }))\n\nexport const getAppIntegrationSettingsIndex = (fieldId: string, settings: AppIntegrationSetting[]): number => {\n let index: number = 0\n for(const setting of settings) {\n if (setting.key === fieldId) {\n break\n }\n index++\n }\n return index\n}\n\n/*\n * Since setting fields are quite complex and we ar not using formik FieldArray\n * we need an helper to easly retrive error and touched state in order to properly\n * build our error feedback object of type `InputFeedbackStatus`\n */\nexport const getSettingFieldError = ({\n type,\n touched,\n errors,\n index,\n}: {\n type: AppConfigurationType\n touched: FormikTouched<BridgeFormValues>\n errors: FormikErrors<BridgeFormValues>\n index: number\n}): {\n isTouched: boolean\n errorMessage: string\n fieldStatus?: InputFeedbackStatus\n} => {\n const touchedSettings = ((touched[type]?.settings &&\n touched[type]?.settings) ||\n []) as boolean[]\n const errorsSettings = ((errors && errors[type] && errors[type]?.settings) ||\n []) as unknown as string[]\n const isTouched = touchedSettings[index]\n const errorMessage = errorsSettings[index]\n\n return {\n isTouched,\n errorMessage,\n fieldStatus: errorMessage\n ? {\n error: errorMessage,\n }\n : undefined,\n }\n}\n\n/*\n * This function is used to handle the \"create new form\" option if setting field is \"Facebook form\"\n * `callback` parameter is used to update form state\n */\nexport const handleCreateNewFacebookForm = (\n integrationSettings: AppIntegrationSetting[],\n callback: (payload?: {\n formID: string\n // eslint-disable-next-line camelcase\n form_url: string\n pageID: string\n name: string\n }) => void\n) => {\n if (!window.FB) {\n FacebookService.createScriptFb()\n }\n\n const pageIdSetting = integrationSettings.find((s) => s.key === 'pageId')\n const adAccountSetting = integrationSettings.find(\n (s) => s.key === 'advertiserAdAccountId'\n )\n\n const pageIdValue = pageIdSetting?.value\n const adAccountValue = adAccountSetting?.value as string\n\n if (!pageIdValue || !adAccountValue) {\n console.error('Missing adAccountValue or pageIdSetting')\n return\n }\n\n const fbUI = FB.ui as any\n\n fbUI(\n {\n method: 'lead_gen',\n page_id: pageIdValue,\n ad_account_id: adAccountValue.replace('act_', ''),\n },\n callback\n )\n}\n\n/*\n * Starting from setting fields returned from api, which are all empty,\n * we ne to return a new formik setting field state which include old values\n * for existing settings and default values for new ones\n */\nexport const fillNewSettingsWithExistingValues = (\n newAndEmptySettings: ApiAppSetting[],\n existingSettingsWithValues: AppIntegrationSetting[]\n): AppIntegrationSetting[] =>\n newAndEmptySettings.map((newEmptySetting) => {\n const oldSetting = existingSettingsWithValues.find(\n ({ key }) => key === newEmptySetting.id\n )\n if (oldSetting) {\n return oldSetting\n }\n\n // we set `false` for type toggle and `0` for type number\n // everything else it's safe to keep it as empty string (also if is an array of string)\n // inputs will always handle it as empty value\n return {\n key: newEmptySetting.id,\n value:\n newEmptySetting.default || newEmptySetting.default === 0\n ? newEmptySetting.default // if we have a default value we set it\n : newEmptySetting.type === 'toggle'\n ? false\n : newEmptySetting.type === 'number'\n ? 0\n : '',\n }\n })\n","import { StepBarStep } from '@components/StepBar'\nimport { useTranslation } from 'react-i18next'\nimport { useHistory } from 'react-router-dom'\nimport { appRoutes } from '@app/routes'\nimport {\n ApiBridgeAvailablePermissionCheckResponse,\n ApiBridgeAvailablePermissionChecklist,\n} from 'BackendApi'\nimport { useFormikContext } from 'formik'\nimport { useAppDispatch } from '@app/store/hooks'\nimport { useUpdateBridge } from '@app/api/updateBridge'\nimport { useCreateNewBridge } from '@app/api/createNewBridge'\nimport {\n closeAlertMessage,\n sendToast,\n setPath,\n} from '@app/store/actions/ApplicationConfigurationActions'\nimport { transformBridgeFormValuesToApiSaveBridgeBody } from '@app/api/utils/bridge'\nimport { BridgeFormValues } from 'Nbee'\n\nexport const makeNbeeSteps = (\n currentStepIndex?: number,\n bridgeId?: number | string,\n isWelcomeMessage?: boolean\n): StepBarStep[] => {\n const { t } = useTranslation()\n const history = useHistory()\n\n const step1Route = bridgeId\n ? appRoutes.nbeeStep1Edit.makeUrl(`${bridgeId}`)\n : appRoutes.nbeeStep1New.makeUrl()\n\n const step2Route = bridgeId ? appRoutes.nbeeStep2.makeUrl(`${bridgeId}`) : '/'\n\n if (currentStepIndex === undefined) {\n return []\n }\n\n // STEP 1\n if (currentStepIndex === 0) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step2Title'),\n label: t('nbee.bridgeBuilder.step2Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n // STEP 2\n if (currentStepIndex === 1) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n onStepClick: () => {\n history.push(step1Route)\n },\n },\n {\n title: isWelcomeMessage\n ? t('nbee.bridgeBuilder.step2TitleWelcome')\n : t('nbee.bridgeBuilder.step2Title'),\n label: isWelcomeMessage\n ? t('nbee.bridgeBuilder.step2TitleWelcome')\n : t('nbee.bridgeBuilder.step2Title'),\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n // STEP 3\n if (currentStepIndex === 2) {\n return [\n {\n title: t('nbee.bridgeBuilder.step1Title'),\n label: t('nbee.bridgeBuilder.step1Title'),\n onStepClick: () => {\n history.push(step1Route)\n },\n },\n {\n title: t('nbee.bridgeBuilder.step2Title'),\n label: t('nbee.bridgeBuilder.step2Title'),\n onStepClick: () => {\n history.push(step2Route)\n },\n },\n {\n title: t('nbee.bridgeBuilder.step3Title'),\n label: t('nbee.bridgeBuilder.step3Title'),\n },\n ]\n }\n\n return []\n}\n\n// this function is used to calculate the initial state of the shouldCheckPermissions state in Step2/FieldsMappingForm\nexport const calculateInitialShouldCheckPermissionsState = (\n payload: ApiBridgeAvailablePermissionCheckResponse | undefined\n): boolean => {\n const permissionChecklist = payload?.data.permissionChecklist\n const executeCheck = payload?.data.executeCheck\n\n if (permissionChecklist?.length !== 0 && executeCheck) {\n return true\n } else {\n return false\n }\n}\nexport const useUpdateBridgeToPricing = (\n bridgeId?: string | number | undefined,\n reasonId?: string,\n minimumPlanRequired?: number\n) => {\n const formik = useFormikContext<BridgeFormValues>()\n const history = useHistory()\n const dispatch = useAppDispatch()\n const { mutate: updateBridge } = useUpdateBridge()\n const { mutate: createNewBridge } = useCreateNewBridge()\n const prevPath = history.location.pathname\n\n const handleError = () => {\n dispatch(\n sendToast({\n title: 'Error',\n message: 'Bridge update failed. Please try again.',\n color: 'negative',\n })\n )\n }\n\n const handleClick = () => {\n const formValues = formik.values\n const bridgeData = transformBridgeFormValuesToApiSaveBridgeBody(formValues)\n\n if (bridgeId) {\n updateBridge(\n {\n bridgeData: bridgeData,\n bridgeId: `${bridgeId}`,\n },\n {\n onSuccess: () => {\n dispatch(setPath(prevPath))\n history.push(\n appRoutes.pricing.makeUrlWithState(reasonId, minimumPlanRequired)\n )\n dispatch(closeAlertMessage())\n },\n onError: handleError,\n }\n )\n } else {\n createNewBridge(bridgeData, {\n onSuccess: (data) => {\n const createdBridgeId = data?.data?.bridge?.id\n const newPath = appRoutes.nbeeStep1Edit.makeUrl(`${createdBridgeId}`)\n dispatch(setPath(newPath))\n history.push(\n appRoutes.pricing.makeUrlWithState(reasonId, minimumPlanRequired)\n )\n dispatch(closeAlertMessage())\n },\n onError: handleError,\n })\n }\n }\n\n return handleClick\n}\n","import { PersistentBbuData } from 'LeadsBridgeApp'\nimport { axiosInterceptor } from '@app/services/axiosInterceptor'\nimport { endpoints, getApiErrorMessage } from '@app/api/config'\nimport { BbuParnersFullName } from '@app/enums/bridgeByUrl'\nimport { PersistentLocalStorageKeys } from '@app/enums/persistentLocalStorageKeys'\n\nexport const validatePersistentBbuData = (\n bbuData?: Partial<PersistentBbuData>\n): boolean => {\n // wee need a try/catch statement to validate `new URL` constructor\n try {\n const isValidSourceLogo =\n bbuData?.source?.logo && new URL(bbuData?.source?.logo)\n const isValidDestinationLogo =\n bbuData?.destination?.logo && new URL(bbuData?.destination?.logo)\n const isValidRedirectUri =\n bbuData?.requestUri && new URL(bbuData.requestUri)\n return Boolean(\n isValidSourceLogo && isValidDestinationLogo && isValidRedirectUri\n )\n } catch {\n return false\n }\n}\n\nexport const userStatusForSurvey = ['NEW', 'DRAFT']\n\nexport const retryButtonPartnerLink: Record<BbuParnersFullName, string> = {\n [BbuParnersFullName.tiktok]: 'https://ads.tiktok.com',\n}\n\nconst setupBridge = async ({ requestUri }: { requestUri: string }) => {\n const axiosInstance = await axiosInterceptor()\n const apiResponse: string = await axiosInstance\n .post(endpoints.setupBridge, { requestUri })\n .then((response) => response.data?.callbackPath)\n return apiResponse\n}\n\n// This function is just a simplified version of what we'll do in future.\n// We still don't have partners with external flow (except FB, which is a custom Fbe)\n// So we return always tru\nexport const checkIfExternalFlowIsRequiredOrSetupBridge = ({\n partnerFullName,\n onSetupBridgeError,\n requestUri,\n}: {\n partnerFullName: BbuParnersFullName\n onSetupBridgeError: (errorMessage: string) => void\n requestUri: string\n}) => {\n const isExternalFlowRequired = partnerFullName !== 'tiktok' // we'll add logic in future\n if (isExternalFlowRequired) {\n // do something (probably it's going to redirect user to a new route eg: /bbu/external-flow/:partnerName or /fbe\n return\n }\n\n // if external flow is not required (eg. tiktok)\n console.log(`Partner does not have external flow, let's setup the bridge`)\n setupBridge({ requestUri })\n .then((callbackPath) => {\n window.sessionStorage.removeItem(\n PersistentLocalStorageKeys.bbuPersistentData\n )\n\n if (process.env.REACT_USE_MOCK_API === 'true') {\n console.log('Simulating redirect to: ' + callbackPath)\n } else {\n window.location.href = callbackPath || `${process.env.REACT_APP_V1_URL}`\n }\n })\n .catch((error) => {\n onSetupBridgeError(getApiErrorMessage({ error }))\n })\n}\n","import { CognitoUserInterface } from '@aws-amplify/ui-components'\nimport { CognitoDevice } from 'LeadsBridgeApp'\nimport { Auth } from 'aws-amplify'\nimport Cookies from 'universal-cookie'\nimport { PersistentCookiesKeys } from '@app/enums/persistentCookiesKeys'\nimport {\n CognitoUserPool,\n CognitoUser,\n CognitoUserSession,\n CognitoIdToken,\n CognitoRefreshToken,\n CognitoAccessToken,\n} from 'amazon-cognito-identity-js'\n\nexport interface HandleSignupCognitoProps {\n username: string\n idToken: string\n accessToken: string\n refreshToken: string\n isIframe?: boolean\n}\n\nexport const signInUserSessionCognito = ({\n username,\n idToken,\n accessToken,\n refreshToken,\n}: HandleSignupCognitoProps) => {\n const userPool = new CognitoUserPool({\n UserPoolId: process.env.REACT_APP_USER_POOL_ID || '',\n ClientId: process.env.REACT_APP_USER_POOL_WEB_CLIENT_ID || '',\n })\n const cognitoIdToken = new CognitoIdToken({\n IdToken: idToken,\n })\n const cognitoAccessToken = new CognitoAccessToken({\n AccessToken: accessToken,\n })\n const cognitoRefreshToken = new CognitoRefreshToken({\n RefreshToken: refreshToken,\n })\n\n const user = new CognitoUser({\n Username: username,\n Pool: userPool,\n })\n\n user.setSignInUserSession(\n new CognitoUserSession({\n AccessToken: cognitoAccessToken,\n IdToken: cognitoIdToken,\n RefreshToken: cognitoRefreshToken,\n })\n )\n\n user.getCachedDeviceKeyAndPassword()\n}\n\nexport const getUserDevice = (user: CognitoUserInterface): Promise<string> => {\n return new Promise((resolve, reject) => {\n user.getDevice({\n onSuccess: (deviceKey: CognitoDevice) => {\n resolve(deviceKey.Device?.DeviceKey || '')\n },\n onFailure: (error?: string) => {\n reject(error || '')\n },\n })\n })\n}\n\ntype CognitoSessionData = {\n accessToken: string\n deviceKey: string\n}\n\n// allow to cache cognito accessToken and deviceKey\nexport const fetchAndPersistCognitoSession = async () => {\n // getting cognito session\n const cognitoSession = await Auth.currentSession().catch((error) => {\n console.warn(`'Cannot authenticate the request: ${error}`)\n })\n\n if (!cognitoSession) {\n return\n }\n\n const expirationSec = cognitoSession.getIdToken().getExpiration()\n const accessToken = cognitoSession.getAccessToken().getJwtToken()\n\n // getting user device\n const user: CognitoUserInterface = await Auth.currentAuthenticatedUser()\n await user.getCachedDeviceKeyAndPassword()\n const deviceKey = '' // await getUserDevice(user)\n\n // preparing data for cookie storage\n const cookies = new Cookies()\n const congnitoSessionData: CognitoSessionData = {\n accessToken,\n deviceKey,\n }\n // setting cookie expiration to match cognito session expiration\n const cookieExpirationSecs = expirationSec - new Date().getTime() / 1000\n cookies.set(PersistentCookiesKeys.CognitoSession, congnitoSessionData, {\n path: '/',\n domain: process.env.REACT_APP_V1_COOKIE_DOMAIN,\n secure: true,\n sameSite: 'none',\n maxAge: cookieExpirationSecs,\n })\n\n return congnitoSessionData\n}\n\nexport const getCognitoPersistentSession = () => {\n const cookies = new Cookies()\n const congnitoSessionData = cookies.get(\n PersistentCookiesKeys.CognitoSession\n ) as CognitoSessionData\n\n const isValidData =\n congnitoSessionData &&\n 'deviceKey' in congnitoSessionData &&\n 'accessToken' in congnitoSessionData\n\n return isValidData ? congnitoSessionData : null\n}\n"],"names":["postInitialDataToPopup","initialData","popup","message","isLbMessage","setTimeout","postMessage","allowedOrigins","split","map","origin","trim","filter","Boolean","usePopupMessageReceiver","dataFromPopup","setDataFromPopup","useState","messageReceiverFn","event","includes","data","useEffect","window","addEventListener","removeEventListener","makePopupFeatures","widthPx","heightPx","positionValues","w","h","dualScreenLeft","undefined","screenLeft","screenX","dualScreenTop","screenTop","screenY","width","innerWidth","document","documentElement","clientWidth","screen","height","innerHeight","clientHeight","systemZoom","availWidth","left","top","calculateToCenterWindow","params","scrollbars","resizable","status","toolbar","menubar","Object","keys","k","join","getPopupWeight","currentWidth","getPopupHeight","currentHeight","availHeight","extractUserIdFromCognitoUser","user","slaveUserId","attributes","userId","accountId","makeNbeeTrackingParams","formValues","type","currentAppParams","appId","appName","ui","selectedAppName","integrationId","integrationName","selectedIntegrationName","sourceAppId","source","sourceAppName","destinationAppId","destination","destinationAppName","bridgeId","bridgeName","name","makePricingTrackingStep","locationPathname","isInPricing","path","exact","isInCheckout","invalidBbuUrlErrors","link","linkText","getInvalidBbuUrlErrors","partnerName","tranformApiResponseToFormValues","apiResponse","field","id","label","value","lastValue","transformFormValuesToTestMappingRequest","fieldsMappingValues","destinationFieldId","mappingType","mapping","fromApiTestReponseToFormErrors","destinationFields","apiResult","fieldsMapping","hasError","find","some","i","sourceFieldId","destinationText","isFieldMapped","m","text","formula","isFieldUnmapped","getShowUnmappedInitialState","requiredFields","f","isRequired","length","every","getListenerAppName","appData","fieldsForSmartSelect","fieldsForSmartCreatableSelect","fieldsForDomain","fieldsForToggle","fieldsForInput","emptyValueByType","password","textarea","code","number","datetime","domain","dropdown","email","tags","url","subdomain","toggle","validate_email","validate_email_multi","google_picker","getDefaultFromApi","default","makeIntegrationFormItemFromApiSchemaField","existingField","required","selectValues","hide","tooltip","docUrl","hasChild","format","refreshable","makeIntegrationFormInitialValues","appAuthSchema","existingIntegration","credentials","key","existingIntegrationCredentials","transformIntegrationFormValuesToApiSaveRequestBody","Array","isArray","prepareCredentialObject","reduce","acc","retrieveStoredCredentials","storedCredentials","sessionStorage","getItem","JSON","parse","startOAuthFlow","redirectUri","isLegacy","setItem","credentialsAsObject","encodedCredentials","btoa","stringify","uriHasQueryStringParams","oauthRedirectUri","location","href","storeCredentials","sendIntegrationDataToParentWindow","newIntegrationId","newIntegrationName","parentWindow","opener","tranformApiAppsToSelectOptions","apiApps","app","parentAppId","logoUri","logoUriSmall","getAppOptionFromAppId","allOptions","option","fieldsForGooglePicker","transformSettingDataInSelectOptions","settingData","getSettingFieldError","touched","errors","index","touchedSettings","settings","errorMessage","isTouched","fieldStatus","error","handleCreateNewFacebookForm","integrationSettings","callback","FB","pageIdSetting","s","adAccountSetting","pageIdValue","adAccountValue","fbUI","method","page_id","ad_account_id","replace","fillNewSettingsWithExistingValues","newAndEmptySettings","existingSettingsWithValues","newEmptySetting","oldSetting","makeNbeeSteps","currentStepIndex","isWelcomeMessage","t","history","step1Route","step2Route","title","onStepClick","push","calculateInitialShouldCheckPermissionsState","payload","permissionChecklist","executeCheck","useUpdateBridgeToPricing","reasonId","minimumPlanRequired","formik","dispatch","mutate","updateBridge","createNewBridge","prevPath","pathname","handleError","color","bridgeData","values","onSuccess","onError","createdBridgeId","bridge","newPath","validatePersistentBbuData","bbuData","isValidSourceLogo","logo","URL","isValidDestinationLogo","isValidRedirectUri","requestUri","userStatusForSurvey","retryButtonPartnerLink","signInUserSessionCognito","username","idToken","accessToken","refreshToken","userPool","UserPoolId","ClientId","cognitoIdToken","IdToken","cognitoAccessToken","AccessToken","cognitoRefreshToken","RefreshToken","Username","Pool","setSignInUserSession","getCachedDeviceKeyAndPassword","fetchAndPersistCognitoSession","cognitoSession","catch","expirationSec","getIdToken","getExpiration","getAccessToken","getJwtToken","cookies","congnitoSessionData","deviceKey","cookieExpirationSecs","Date","getTime","set","secure","sameSite","maxAge","getCognitoPersistentSession","get"],"sourceRoot":""}