{"version":3,"sources":["lib/services/billing.tsx","lib/services/permissions.tsx","lib/services/UserServiceBackend.ts","lib/services/UserSettingsService.ts","lib/services/stat.ts","lib/services/intercom-wrapper.js","lib/services/analytics.ts","lib/services/rpc.ts","lib/services/jitsu-next-ee-client.ts","lib/services/BackendApiClient.ts","lib/services/ServerStorage.ts","lib/services/ApplicationConfiguration.ts","lib/services/slack.ts","lib/services/oauth.ts","lib/services/ProjectService.ts","lib/services/UserServiceFirebase.ts","lib/services/ApplicationServices.ts","lib/services/model.ts"],"names":["opensource","name","id","quota","destinations","sources","events","allowedSchedules","free","price","growth","premium","enterprise","paymentPlans","fetchCurrentSubscription","services","ApplicationServices","get","billingUrl","applicationConfiguration","planId","billingEmail","project_id","activeProject","user_id","userService","getUser","getIdToken","id_token","fetch","method","body","JSON","stringify","subscriptionResponse","status","doNotBlock","json","subscription","console","error","getCurrentSubscription","projectId","backendApiClient","destinationsStore","sourcesStore","statService","StatisticsService","subscriptionEnd","stripeSubscriptionObject","current_period_end","moment","undefined","subscriptionStart","current_period_start","subscriptionIsManagedByStripe","endOf","startOf","subscriptionExpired","isBefore","utc","quotaPeriodStart","toDate","add","stat","info","reduce","res","item","usage","list","length","paymentPlan","Error","currentPlan","stripeCustomerId","autorenew","cancel_at_period_end","expiration","hasUnpaidInvoices","checkQuotas","numberFormat","format","generateCheckoutLink","params","link","withQueryParams","encode","generateCustomerPortalLink","signToken","showQuotaLimitModal","msg","content","closable","width","title","allPermissions","ProjectPermission","VIEW_CONFIG","MODIFY_CONFIG","withPermissionRequirement","Component","permissions","props","project","useProject","every","p","includes","join","LS_ACCESS_KEY","LS_REFRESH_KEY","BackendUserService","backendApi","storageService","smtpConfigured","ssoProvider","backendApiBase","user","_apiAccess","ssoAuthLink","encodeURIComponent","Promise","resolve","reject","email","password","post","noauth","response","ApiAccess","setTokens","signup","suggestedCompanyName","company","created","Date","toISOString","emailOptout","forcePasswordChange","saveUserInfo","userToDTO","token","getTokens","accessToken","refreshToken","getUserInfo","userDTO","userFromDTO","clearTokens","localStorage","getItem","setItem","removeItem","callback","cleaningCallback","cleanAuthorizationLocalStorage","then","sso_logout_url","mode","credentials","finally","needsConfirmation","concatenateURLs","getFullUiPath","newPassword","resetId","new_password","reset_id","updateTokens","access_token","refresh_token","newEmail","newSettings","disabled","isTelemetryEnabled","oauth","signupEnabled","href","Settings","UserSettingsLocalService","_keyNamePrefix","_userService","data","settings","keyName","settingName","parse","EventsComparison","series","granularity","current","currentExtrapolated","previous","lastPeriod","date","addSeconds","seconds","getTime","setSeconds","getSeconds","emptySeries","from","to","end","start","isSameOrAfter","push","subtract","mergeSeries","lowPriority","highPriority","Object","entries","index","map","key","val","sort","e1","e2","forEach","point","api","timeInUTC","datePoints","_","idx","entry","value","total","namespace","type","destinationId","queryParams","query","substring","getQuery","proxy","el","sourceId","requests","all","successData","skipData","errorData","sourceDataEntries","combineStatisticsData","errorsDataAvailable","destinationDataEntries","initIntercom","window","Intercom","intercomSettings","app_id","w","ic","d","document","i","c","arguments","q","args","l","s","createElement","async","src","x","getElementsByTagName","parentNode","insertBefore","readyState","attachEvent","addEventListener","getIntercom","defaultExecutors","execs","jitsu","eventType","payload","AnalyticsBlock","isBlocked","track","intercom","blockAll","unblockAll","ConsoleLogInterceptor","initialized","listeners","originalError","listener","interceptor","e","warn","apply","Array","prototype","slice","call","message","optionalParams","ApiErrorWrapper","apiDetails","findError","arg","isError","isArray","obj","isNullOrUndef","constructor","stack","getErrorPayload","error_message","error_name","error_stack","AnalyticsService","appConfig","globalErrorListenerPresent","errorTrackingInitialized","consoleInterceptor","_anonymizeUsers","_appName","buildId","init","rawConfig","keys","eventnative","jitsuClient","tracking_host","cookie_domain","randomize_url","set","app","setupGlobalErrorHandler","addListener","level","onGlobalError","sentry","Sentry","dsn","integrations","BrowserTracing","tracesSampleRate","setDebugInfo","logrocket","LogRocket","getSessionURL","sessionURL","scope","setExtra","domains","find","domain","indexOf","userProps","ensureErrorTrackingInitialized","identify","getJitsuIdPayload","internal_id","murmurhash","v3","customHandlers","waitlist","exec","client","features","anonymizeUsers","appName","otherFeatures","sysFeatures","appEnvironment","pagePath","path","doNotLog","isDev","sendException","event","filename","lineno","colno","onGlobalErrorEvent","reason","param","toUpperCase","url","responseStatus","responseObject","tryJson","parseJsonResponse","result","text","getErrorMessage","log","urlWithQueryString","k","v","notEmpty","ApiResponseError","request","rpc","rest","urlWithQuery","requestParams","fetchImpl","getFetch","getErrorText","ok","errorText","errorJson","rpcFetchImpl","useFetch","impl","global","removeDoubleSlashes","replace","getJitsuNextEeClient","host","checkClassicProject","auth","currentUser","fbToken","cache","headers","Authorization","createCustomToken","customToken","DEFAULT_OPTIONS","version","APIError","_httpStatus","_response","errorResponse","parseErrorResponseBody","strResponse","toString","JWTBackendClient","baseUrl","proxyUrl","apiAccessAccessor","analyticsService","axios","interceptors","use","originalRequest","config","supportRefreshToken","_retry","transform","options","opts","baseUrlWithApiVersion","fullUrl","urlParams","filter","transformResponse","timeout","toLowerCase","handleApiError","catch","baseMessage","onFailedAPI","requestPayload","errorMessage","reloadPage","JSON_FORMAT","AS_IS_FORMAT","ServerStorage","getEntitiesTable","collectionName","collectionId","object","delete","getAll","patch","put","HttpServerStorage","mergedUserInfo","sanitize","allow","USERS_INFO_PATH","ApplicationConfiguration","_rawConfig","_firebaseConfig","_backendApiBase","_backendApiProxyBase","_billingUrl","_billingApiBase","_oauthApiBase","_appEnvironment","_buildId","getRawApplicationConfig","firebase","getBackendApiBase","env","BILLING_API_BASE_URL","OAUTH_BACKEND_API_BASE","NODE_ENV","BUILD_ID","GIT_BRANCH","GIT_COMMIT_REF","BUILD_TIMESTAMP","process","parseJson","envVar","defaultValue","SlackApiService","apiAccess","Headers","requestOptions","append","fetchOptions","createFetchOptions","_body","project_name","channel","OauthService","oauthApiBase","_oauthSupported","_backendApiClient","sourceType","secretsStatus","service","supported","messageListener","isTrusted","source","oauthWindow","endOauthFlow","removeEventListener","close","open","oauthFlowPromise","timer","setInterval","closed","clearInterval","createProjectService","backend","updatePermissions","userId","getProjectUsers","assertIsArray","assertIsUserBasicInfo","linkUserToProject","errorIncludes","assertIsObject","assert","userStatus","unlinkFromProject","createProject","assertIsProject","requiresSetup","getAvailableProjects","userProjects","updateProject","assertHasAllProperties","FirebaseUserService","appFeatures","firebaseApp","firebaseUser","initializeApp","signupType","signup_type","provider","GithubAuthProvider","setCustomParameters","login","signInWithPopup","getAuth","a","isNewUser","trackSignup","GoogleAuthProvider","prompt","signInWithEmailAndPassword","fbLogin","signInWithCustomToken","fbUserPromise","unregister","onAuthStateChanged","fbUser","uid","displayName","signOut","isConfirmed","emailVerified","forceRefresh","getIdTokenResult","tokenInfo","expirationMs","expirationTime","now","setTimeout","createUserWithEmailAndPassword","trim","sendPasswordResetEmail","location","sendEmailVerification","updatePassword","updateEmail","_email","sendSignInLinkToEmail","protocol","btoa","handleCodeInApp","isSignInWithEmailLink","signInWithEmailLink","_applicationConfiguration","_analyticsService","_storageService","_slackApiService","_oauthService","_projectService","_userSettingsService","_features","onboardingNotCompleteErrorMessage","_currentSubscription","backendApiProxyBase","loadBackendConfiguration","configuration","configure","authorization","firebaseConfig","smtp","getAppVersion","appVersion","ActiveProject","Set","currentVersion","statusText","mapBackendConfigResponseToAppFeatures","uuid","s2s_auth","origins","users","pluginScript","script","onload","onerror","appendChild","_get","innerHTML","stop","responseData","environment","selfhosted","docker_hub_id","sso_provider","createDemoDatabase","enableCustomDomains","chatSupportType","billingEnabled","onlyAdminCanChangeUserEmail","only_admin_can_change_user_email","plugin_script","serverPublicUrl","server_public_url","_uid","_name","_emailOptout","_forcePasswordChange","_lastUpdated","_suggestedInfo","companyName","$type","_created","_onboarded","dto","localStorageTokensUpdateCallback","_accessToken","_refreshToken","_localStorageTokensUpdateCallback"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;AAOA;AAmBA,GAAMA,WAAuB,CAAG,CAC9BC,IAAI,CAAE,YADwB,CAE9BC,EAAE,CAAE,YAF0B,CAG9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EmhB,GAAG,CAACR,YAAJ,EAAoB,KAH5B,CAIL1gB,mBAAmB,CAAEkhB,GAAG,CAACP,oBAAJ,EAA4B,KAJ5C,CAKLrpB,IAAI,CAAE4pB,GAAG,CAACT,KAAJ,yBAAaS,GAAG,CAACL,cAAjB,+CAAa,qBAAoBvpB,IAAjC,CALD,CAMLC,EAAE,CAAE2pB,GAAG,CAACV,IANH,CAOL9gB,oBAAoB,uBAAEwhB,GAAG,CAACL,cAAN,+CAAE,qBAAoBC,WAPrC,CAAP,CASD,CAQM,GAAMvhB,UAAb,yBAKE,mBACEc,WADF,CAEEC,YAFF,CAGE6gB,gCAHF,CAIE,CAAC,iOARKC,YAQN,aAPMC,aAON,aANMC,iCAMN,QACA,KAAKF,YAAL,CAAoB/gB,WAApB,CACA,KAAKghB,aAAL,CAAqB/gB,YAArB,CACA,KAAKghB,iCAAL,CAAyCH,gCAAzC,CACD,CAbH,2OAeE,cAA0B,CACxB,MAAO,MAAKC,YAAZ,CACD,CAjBH,0BAmBE,cAA2B,CACzB,MAAO,MAAKC,aAAZ,CACD,CArBH,mCAuBE,8BAA+B,CAC7B,MAAO,MAAKA,aAAL,EAAsB,IAA7B,CACD,CAzBH,4BA2BE,sBAAahhB,WAAb,CAAkCC,YAAlC,CAAwD,CACtD,KAAK8gB,YAAL,CAAoB/gB,WAApB,CACA,KAAKghB,aAAL,CAAqB/gB,YAArB,CACA,KAAKghB,iCAAL,CAAuCjhB,WAAvC,CAAoDC,YAApD,EACD,CA/BH,yB","file":"static/js/main~213b07df.6ebde33b.chunk.js","sourcesContent":["// @Libs\nimport { ReactElement } from \"react\"\nimport { Modal, Typography } from \"antd\"\nimport moment, { Moment } from \"moment\"\n// @Services\nimport ApplicationServices from \"./ApplicationServices\"\nimport { BackendApiClient } from \"./BackendApiClient\"\n// @Types\nimport type { destinationsStore as DestinationsStore } from \"../../stores/destinations\"\nimport type { sourcesStore as SourcesStore } from \"../../stores/sources\"\nimport { DatePoint, StatisticsService } from \"lib/services/stat\"\n// @Utils\nimport { withQueryParams } from \"utils/queryParams\"\nimport { numberFormat } from \"../commons/utils\"\nimport { BillingPlanOptions } from \"lib/components/BillingPlanOptions/BillingPlanOptions\"\n\nexport type PricingPlanId = \"opensource\" | \"free\" | \"growth\" | \"premium\" | \"enterprise\"\n\nexport interface Quota extends Usage {\n //allowed schedules (sync frequency), see schedule.ts for IDs\n allowedSchedules: string[]\n}\n\nexport type PricingPlan = {\n name: string\n id: PricingPlanId\n quota: Quota\n price?: number\n}\n\nconst opensource: PricingPlan = {\n name: \"Opensource\",\n id: \"opensource\",\n quota: {\n destinations: 100,\n sources: 150,\n events: 10_000_000,\n allowedSchedules: [\"1d\", \"1h\", \"5m\", \"1m\", \"cron\"],\n },\n}\nconst free: PricingPlan = {\n name: \"Startup\",\n id: \"free\",\n quota: {\n destinations: 2,\n sources: 1,\n events: 250_000,\n allowedSchedules: [\"1d\"],\n },\n price: 0,\n}\nconst growth: PricingPlan = {\n name: \"Growth\",\n id: \"growth\",\n quota: {\n destinations: 10,\n sources: 5,\n events: 1_000_000,\n allowedSchedules: [\"1d\", \"1h\", \"5m\"],\n },\n price: 99,\n}\nconst premium: PricingPlan = {\n name: \"Premium\",\n id: \"premium\",\n quota: {\n destinations: 10,\n sources: 15,\n events: 10_000_000,\n allowedSchedules: [\"1d\", \"1h\", \"5m\", \"1m\", \"cron\"],\n },\n price: 299,\n}\nconst enterprise: PricingPlan = {\n name: \"Enterprise\",\n id: \"enterprise\",\n quota: {\n destinations: 100,\n sources: 150,\n events: 10_000_000,\n allowedSchedules: [\"1d\", \"1h\", \"5m\", \"1m\", \"cron\"],\n },\n}\nexport const paymentPlans: Record = {\n opensource,\n free,\n growth,\n premium,\n enterprise,\n} as const\n\nexport type Usage = {\n events: number\n sources: number\n destinations: number\n}\n\n/**\n * Status of current payment plan\n */\nexport type CurrentSubscription = {\n /**\n * Current plan. Might be 'free'\n */\n currentPlan: PricingPlan\n /**\n * Customer id in stripe. May be undefined if user paid directly\n */\n stripeCustomerId?: string\n /**\n * Start of the current billing period.\n */\n quotaPeriodStart: Moment\n /**\n * Current usage\n */\n usage: Usage\n /**\n * When subscription expires\n */\n expiration: Moment\n /**\n * Autorenew\n */\n autorenew: boolean\n /**\n * If UI shouldn't be blocked\n */\n doNotBlock: boolean\n\n /**\n * Unpaid invoices\n */\n hasUnpaidInvoices: boolean\n\n /**\n * If subscription is managed by stripe\n */\n subscriptionIsManagedByStripe: boolean\n}\n\n/**\n * Schema of the record in firebase\n */\nexport type FirebaseSubscriptionEntry = {\n /**\n * Pricing plan\n */\n planId: PricingPlanId\n /**\n * Billing email\n */\n billingEmail: string\n /**\n * Current id of the customer\n */\n stripeCustomerId?: string\n\n /**\n * If UI shouldn't be blocked\n */\n doNotBlock?: boolean\n\n hasUnpaidInvoices?: boolean\n\n /**\n * Stripe subscription data\n */\n stripeSubscriptionObject?: {\n current_period_end: number\n current_period_start: number\n cancel_at_period_end: boolean\n cancel_at?: number\n cancelled_at: number\n status: string\n }\n}\n\nasync function fetchCurrentSubscription(): Promise {\n const services = ApplicationServices.get()\n const billingUrl = services.applicationConfiguration.billingUrl\n\n if (!billingUrl) {\n return { planId: \"opensource\", billingEmail: \"none@none.com\" }\n }\n\n const project_id = services.activeProject.id\n const user_id = services.userService.getUser().id\n const id_token = await services.userService.getIdToken()\n\n try {\n const subscriptionResponse = await fetch(`${billingUrl}/api/get-current-subscription`, {\n method: \"POST\",\n body: JSON.stringify({ project_id, user_id, id_token }),\n })\n\n if (subscriptionResponse.status === 500) return { planId: \"free\", billingEmail: \"\", doNotBlock: true }\n\n const subscription = (await subscriptionResponse.json()).subscription\n\n if (!subscription) {\n return { planId: \"free\", billingEmail: \"none@none.com\" }\n }\n\n return subscription\n } catch (error) {\n console.error(\n \"Failed to fetch subscription. User: \",\n services.userService.getUser(),\n \"Project: \",\n services.activeProject,\n \"Error: \",\n error\n )\n return { planId: \"free\", billingEmail: \"none@none.com\", doNotBlock: true }\n }\n}\n\nexport async function getCurrentSubscription(\n projectId: string,\n backendApiClient: BackendApiClient,\n destinationsStore: typeof DestinationsStore,\n sourcesStore: typeof SourcesStore\n): Promise {\n const statService = new StatisticsService(backendApiClient, projectId, true)\n\n const subscription = await fetchCurrentSubscription()\n\n let subscriptionEnd = subscription.stripeSubscriptionObject?.current_period_end\n ? moment(subscription.stripeSubscriptionObject?.current_period_end * 1000)\n : undefined\n let subscriptionStart = subscription.stripeSubscriptionObject?.current_period_start\n ? moment(subscription.stripeSubscriptionObject?.current_period_start * 1000)\n : undefined\n let subscriptionIsManagedByStripe = true\n\n if (subscription.planId === \"enterprise\") {\n //enterprise customers always bills from the beginning of the month,\n //they are not subject if stripe billing period\n subscriptionEnd = moment().endOf(\"month\")\n subscriptionStart = moment().startOf(\"month\")\n subscriptionIsManagedByStripe = false\n }\n if (!subscriptionStart && subscription.planId !== \"free\" && subscription.planId !== \"opensource\") {\n //manually created subscription without stripe subscription object, set billing to calendar month\n subscriptionEnd = moment().endOf(\"month\")\n subscriptionStart = moment().startOf(\"month\")\n subscriptionIsManagedByStripe = false\n }\n\n const subscriptionExpired =\n subscription.stripeSubscriptionObject?.status === \"canceled\" && subscriptionEnd.isBefore(moment.utc())\n\n const quotaPeriodStart = subscriptionExpired ? moment.utc().startOf(\"month\") : subscriptionStart\n\n let stat: DatePoint[]\n try {\n stat = await statService.get(\n quotaPeriodStart.toDate(),\n quotaPeriodStart.add(1, \"M\").toDate(),\n \"day\",\n \"source\",\n \"push\",\n \"success\"\n )\n } catch (e) {\n console.info(\"Failed to obtain stat, it could happen if Jitsu configurator isn't connected to jitsu server\", e)\n stat = []\n }\n\n const events = stat.reduce((res, item) => {\n res += item.events\n return res\n }, 0)\n\n const usage = {\n events,\n sources: sourcesStore.list.length,\n destinations: destinationsStore.list.length,\n }\n\n const paymentPlan = subscriptionExpired ? paymentPlans.free : paymentPlans[subscription.planId]\n if (!paymentPlan) {\n throw new Error(`Unknown plan ${subscription.planId}`)\n }\n return {\n currentPlan: paymentPlan,\n quotaPeriodStart,\n stripeCustomerId: subscription.stripeCustomerId,\n usage,\n subscriptionIsManagedByStripe,\n autorenew: !subscription.stripeSubscriptionObject?.cancel_at_period_end,\n expiration: subscriptionEnd,\n doNotBlock: !!subscription.doNotBlock,\n hasUnpaidInvoices: !!subscription.hasUnpaidInvoices,\n }\n}\n\n/**\n * Checks if user is over the limits. Returns the description\n */\nexport function checkQuotas(status: CurrentSubscription): React.ReactElement {\n if (status.doNotBlock) {\n return null\n }\n if (status.usage.sources > status.currentPlan.quota.sources) {\n return (\n <>\n you currently using {status.usage.sources} sources which is above {status.currentPlan.id} plan limit{\" \"}\n (maximum number of sources is {status.currentPlan.quota.sources})\n \n )\n }\n if (status.usage.destinations > status.currentPlan.quota.destinations) {\n return (\n <>\n you currently using {status.usage.destinations} destinations which is above {status.currentPlan.id} plan\n limit (maximum number of destinations is {status.currentPlan.quota.destinations})\n \n )\n }\n if (status.usage.events > status.currentPlan.quota.events) {\n return (\n <>\n you processed {numberFormat(status.usage.events)} events per current\n month, which is above your {status.currentPlan.id} plan (\n {numberFormat(status.currentPlan.quota.events)} events per month) The\n quota restarts on: {moment(status.quotaPeriodStart).add(1, \"M\").format(\"MMM Do, YY\")}\n \n )\n }\n return null\n}\n\nexport function generateCheckoutLink(params: {\n project_id: string\n user_email: string\n plan_id: string\n redirect_base: string\n}): string {\n const billingUrl = ApplicationServices.get().applicationConfiguration.billingUrl\n const link = withQueryParams(`${billingUrl}/api/init-checkout`, params, { encode: [\"user_email\"] })\n return link\n}\n\nexport function generateCustomerPortalLink(\n params: {\n project_id: string\n user_email: string\n return_url: string\n },\n signToken?: string\n): string {\n const billingUrl = ApplicationServices.get().applicationConfiguration.billingUrl\n return withQueryParams(\n `${billingUrl}/api/to-customer-portal`,\n !signToken\n ? params\n : {\n ...params,\n }\n )\n}\n\nexport function showQuotaLimitModal(subscription: CurrentSubscription, msg: ReactElement) {\n Modal.info({\n content: (\n
\n
{msg}
\n \n
\n ),\n closable: true,\n width: 800,\n title: \"Please, upgrade your subscription\",\n })\n}\n","import useProject from \"../../hooks/useProject\"\nimport { ErrorCard } from \"../components/ErrorCard/ErrorCard\"\nimport { ProjectPermission } from \"../../generated/conf-openapi\"\n\nexport const allPermissions: ProjectPermission[] = [ProjectPermission.VIEW_CONFIG, ProjectPermission.MODIFY_CONFIG]\n\nexport function withPermissionRequirement(Component, ...permissions: ProjectPermission[]): React.FC {\n return props => {\n const project = useProject()\n if (permissions.every(p => ((project.permissions || []) as string[]).includes(p))) {\n return \n }\n return (\n
\n Your permissions are: {project.permissions?.join(\", \") || \"none\"}}\n />\n
\n )\n }\n}\n","import { ApiAccess, userFromDTO, userToDTO } from \"./model\"\nimport { cleanAuthorizationLocalStorage, concatenateURLs, reloadPage } from \"lib/commons/utils\"\nimport { getFullUiPath } from \"lib/commons/pathHelper\"\nimport { BackendApiClient } from \"./BackendApiClient\"\nimport { ServerStorage } from \"./ServerStorage\"\nimport { LoginFeatures, TelemetrySettings, UserEmailStatus, UserService } from \"./UserService\"\nimport { SignupRequest, TokensResponse, User } from \"../../generated/conf-openapi\"\nimport * as uuid from \"uuid\"\n\nexport const LS_ACCESS_KEY = \"en_access\"\nexport const LS_REFRESH_KEY = \"en_refresh\"\n\nexport class BackendUserService implements UserService {\n private user?: User\n private backendApi: BackendApiClient\n private readonly storageService: ServerStorage\n private readonly smtpConfigured: boolean\n private _apiAccess: ApiAccess\n private readonly ssoProvider: string\n private readonly ssoAuthLink: string\n\n constructor(\n backendApi: BackendApiClient,\n storageService: ServerStorage,\n smtpConfigured: boolean,\n ssoProvider: string,\n backendApiBase: string\n ) {\n this.backendApi = backendApi\n this.storageService = storageService\n this.smtpConfigured = smtpConfigured\n if (ssoProvider !== \"\") {\n this.ssoProvider = ssoProvider\n this.ssoAuthLink = `${backendApiBase}/v1/sso-login?redirect_uri=${encodeURIComponent(\n `${backendApiBase}/v1/sso-auth-callback`\n )}`\n }\n }\n\n initiateGithubLogin(): Promise {\n return new Promise((resolve, reject) => {\n reject(new Error(\"GitHub authorization isn't supported in BackendUserService\"))\n })\n }\n\n initiateGoogleLogin(): Promise {\n return new Promise((resolve, reject) => {\n reject(new Error(\"Google authorization isn't supported in BackendUserService\"))\n })\n }\n\n async sendConfirmationEmail(): Promise {\n throw new Error(\"Email verification currently not supported in self-hosted version\")\n }\n\n async login(email: string, password: string): Promise {\n let response = await this.backendApi.post(\"/users/signin\", { email, password }, { noauth: true })\n this._apiAccess = new ApiAccess(response[\"access_token\"], response[\"refresh_token\"], this.setTokens)\n this.setTokens(response[\"access_token\"], response[\"refresh_token\"])\n }\n\n async createUser(signup: SignupRequest): Promise {\n const response = await this.backendApi.post(\"/users/signup\", signup, { noauth: true })\n this.user = {\n suggestedCompanyName: signup.company,\n created: new Date().toISOString(),\n id: response[\"user_id\"],\n emailOptout: signup.emailOptout,\n forcePasswordChange: false,\n name: signup.name,\n email: signup.email,\n }\n\n this._apiAccess = new ApiAccess(response[\"access_token\"], response[\"refresh_token\"], this.setTokens)\n await this.storageService.saveUserInfo(userToDTO(this.user))\n }\n\n public async waitForUser(token?: string): Promise {\n if (this.user) {\n return\n }\n\n try {\n const { accessToken, refreshToken } = this.getTokens()\n //not authorized\n if (!accessToken) {\n return\n }\n\n this._apiAccess = new ApiAccess(accessToken, refreshToken, this.setTokens)\n const userDTO = await this.storageService.getUserInfo()\n this.user = userFromDTO(userDTO)\n } catch (error) {\n this.clearTokens()\n throw new Error(error)\n }\n }\n\n private getTokens(): { accessToken?: string; refreshToken?: string } {\n return {\n accessToken: localStorage.getItem(LS_ACCESS_KEY),\n refreshToken: localStorage.getItem(LS_REFRESH_KEY),\n }\n }\n\n private setTokens(accessToken: string, refreshToken: string): void {\n localStorage.setItem(LS_ACCESS_KEY, accessToken)\n localStorage.setItem(LS_REFRESH_KEY, refreshToken)\n }\n\n private clearTokens(): void {\n localStorage.removeItem(LS_ACCESS_KEY)\n localStorage.removeItem(LS_REFRESH_KEY)\n }\n\n removeAuth(callback: () => void) {\n const cleaningCallback = () => {\n cleanAuthorizationLocalStorage()\n callback()\n }\n\n this.backendApi\n .post(\"/users/signout\", {})\n .then(res => {\n if (res.sso_logout_url) {\n return fetch(res.sso_logout_url, { mode: \"cors\", credentials: \"include\" })\n }\n })\n .finally(cleaningCallback)\n }\n\n getUser(): User {\n if (!this.user) {\n throw new Error(\"User is null. Should you called services.userService.hasUser()?\")\n }\n return this.user\n }\n\n getUserEmailStatus(): UserEmailStatus {\n return { needsConfirmation: false }\n }\n\n sendPasswordReset(email?: string): Promise {\n if (!this.smtpConfigured) {\n throw new Error(\n \"SMTP isn't configured on the server.\"\n )\n }\n\n if (!email) {\n email = this.getUser().email\n }\n\n return this.backendApi.post(\n \"/users/password/reset\",\n {\n email: email,\n callback: concatenateURLs(getFullUiPath(), `/reset_password/{{token}}`),\n },\n { noauth: true }\n )\n }\n\n hasUser(): boolean {\n return !!this.user\n }\n\n changePassword(newPassword: string, resetId?: string): Promise {\n return this.backendApi\n .post(\"/users/password/change\", { new_password: newPassword, reset_id: resetId }, { noauth: !!resetId })\n .then((res: TokensResponse) => {\n if (!!this._apiAccess) {\n this._apiAccess.updateTokens(res.access_token, res.refresh_token)\n } else {\n this.clearTokens()\n }\n })\n }\n\n //changeEmail is supported via CLUSTER_ADMIN_TOKEN only\n async changeEmail(newEmail: string): Promise {\n return new Promise((resolve, reject) => {\n reject(new Error(\"changeEmail isn't supported in BackendUserService\"))\n })\n }\n\n async changeTelemetrySettings(newSettings: TelemetrySettings): Promise {\n await this.backendApi.post(\"/configurations/telemetry?id=global_configuration\", {\n disabled: { usage: !newSettings.isTelemetryEnabled },\n })\n }\n\n getLoginFeatures(): LoginFeatures {\n return { oauth: false, password: true, signupEnabled: false }\n }\n\n getSSOProvider(): string {\n return this.ssoProvider ?? \"\"\n }\n\n getSSOAuthLink(): string {\n return this.ssoAuthLink ?? \"\"\n }\n\n sendLoginLink(email: string): Promise {\n throw new Error(\"sendLoginLink is not supporteb by self-hosted user service\")\n }\n\n supportsLoginViaLink(): boolean {\n return false\n }\n\n isEmailLoginLink(href: string): boolean {\n throw new Error(\"isEmailLoginLink is not supporteb by self-hosted user service\")\n }\n\n loginWithLink(email: string, href: string): Promise {\n throw new Error(\"loginWithLink is not supported by self-hosted user service\")\n }\n\n async getIdToken(): Promise {\n throw new Error(\"getIdToken is not supported by self-hosted user service\")\n }\n\n apiAccess(): ApiAccess {\n return this._apiAccess\n }\n\n refreshAuth(): Promise {\n return Promise.resolve()\n }\n}\n","import { UserService } from \"./UserService\"\nimport { merge } from \"lodash\"\n\nexport enum Settings {\n ActiveProject = \"activeProject\",\n}\n\nexport interface UserSettingsService {\n set(data: { [key: string]: any }): void\n\n get(settingName?: string): any\n\n remove(settingName): void\n}\n\nexport class UserSettingsLocalService implements UserSettingsService {\n private _keyNamePrefix = \"userSettings\"\n private _userService: UserService\n\n constructor(userService: UserService) {\n this._userService = userService\n }\n\n private get keyName() {\n return `${this._keyNamePrefix}_${this._userService?.getUser()?.id}`\n }\n\n set(data: { [key: string]: any }): void {\n let settings = this.get()\n\n if (settings !== null) {\n settings = merge(settings, data)\n }\n\n localStorage.setItem(this.keyName, JSON.stringify(settings))\n }\n\n get(settingName?: string) {\n let json: string = localStorage.getItem(this.keyName)\n let data: any\n\n if (json !== null) {\n try {\n data = JSON.parse(json)\n } catch {\n return null\n }\n }\n\n if (settingName) {\n data = data?.[settingName] ?? null\n }\n\n return data\n }\n\n remove(settingName: string) {\n const settings = this.get()\n\n if (settings !== null && settings[settingName]) {\n delete settings[settingName]\n }\n\n localStorage.setItem(this.keyName, JSON.stringify(settings))\n }\n}\n","import moment, { Moment, unitOfTime } from \"moment\"\nimport { BackendApiClient } from \"./BackendApiClient\"\nimport { Project } from \"../../generated/conf-openapi\"\n/**\n * Events that come directly from sources are in the `source` namespace.\n * When events are processed internally in Jitsu thay may get multiplexed\n * in order to get delivered to different destinations and are counted in\n * the `destination` namespace. Total count of the `destination` events is\n * greater or equal to the total count of the `source` events due to the\n * multiplexing\n */\ntype EventsNamespace = \"source\" | \"destination\"\n\ntype EventsType = \"push\" | \"pull\"\n\ntype EventsCountType = \"success\" | \"skip\" | \"errors\"\n\ntype SourcesEventsCountTypePush = Exclude\ntype SourcesEventsCountType = EventsCountType\ntype DestinationsEventsCountTypePull = Exclude\ntype DestinationsEventsCountType = EventsCountType\n\ntype Granularity = \"day\" | \"hour\" | \"total\"\n\nexport type DatePoint = {\n date: Moment\n events: number\n}\n\n// type StatisticsPoint = {\n// [key in T]: number\n// }\n// type GenericDetailedStatisticsDatePoint = StatisticsPoint & {\n// date: Moment\n// total: number\n// }\n\n// // export type DetailedStatisticsDatePoint = GenericDetailedStatisticsDatePoint\n\n// export type SourcesStatisticsDatePoint = GenericDetailedStatisticsDatePoint\n// export type DestinationsStatisticsDatePoint = GenericDetailedStatisticsDatePoint\n\n// type DetailedStatisticsDatePointFull = {\n// date: Moment\n// success: number\n// skip: number\n// error: number\n// }\n\n// type DetailedStatisticsDatePointWithoutErrors = {\n// date: Moment\n// success: number\n// skip: number\n// }\n// export type DetailedStatisticsDatePoint = Namespace extends \"source\"\n// ? Type extends \"push\"\n// ? DetailedStatisticsDatePointWithoutErrors\n// : DetailedStatisticsDatePointFull\n// : Type extends \"push\"\n// ? DetailedStatisticsDatePointFull\n// : DetailedStatisticsDatePointWithoutErrors\n\nexport type CombinedStatisticsDatePoint = {\n date: Moment\n total: number\n success: number\n skip: number\n error?: number\n}\n\n/**\n * Information about events per current period and prev\n * period\n */\nexport class EventsComparison {\n current: number\n\n currentExtrapolated: number //if current isn't representing a full period (example, we're in the middle\n\n //of the hour), this value will contain extrapolated value. Currently not calculated, reserver for future use\n previous: number\n\n lastPeriod: Moment\n\n constructor(series: DatePoint[], granularity: Granularity) {\n if (series == null || series.length == 0) {\n this.current = this.previous = 0\n this.lastPeriod = null\n } else {\n this.current = series[series.length - 1].events\n this.lastPeriod = series[series.length - 1].date\n this.previous = series.length > 1 ? series[series.length - 2].events : null\n }\n }\n}\n\nexport interface IStatisticsService {\n get(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: \"source\",\n type: \"push\",\n status?: SourcesEventsCountTypePush\n ): Promise\n get(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: \"source\",\n type: \"pull\",\n status?: SourcesEventsCountType\n ): Promise\n get(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: \"destination\",\n type: \"push\",\n status?: DestinationsEventsCountType,\n destinationId?: string\n ): Promise\n get(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: \"destination\",\n type: \"pull\",\n status?: DestinationsEventsCountTypePull,\n destinationId?: string\n ): Promise\n getCombinedStatisticsBySources(\n start: Date,\n end: Date,\n granularity: Granularity,\n type: EventsType\n ): Promise\n getCombinedStatisticsByDestinations(\n start: Date,\n end: Date,\n granularity: Granularity,\n type: EventsType,\n destinationId: string\n ): Promise\n}\n\nexport function addSeconds(date: Date, seconds: number): Date {\n let res = new Date(date.getTime())\n res.setSeconds(res.getSeconds() + seconds)\n return res\n}\n\nfunction emptySeries(from: Moment, to: Moment, granularity: Granularity): DatePoint[] {\n let res: DatePoint[] = []\n let end = moment(to)\n .utc()\n .startOf(granularity as unitOfTime.StartOf)\n let start = moment(from)\n .utc()\n .startOf(granularity as unitOfTime.StartOf)\n while (end.isSameOrAfter(start)) {\n res.push({ date: moment(end), events: 0 })\n end = end.subtract(1, granularity as unitOfTime.DurationConstructor)\n }\n return res\n}\n\nfunction mergeSeries(lowPriority: DatePoint[], highPriority: DatePoint[]): DatePoint[] {\n return Object.entries({ ...index(lowPriority), ...index(highPriority) })\n .map(([key, val]) => {\n return { date: moment(key).utc(), events: val }\n })\n .sort((e1, e2) => {\n if (e1.date > e2.date) {\n return 1\n } else if (e1.date < e2.date) {\n return -1\n }\n return 0\n })\n}\n\nfunction index(series: DatePoint[]): Record {\n let res = {}\n series.forEach(point => {\n res[point.date.toISOString()] = point.events\n })\n return res\n}\n\nexport class StatisticsService implements IStatisticsService {\n private readonly api: BackendApiClient\n\n private readonly projectId: string\n\n private readonly timeInUTC: boolean\n\n constructor(api: BackendApiClient, projectId: string, timeInUTC: boolean) {\n this.api = api\n this.projectId = projectId\n this.timeInUTC = timeInUTC\n }\n\n private combineStatisticsData(\n entries: Array<[EventsCountType, DatePoint[]]>\n ): CombinedStatisticsDatePoint[] {\n if (!entries.length) return []\n const datePoints = entries[0][1]\n return datePoints.map((_, idx) => {\n return entries.reduce(\n (point, entry) => {\n const date = entry[1][idx].date\n const name = entry[0]\n const value = entry[1][idx].events\n const total = point.total + value\n return {\n ...point,\n date,\n total,\n [name]: value,\n }\n },\n { total: 0 }\n ) as CombinedStatisticsDatePoint\n })\n }\n\n private getQuery(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: EventsNamespace,\n type: EventsType,\n status?: EventsCountType,\n destinationId?: string\n ): string {\n const queryParams = [\n [\"project_id\", this.projectId],\n [\"start\", start.toISOString()],\n [\"end\", end.toISOString()],\n [\"granularity\", granularity],\n [\"type\", type],\n ]\n if (namespace) queryParams.push([\"namespace\", namespace])\n if (status) queryParams.push([\"status\", status])\n if (destinationId) queryParams.push([namespace === \"source\" ? \"source_id\" : \"destination_id\", destinationId])\n const query = queryParams.reduce((query, [name, value]) => `${query}${name}=${value}&`, \"\")\n return query.substring(0, query.length - 1) // removes the last '&' symbol\n }\n\n public async get(\n start: Date,\n end: Date,\n granularity: Granularity,\n namespace: EventsNamespace,\n type: EventsType,\n status?: EventsCountType,\n destinationId?: string\n ): Promise {\n let response = await this.api.get(\n `/statistics/detailed?${this.getQuery(start, end, granularity, namespace, type, status, destinationId)}`,\n { proxy: true }\n )\n\n if (response[\"status\"] !== \"ok\") {\n throw new Error(\"Failed to fetch statistics data\")\n }\n\n const data = response[\"data\"]\n\n return mergeSeries(\n emptySeries(moment(start).utc(), moment(end).utc(), granularity),\n data.map(el => {\n return {\n date: this.timeInUTC ? moment(el.key).utc() : moment(el.key),\n events: el.events,\n }\n })\n )\n }\n\n public async getCombinedStatisticsBySources(\n start: Date,\n end: Date,\n granularity: Granularity,\n type: EventsType,\n sourceId?: string\n ): Promise {\n if (sourceId === \"all\") {\n sourceId = \"\"\n }\n const requests = [\n this.get(start, end, granularity, \"source\", type, \"success\", sourceId),\n this.get(start, end, granularity, \"source\", type, \"skip\", sourceId),\n this.get(start, end, granularity, \"source\", type, \"errors\", sourceId),\n ]\n\n const [successData, skipData, errorData] = await Promise.all(requests)\n const sourceDataEntries: [SourcesEventsCountType, DatePoint[]][] = [\n [\"success\", successData],\n [\"skip\", skipData],\n [\"errors\", errorData],\n ]\n return this.combineStatisticsData(sourceDataEntries)\n }\n\n public async getCombinedStatisticsByDestinations(\n start: Date,\n end: Date,\n granularity: Granularity,\n type: EventsType,\n destinationId?: string\n ): Promise {\n if (destinationId === \"all\") {\n destinationId = \"\"\n }\n const errorsDataAvailable = type === \"push\"\n const requests = [\n this.get(start, end, granularity, \"destination\", type, \"success\", destinationId),\n this.get(start, end, granularity, \"destination\", type, \"skip\", destinationId),\n ]\n if (errorsDataAvailable)\n requests.push(this.get(start, end, granularity, \"destination\", type, \"errors\", destinationId))\n const [successData, skipData, errorData] = await Promise.all(requests)\n\n const destinationDataEntries: [DestinationsEventsCountType, DatePoint[]][] = [\n [\"success\", successData],\n [\"skip\", skipData],\n ]\n\n if (errorsDataAvailable) destinationDataEntries.push([\"errors\", errorData])\n\n return this.combineStatisticsData(destinationDataEntries)\n }\n}\n","export function initIntercom(key, data) {\n if (window && window.Intercom) {\n return\n }\n window.intercomSettings = {\n app_id: key,\n ...(data || {}),\n }\n ;(function () {\n var w = window\n var ic = w.Intercom\n if (typeof ic === \"function\") {\n ic(\"reattach_activator\")\n ic(\"update\", w.intercomSettings)\n } else {\n var d = document\n var i = function () {\n i.c(arguments)\n }\n i.q = []\n i.c = function (args) {\n i.q.push(args)\n }\n w.Intercom = i\n var l = function () {\n var s = d.createElement(\"script\")\n s.type = \"text/javascript\"\n s.async = true\n s.src = \"https://widget.intercom.io/widget/\" + key\n var x = d.getElementsByTagName(\"script\")[0]\n x.parentNode.insertBefore(s, x)\n }\n if (document.readyState === \"complete\") {\n l()\n } else if (w.attachEvent) {\n w.attachEvent(\"onload\", l)\n } else {\n w.addEventListener(\"load\", l, false)\n }\n }\n })()\n}\n\nexport function getIntercom() {\n return window.Intercom\n}\n","import { FeatureSettings } from \"./ApplicationServices\"\n// @ts-ignore\nimport murmurhash from \"murmurhash\"\nimport { isNullOrUndef, setDebugInfo } from \"../commons/utils\"\nimport { jitsuClient, JitsuClient } from \"@jitsu/sdk-js\"\nimport { getIntercom, initIntercom } from \"lib/services/intercom-wrapper\"\nimport { ApplicationConfiguration } from \"./ApplicationConfiguration\"\nimport * as Sentry from \"@sentry/react\"\nimport LogRocket from \"logrocket\"\nimport { BrowserTracing } from \"@sentry/tracing\"\n\ntype ConsoleMessageListener = (level: string, ...args) => void\n\ntype IntercomClient = (...args) => void\n\ntype Executor = (client: T, eventType: string, payload: any) => Promise | void\n\ninterface AnalyticsExecutors extends Record> {\n jitsu?: Executor\n intercom?: Executor\n}\n\nfunction defaultExecutors(execs: AnalyticsExecutors): AnalyticsExecutors {\n return {\n jitsu:\n execs?.jitsu ??\n ((jitsu, eventType, payload) => {\n if (!AnalyticsBlock.isBlocked()) {\n return jitsu.track(eventType, payload || {})\n }\n }),\n intercom:\n execs?.intercom ??\n ((intercom, eventType, payload) => {\n if (!AnalyticsBlock.isBlocked()) {\n intercom(\"trackEvent\", eventType, payload || {})\n }\n return Promise.resolve()\n }),\n }\n}\n\n/**\n * Allows to block all calls to any analytics service\n */\nexport const AnalyticsBlock = {\n blockAll: () => {\n localStorage.setItem(\"jitsuBlockAllTracking\", \"true\")\n },\n unblockAll: () => {\n localStorage.setItem(\"jitsuBlockAllTracking\", \"false\")\n },\n isBlocked: (): boolean => {\n return localStorage.getItem(\"jitsuBlockAllTracking\") === \"true\"\n },\n}\nclass ConsoleLogInterceptor {\n private initialized: boolean = false\n private listeners: ConsoleMessageListener[] = []\n private originalError: (message?: any, ...optionalParams: any[]) => void\n\n public addListener(listener: ConsoleMessageListener) {\n this.listeners.push(listener)\n }\n\n public init() {\n if (this.initialized) {\n return\n }\n let interceptor = this\n\n ;(function () {\n interceptor.originalError = console.error\n console.error = function () {\n interceptor.listeners.forEach((listener: ConsoleMessageListener) => {\n try {\n listener(\"error\", arguments)\n } catch (e) {\n console.warn(\"Error applying error listener\")\n }\n })\n interceptor.originalError.apply(this, Array.prototype.slice.call(arguments))\n }\n })()\n }\n\n public error(message?: any, ...optionalParams: any[]) {\n this.originalError.apply(this, Array.prototype.slice.call(arguments))\n }\n}\n\ntype ApiErrorInfo = {\n method: string\n url: string\n requestPayload: any\n responseStatus: number\n responseObject?: any\n errorMessage?: string\n}\n\nclass ApiErrorWrapper extends Error {\n private apiDetails: ApiErrorInfo\n\n constructor(message: string, apiDetails: ApiErrorInfo) {\n super(message)\n this.apiDetails = apiDetails\n }\n}\n\nfunction findError(args: any): Error {\n if (typeof args === \"string\" || typeof args === \"number\" || typeof args === \"boolean\") {\n return null\n }\n args = Array.prototype.slice.call(args)\n for (let i = 0; i < args.length; i++) {\n let arg = args[i]\n if (isError(arg)) {\n return arg\n } else if (Array.isArray(Array.prototype.slice.call(arg))) {\n let error = findError(arg)\n if (error) {\n return error\n }\n }\n }\n return null\n}\n\nfunction isError(obj: any) {\n if (isNullOrUndef(obj)) {\n return false\n }\n return (\n obj instanceof Error || obj.constructor.name === \"Error\" || (obj.message !== undefined && obj.stack !== undefined)\n )\n}\n\nexport type UserProps = {\n name?: string\n email: string\n id: string\n}\n\nexport function getErrorPayload(error: Error) {\n return {\n error_message: error.message ?? \"Empty message\",\n error_name: error.name ?? \"name_unknown\",\n error_stack: error.stack ?? \"\",\n }\n}\n\nexport default class AnalyticsService {\n private globalErrorListenerPresent: boolean = false\n private appConfig: ApplicationConfiguration\n private user: UserProps\n private jitsu?: JitsuClient\n private errorTrackingInitialized: boolean = false\n private consoleInterceptor: ConsoleLogInterceptor = new ConsoleLogInterceptor()\n private _anonymizeUsers = false\n private _appName = \"unknown\"\n private buildId: string\n\n constructor(appConfig: ApplicationConfiguration) {\n this.appConfig = appConfig\n this.consoleInterceptor.init()\n if (this.appConfig.rawConfig.keys.eventnative && !AnalyticsBlock.isBlocked()) {\n this.jitsu = jitsuClient({\n key: this.appConfig.rawConfig.keys.eventnative,\n tracking_host: \"https://t.jitsu.com\",\n cookie_domain: \"jitsu.com\",\n randomize_url: true,\n })\n this.jitsu.set(\n {\n app: this._appName,\n buildId: appConfig.buildId,\n },\n {}\n )\n }\n this.setupGlobalErrorHandler()\n this.consoleInterceptor.addListener((level, ...args) => {\n let error = findError(args)\n if (error) {\n this.onGlobalError(error, true)\n }\n })\n }\n\n public ensureErrorTrackingInitialized() {\n if (this.errorTrackingInitialized || AnalyticsBlock.isBlocked()) {\n return\n }\n\n if (this.appConfig.rawConfig.keys.sentry) {\n Sentry.init({\n dsn: this.appConfig.rawConfig.keys.sentry,\n integrations: [new BrowserTracing()],\n tracesSampleRate: 1.0,\n })\n setDebugInfo(\"sentry\", Sentry, false)\n }\n\n if (this.appConfig.rawConfig.keys.logrocket) {\n LogRocket.init(this.appConfig.rawConfig.keys.logrocket)\n LogRocket.getSessionURL(sessionURL => {\n Sentry.configureScope(scope => {\n scope.setExtra(\"LogRocket session\", sessionURL)\n })\n })\n setDebugInfo(\"logRocket\", LogRocket, false)\n }\n\n this.errorTrackingInitialized = true\n }\n\n public userHasDomain(email: string, domains: string[]) {\n return domains.find(domain => email.indexOf(\"@\" + domain) > 0) !== undefined\n }\n\n public onUserKnown(userProps?: UserProps) {\n if (!userProps) {\n return\n }\n this.user = userProps\n this.ensureErrorTrackingInitialized()\n if (this.appConfig.rawConfig.keys.sentry) {\n Sentry.setUser({ id: userProps.id, email: userProps.email })\n }\n if (this.appConfig.rawConfig.keys.logrocket) {\n LogRocket.identify(userProps.id, {\n email: userProps.email,\n })\n }\n if (this.jitsu) {\n this.jitsu.id(this.getJitsuIdPayload(userProps))\n }\n if (this.appConfig.rawConfig.keys.intercom && !AnalyticsBlock.isBlocked()) {\n initIntercom(this.appConfig.rawConfig.keys.intercom, {\n email: userProps.email,\n name: userProps.name,\n user_id: userProps.id,\n })\n }\n }\n\n public getJitsuIdPayload({ email, id }) {\n return {\n email: this._anonymizeUsers ? \"masked\" : email,\n internal_id: this._anonymizeUsers ? \"hid_\" + murmurhash.v3(email || id) : id,\n }\n }\n\n public track(eventType: string, payload?: any, customHandlers?: AnalyticsExecutors): Promise {\n const waitlist: Promise[] = []\n const add = (exec: Executor, client: T) => {\n if (client) {\n const res = exec(client, eventType, payload)\n //if res is promise\n if (res && typeof res === \"object\" && typeof res.then === \"function\") {\n waitlist.push(res)\n }\n }\n }\n const execs = defaultExecutors(customHandlers)\n add(execs.jitsu, this.jitsu)\n add(execs.intercom, getIntercom())\n return Promise.all(waitlist).then()\n }\n\n public configure(features: FeatureSettings) {\n this._anonymizeUsers = features.anonymizeUsers\n const { appName, ...otherFeatures } = features\n this._appName = appName\n if (this.jitsu) {\n this.jitsu.set(\n {\n app: this._appName,\n sysFeatures: otherFeatures,\n },\n {}\n )\n }\n }\n\n private isDev() {\n return this.appConfig.appEnvironment === \"development\"\n }\n\n public onPageLoad({ pagePath }: { pagePath: string }) {\n this.track(\n \"app_page\",\n { path: pagePath, app: this._appName },\n {\n intercom: (intercom, eventType, payload) => {},\n }\n )\n }\n\n public onGlobalError(error: Error, doNotLog?: boolean) {\n if (!doNotLog) {\n //call console log through interceptor, to make sure it won't be handled\n this.consoleInterceptor.error(\"[Jitsu] uncaught error\", error)\n }\n if (!this.isDev()) {\n try {\n this.sendException(error)\n } catch (e) {\n console.warn(\"Failed to send event to error monitoring\", e)\n }\n }\n }\n\n public onGlobalErrorEvent(event: ErrorEvent) {\n this.consoleInterceptor.error(\n `[Jitsu] uncaught error '${event.message || \"unknown\"}' at ${event.filename}:${event.lineno}:${event.colno}`,\n event.error\n )\n if (!this.isDev()) {\n try {\n this.sendException(event.error)\n } catch (e) {\n console.warn(\"Failed to send event to error monitoring\", e)\n }\n }\n }\n\n setupGlobalErrorHandler() {\n if (!this.globalErrorListenerPresent) {\n window.addEventListener(\"error\", event => this.onGlobalErrorEvent(event))\n window.addEventListener(\"unhandledrejection\", event => {\n this.onGlobalError(new Error(\"Unhandled rejection: \" + JSON.stringify(event.reason)))\n })\n this.globalErrorListenerPresent = true\n }\n }\n\n onFailedAPI(param: ApiErrorInfo) {\n let message = `[Jitsu] ${param.method.toUpperCase()} ${param.url} failed with ${\n param.responseStatus\n }:${JSON.stringify(param.responseObject)}`\n this.consoleInterceptor.error(message)\n if (!this.isDev()) {\n this.sendException(new ApiErrorWrapper(message, param))\n }\n }\n\n private sendException(error: Error) {\n if (!this.isDev()) {\n this.track(\"error\", getErrorPayload(error))\n }\n }\n}\n","import {getErrorMessage} from \"../commons/errors\";\n\nexport function tryJson(res: any) {\n if (typeof res === \"string\") {\n try {\n return JSON.parse(res);\n } catch (e) {\n return res;\n }\n }\n return res;\n}\n\nasync function parseJsonResponse(result: Response, method: string, url: string) {\n const text = await result.text();\n try {\n return JSON.parse(text);\n } catch (e) {\n const message = `Error parsing JSON (len=${text.length}) from ${method} ${url}: ${getErrorMessage(e)}`;\n console.log(`${message}. Full response:`, text);\n throw new Error(`${message}. See console for full response.`);\n }\n}\n\nfunction urlWithQueryString(url: string, query: Record) {\n return `${url}?${Object.entries(query)\n .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)\n .join(\"&\")}`;\n}\n\nfunction notEmpty(param): boolean {\n return param !== undefined && param !== null && Object.keys(param).length > 0;\n}\n\nexport class ApiResponseError extends Error {\n public response: object;\n public request: object;\n\n constructor(message: string, response: object, request: object) {\n super(message + \": \" + JSON.stringify(response));\n this.response = response;\n this.request = request;\n }\n}\n\nexport type RpcParams, Payload = any> = Omit & {\n method?: string;\n body?: Payload;\n query?: Query;\n};\n\ntype FetchType = typeof fetch;\n\nexport interface RpcFunc, Payload = any> {\n (url: string, params?: RpcParams): Promise;\n\n useFetch(fetchImpl: FetchType);\n}\n\nexport const rpc: RpcFunc = async (url, { body, ...rest } = {}) => {\n const urlWithQuery = notEmpty(rest?.query) ? urlWithQueryString(url, rest?.query || {}) : url;\n\n const method = rest.method || (body ? \"POST\" : \"GET\");\n let result: Response;\n const requestParams = {\n method: method,\n body: body ? JSON.stringify(body) : undefined,\n ...rest,\n };\n const fetchImpl = getFetch();\n try {\n result = await fetchImpl(urlWithQuery, requestParams);\n } catch (e) {\n throw new Error(`Error calling ${method} ${url}: ${getErrorMessage(e)}`);\n }\n\n const getErrorText = async (result: Response) => {\n try {\n return await result.text();\n } catch (e) {\n return \"Unknown error\";\n }\n };\n\n if (!result.ok) {\n let errorText = await getErrorText(result);\n const errorJson = tryJson(errorText);\n const message = `Error ${result.status} on ${method} ${url}`;\n console.log(message, errorJson);\n throw typeof errorJson === \"string\"\n ? new Error(`${message}: ${errorJson}`)\n : new ApiResponseError(message, errorJson, {\n url: urlWithQuery,\n ...requestParams,\n body: body || undefined,\n });\n }\n return await parseJsonResponse(result, method, url);\n};\nlet rpcFetchImpl: FetchType | undefined;\n\nrpc.useFetch = impl => {\n rpcFetchImpl = impl;\n};\n\nfunction getFetch() {\n if (rpcFetchImpl) {\n return rpcFetchImpl;\n } else if (global['fetch']) {\n return global['fetch'];\n } else {\n throw new Error(\"No fetch implementation found. Use rpc.useFetch() to set one.\");\n }\n}\n","import * as auth from \"firebase/auth\";\nimport {rpc} from \"./rpc\";\n\nexport type ClassicProjectStatus = {\n ok: boolean;\n uid: string | null;\n project: string | null;\n name: string | null;\n active: boolean | null;\n token?: string;\n};\n\nexport interface JitsuNextEeClient {\n checkClassicProject(): Promise;\n createCustomToken(): Promise;\n}\n\nfunction removeDoubleSlashes(s: string) {\n return s.replace(/([^:]\\/)\\/+/g, \"$1\");\n}\n\nexport function getJitsuNextEeClient(host: string): JitsuNextEeClient {\n return {\n checkClassicProject: async () => {\n const fbToken = await auth.getAuth().currentUser?.getIdToken();\n return await rpc(removeDoubleSlashes(`${host}/api/is-active`), {\n credentials: \"include\",\n cache: \"default\",\n mode: \"cors\",\n headers: {\n Authorization: `Bearer ${fbToken}`,\n },\n });\n },\n createCustomToken: async () => {\n const fbToken = await auth.getAuth().currentUser?.getIdToken();\n const res = await rpc(removeDoubleSlashes(`${host}/api/custom-token`), {\n headers: {\n Authorization: `Bearer ${fbToken}`,\n },\n });\n return res.customToken;\n },\n };\n}\n","import axios, { AxiosRequestConfig, AxiosResponse, AxiosTransformer, Method } from \"axios\"\nimport { cleanAuthorizationLocalStorage, concatenateURLs, reloadPage } from \"lib/commons/utils\"\nimport AnalyticsService from \"./analytics\"\nimport { ApiAccess, AS_IS_FORMAT, JSON_FORMAT } from \"./model\"\n\n/**\n * Additional options for API request\n */\nexport type ApiRequestOptions = {\n /**\n * If request should be sent to /proxy endpoint\n */\n proxy?: boolean\n /**\n * Get parameters (to avoid adding them to URL for better readability)\n */\n urlParams?: { [propName: string]: any }\n /**\n * If set to true, Auth header should not be added\n */\n noauth?: boolean\n /**\n * API version, 1 by default\n */\n version?: number\n}\n\nconst DEFAULT_OPTIONS: ApiRequestOptions = { version: 1 } as const\n\n/**\n * Backend API client. Authorization is handled by implementation\n */\nexport interface BackendApiClient {\n /**\n * For end-points that return JSON. In that case response will\n * be deserialized\n * @param url url\n * @param payload payload\n * @param opts additional options\n */\n post(url, payload: any, opts?: ApiRequestOptions): Promise\n\n /**\n * Same as post, but returns raw body\n */\n postRaw(url, data: any, opts?: ApiRequestOptions): Promise\n\n getRaw(url, opts?: ApiRequestOptions): Promise\n\n get(url: string, opts?: ApiRequestOptions): Promise\n\n put(url, payload: unknown, opts?: ApiRequestOptions): Promise\n\n patch(url, payload: unknown, opts?: ApiRequestOptions): Promise\n\n delete(url, opts?: ApiRequestOptions): Promise\n}\n\nexport class APIError extends Error {\n private _httpStatus: number\n private _response: any\n\n constructor(response: AxiosResponse, request: AxiosRequestConfig) {\n super(getErrorMessage(response, request))\n this._httpStatus = response.status\n this._response = response.data\n }\n}\n\nfunction getErrorMessage(response: AxiosResponse, request: AxiosRequestConfig): string {\n let errorResponse = parseErrorResponseBody(response)\n if (errorResponse && errorResponse.message) {\n return `${errorResponse.message} (#${response.status})`\n } else {\n return `Error ${response.status} at ${request.url}`\n }\n}\n\nfunction parseErrorResponseBody(response: AxiosResponse) {\n let strResponse = response.data.toString()\n if (response.data === null || response.data === undefined) {\n return null\n }\n if (typeof response.data === \"object\") {\n return response.data\n }\n try {\n return response.data ? JSON.parse(response.data.toString()) : null\n } catch (e) {\n return null\n }\n}\n\nexport class JWTBackendClient implements BackendApiClient {\n private readonly baseUrl: string\n private readonly proxyUrl: string\n private readonly apiAccessAccessor: () => ApiAccess\n private readonly analyticsService: AnalyticsService\n\n constructor(\n baseUrl: string,\n proxyUrl: string,\n apiAccessAccessor: () => ApiAccess,\n analyticsService: AnalyticsService\n ) {\n this.baseUrl = baseUrl\n this.proxyUrl = proxyUrl\n this.apiAccessAccessor = apiAccessAccessor\n this.analyticsService = analyticsService\n\n //Refresh token axios interceptor\n axios.interceptors.response.use(\n response => {\n return response\n },\n function (error) {\n const originalRequest = error.config\n\n //try to refresh only if 401 error + authorization supports refresh tokens\n if (\n error.response &&\n error.response.status === 401 &&\n apiAccessAccessor().supportRefreshToken() &&\n !originalRequest._retry &&\n !originalRequest.url.includes(\"/v1/users/token/refresh\")\n ) {\n originalRequest._retry = true\n return axios\n .post(concatenateURLs(baseUrl, \"/v1/users/token/refresh\"), {\n refresh_token: apiAccessAccessor().refreshToken,\n })\n .then(res => {\n if (res.status === 200) {\n apiAccessAccessor().updateTokens(res.data[\"access_token\"], res.data[\"refresh_token\"])\n originalRequest.headers = {\n \"X-Client-Auth\": apiAccessAccessor().accessToken,\n }\n return axios(originalRequest)\n }\n })\n }\n\n return Promise.reject(error)\n }\n )\n }\n\n private exec(\n method: Method,\n transform: AxiosTransformer,\n url: string,\n payload: unknown,\n options: ApiRequestOptions = { version: 1 }\n ): Promise {\n const opts = { ...DEFAULT_OPTIONS, ...(options ?? {}) }\n const baseUrl = opts.proxy ? this.proxyUrl : this.baseUrl\n const baseUrlWithApiVersion = concatenateURLs(baseUrl, `/v${opts.version}/`)\n let fullUrl = concatenateURLs(baseUrlWithApiVersion, url)\n if (opts.urlParams) {\n fullUrl +=\n \"?\" +\n Object.entries(opts.urlParams)\n .filter(([, val]) => val !== undefined)\n .map(([key, val]) => `${key}=${encodeURIComponent(val + \"\")}`)\n .join(\"&\")\n }\n\n const request: AxiosRequestConfig = {\n method: method,\n url: fullUrl,\n transformResponse: transform,\n timeout: 600000,\n }\n\n if (!opts.noauth) {\n request.headers = {\n \"X-Client-Auth\": this.apiAccessAccessor().accessToken,\n }\n }\n\n if (payload !== undefined) {\n if (method.toLowerCase() === \"get\") {\n throw new Error(`System UI Error: GET ${fullUrl} can't have a body`)\n }\n request.data = payload\n }\n return new Promise((resolve, reject) => {\n axios(request)\n .then((response: AxiosResponse) => {\n if (response.status == 200 || response.status == 201) {\n resolve(response.data)\n } else if (response.status == 204) {\n resolve({})\n } else {\n let error = new APIError(response, request)\n this.handleApiError(request, response)\n reject(error)\n }\n })\n .catch(error => {\n if (error.response) {\n this.handleApiError(request, error.response)\n reject(new APIError(error.response, request))\n } else {\n let baseMessage = \"Request at \" + fullUrl + \" failed\"\n if (error.message) {\n baseMessage += \" with \" + error.message\n }\n this.analyticsService.onFailedAPI({\n method: request.method,\n url: request.url,\n requestPayload: request.data,\n responseStatus: -1,\n errorMessage: baseMessage,\n })\n reject(error)\n reject(new Error(baseMessage))\n }\n })\n })\n }\n\n private handleApiError(request: AxiosRequestConfig, response: AxiosResponse) {\n this.analyticsService.onFailedAPI({\n method: request.method,\n url: request.url,\n requestPayload: request.data,\n responseStatus: response.status,\n responseObject: response.data,\n })\n\n //we should remove authorization and reload page\n if (response.status == 401) {\n cleanAuthorizationLocalStorage()\n reloadPage()\n }\n }\n\n get(url: string, opts?: ApiRequestOptions): Promise {\n return this.exec(\"get\", JSON_FORMAT, url, undefined, opts)\n }\n\n post(url: string, data: any, opts?: ApiRequestOptions): Promise {\n return this.exec(\"post\", JSON_FORMAT, url, data, opts)\n }\n\n put(url: string, data: unknown, opts?: ApiRequestOptions): Promise {\n return this.exec(\"put\", JSON_FORMAT, url, data, opts)\n }\n\n patch(url: string, data: unknown, opts?: ApiRequestOptions): Promise {\n return this.exec(\"PATCH\", JSON_FORMAT, url, data, opts)\n }\n\n delete(url: string, opts?: ApiRequestOptions): Promise {\n return this.exec(\"delete\", JSON_FORMAT, url, undefined, opts)\n }\n\n postRaw(url, data: unknown, opts?: ApiRequestOptions): Promise {\n return this.exec(\"post\", AS_IS_FORMAT, url, data ?? {}, opts)\n }\n\n getRaw(url, opts?: ApiRequestOptions): Promise {\n return this.exec(\"get\", AS_IS_FORMAT, url, undefined, opts)\n }\n}\n","import ApplicationServices from \"./ApplicationServices\"\nimport { BackendApiClient } from \"./BackendApiClient\"\nimport { UserDTO } from \"./model\"\nimport { merge } from \"lodash\"\nimport { sanitize } from \"../commons/utils\"\n\n/**\n * A generic object storage\n */\nexport abstract class ServerStorage {\n protected readonly backendApi: BackendApiClient\n\n constructor(backendApi: BackendApiClient) {\n this.backendApi = backendApi\n }\n\n /**\n * Returns user info object (user id is got from authorization token)\n */\n abstract getUserInfo(): Promise\n\n /**\n * Saves users information required for system (on-boarding status, user projects, etc.)\n * (user id is got from authorization token)\n * @param data User JSON representation\n */\n abstract saveUserInfo(userInfo: Partial): Promise\n\n /**\n * Returns a table-like structure for managing config. See ConfigurationEntitiesTable\n */\n table(type: ObjectsApiTypes): ConfigurationEntitiesTable {\n let projectId = ApplicationServices.get().activeProject.id\n if (type === \"api_keys\") {\n return getEntitiesTable(this.backendApi, type, projectId)\n }\n if (type === \"destinations\") {\n return getEntitiesTable(this.backendApi, type, projectId)\n }\n if (type === \"sources\") {\n return getEntitiesTable(this.backendApi, \"sources\", projectId)\n }\n\n throw new Error(`Unknown table type ${type}`)\n }\n}\n\n/**\n * Table-like structure for managing server-side config\n */\nexport interface ConfigurationEntitiesTable {\n /**\n * Return all entities\n */\n getAll(): Promise\n\n /**\n * Patches the entity by id (merges current version with object)\n */\n patch(id: string, object: Partial): Promise\n\n /**\n * Replaces entity by id\n */\n replace(id: string, object: T): Promise\n\n /**\n * Adds an object to collection\n */\n add(object: T): Promise\n\n /**\n * Removes entity by id\n */\n delete(id: string): Promise\n}\n\nfunction getEntitiesTable(\n api: BackendApiClient,\n collectionName: ObjectsApiTypes,\n collectionId: string\n): ConfigurationEntitiesTable {\n return {\n async add(object: T): Promise {\n return await api.post(`/objects/${collectionId}/${collectionName}`, object, {\n version: 2,\n })\n },\n async delete(id: string): Promise {\n return await api.delete(`/objects/${collectionId}/${collectionName}/${id}`, { version: 2 })\n },\n async getAll(): Promise {\n return await api.get(`/objects/${collectionId}/${collectionName}`, { version: 2 })\n },\n async patch(id: string, patch: T): Promise {\n return await api.patch(`/objects/${collectionId}/${collectionName}/${id}`, patch, {\n version: 2,\n })\n },\n async replace(id: string, object: T): Promise {\n return await api.put(`/objects/${collectionId}/${collectionName}/${id}`, object, {\n version: 2,\n })\n },\n }\n}\n\nexport class HttpServerStorage extends ServerStorage {\n public static readonly USERS_INFO_PATH = \"/users/info\"\n\n constructor(backendApi: BackendApiClient) {\n super(backendApi)\n }\n\n getUserInfo(): Promise {\n return this.backendApi.get(`/users/info`)\n }\n\n async saveUserInfo(data: Partial): Promise {\n let mergedUserInfo = sanitize(data, {\n // TODO _email is temporary\n allow: [\n \"_emailOptout\",\n \"_name\",\n \"_forcePasswordChange\",\n \"_name\",\n \"_onboarded\",\n \"_suggestedInfo\",\n \"_project\",\n \"_email\",\n ],\n })\n console.log(\"Saving user info\", mergedUserInfo)\n return this.backendApi.post(`/users/info`, mergedUserInfo)\n }\n}\n\ntype ObjectsApiTypes = \"destinations\" | \"sources\" | \"api_keys\"\n","import { getBackendApiBase } from \"lib/commons/pathHelper\"\nimport { concatenateURLs } from \"lib/commons/utils\"\n\ntype AppEnvironmentType = \"development\" | \"production\"\n\nexport class ApplicationConfiguration {\n private readonly _rawConfig: RawConfigObject\n private readonly _firebaseConfig: any\n private readonly _backendApiBase: string\n private readonly _backendApiProxyBase: string\n private readonly _billingUrl: string | null = null\n private readonly _billingApiBase: string | null = null\n private readonly _oauthApiBase: string | null = null\n /**\n * One of the following: `development`, `production`\n */\n private readonly _appEnvironment: AppEnvironmentType\n private readonly _buildId: string\n\n constructor() {\n this._rawConfig = getRawApplicationConfig()\n this._firebaseConfig = this._rawConfig.firebase\n const backendApi = getBackendApiBase(this._rawConfig.env)\n this._backendApiBase = concatenateURLs(backendApi, \"/api\")\n this._backendApiProxyBase = concatenateURLs(backendApi, \"/proxy/api\")\n this._billingUrl = this._rawConfig.env.BILLING_API_BASE_URL\n this._billingApiBase = this._billingUrl ? concatenateURLs(this._billingUrl, \"/api\") : null\n\n this._oauthApiBase = this._rawConfig.env.OAUTH_BACKEND_API_BASE\n ? concatenateURLs(this._rawConfig.env.OAUTH_BACKEND_API_BASE, \"/api\")\n : null\n this._appEnvironment = (this._rawConfig.env.NODE_ENV || \"production\").toLowerCase() as AppEnvironmentType\n this._buildId = [\n `b=${this._rawConfig.env.BUILD_ID || \"dev\"}`,\n `sc=${this._rawConfig.env.GIT_BRANCH || \"unknown\"}/${this._rawConfig.env.GIT_COMMIT_REF || \"unknown\"}`,\n `t=${this._rawConfig.env.BUILD_TIMESTAMP || \"unknown\"}`,\n ].join(\";\")\n\n console.log(\n `App config initialized. Backend: ${this._backendApiBase}. Env: ${\n this._appEnvironment\n }. Firebase configured: ${!!this._firebaseConfig}. Build info: ${this._buildId}. Billing API: ${\n this._billingApiBase\n }.`\n )\n }\n\n get buildId(): string {\n return this._buildId\n }\n\n get firebaseConfig(): any {\n return this._firebaseConfig\n }\n\n get appEnvironment() {\n return this._appEnvironment\n }\n\n get backendApiBase(): string {\n return this._backendApiBase\n }\n\n get backendApiProxyBase(): string {\n return this._backendApiProxyBase\n }\n\n get billingUrl(): string {\n return this._billingUrl\n }\n\n get billingApiBase(): string {\n return this._billingApiBase\n }\n\n get oauthApiBase(): string {\n return this._oauthApiBase ?? \"\"\n }\n\n get rawConfig(): RawConfigObject {\n return this._rawConfig\n }\n}\n\nexport type RawConfigObject = {\n env: Record\n firebase?: Record\n keys: {\n sentry?: string\n logrocket?: string\n intercom?: string\n jitsu?: string\n eventnative?: string\n }\n}\n\nfunction getRawApplicationConfig(): RawConfigObject {\n return {\n env: process.env || {},\n firebase: parseJson(process.env.FIREBASE_CONFIG, null),\n keys: parseJson(process.env.ANALYTICS_KEYS, {}),\n }\n}\n\nfunction parseJson(envVar, defaultValue) {\n if (envVar) {\n try {\n return JSON.parse(envVar)\n } catch (e) {\n throw new Error(`env variable suppose to contain JSON, but the content (${envVar}) is not parsable: ${e.message}`)\n }\n }\n return defaultValue\n}\n","import { withQueryParams } from \"utils/queryParams\"\nimport { ApiAccess } from \"./model\"\n\nexport interface ISlackApiService {\n /**\n * Shows whether slack support methods are callable (i.e. if env var is set)\n */\n supportApiAvailable: boolean\n /**\n * Creates a private support channel and returns an invitation link.\n */\n createPrivateSupportChannel: (project_id: string, project_name: string) => Promise\n}\n\ntype RequestOptions = {\n token?: string\n}\n\nexport class SlackApiService implements ISlackApiService {\n private readonly baseUrl: string = process.env.SLACK_API_URL\n\n private readonly apiAccess: () => ApiAccess\n\n constructor(apiAccess: () => ApiAccess) {\n this.apiAccess = apiAccess\n }\n\n private createFetchOptions(options?: RequestOptions) {\n const headers = new Headers()\n let requestOptions: RequestInit = {\n headers,\n }\n\n headers.append(\"X-Client-Auth\", this.apiAccess().accessToken)\n\n if (options?.token)\n requestOptions = {\n ...requestOptions,\n headers: { ...requestOptions.headers, Authorization: `Bearer: ${options.token}` },\n }\n return requestOptions\n }\n\n private async get(api: string, params?: { [key: string]: string }, options?: RequestOptions) {\n const fetchOptions = this.createFetchOptions(options)\n const response = await fetch(withQueryParams(`${this.baseUrl}/${api}`, params), fetchOptions)\n return await response.json()\n }\n\n private async post(api: string, _body?: UnknownObject, options?: RequestOptions) {\n const fetchOptions = this.createFetchOptions(options)\n const body = _body ? JSON.stringify(_body) : null\n const response = await fetch(`${this.baseUrl}/${api}`, { ...fetchOptions, method: \"POST\", body })\n return await response.json()\n }\n\n public async createPrivateSupportChannel(project_id: string, project_name: string): Promise {\n const response = await this.post(\"create-support-channel\", {\n project_id,\n project_name,\n })\n if (!response.ok) throw new Error(response.error ?? \"Slack API Service failed to create a channel\")\n return response.channel?.url\n }\n\n public get supportApiAvailable(): boolean {\n return !!this.baseUrl\n }\n}\n","import { BackendApiClient } from \"./BackendApiClient\"\n\ntype OauthResult = OauthCredentials | OauthWarning | OauthError\n\ntype OauthCredentials = { status: \"success\"; secrets: any }\ntype OauthWarning = { status: \"warning\"; message: string }\ntype OauthError = {\n status: \"error\"\n message?: string\n /** @deprecated as of Jan 2022 */\n errorMessage?: string\n errorDetails?: any\n}\n\nexport type OauthSupportResponse = {\n status: \"ok\"\n supported: boolean\n message: string\n}\n\nexport interface IOauthService {\n getAvailableBackendSecrets(sourceType: string, projectId: string): Promise\n checkIfOauthSupported(service: string): Promise\n getCredentialsInSeparateWindow(service: string): Promise\n}\n\nexport class OauthService implements IOauthService {\n private readonly _oauthApiBase: string\n private readonly _oauthSupported: boolean\n private readonly _backendApiClient: BackendApiClient\n\n constructor(oauthApiBase: string, backendApiClient: BackendApiClient) {\n this._oauthApiBase = oauthApiBase\n this._oauthSupported = !!oauthApiBase\n this._backendApiClient = backendApiClient\n }\n\n public async getAvailableBackendSecrets(sourceType: string, projectId: string): Promise {\n const secretsStatus = await this._backendApiClient.get(\n `sources/oauth_fields/${sourceType}?project_id=${projectId}`,\n {\n proxy: true,\n }\n )\n\n return (\n Object.entries(secretsStatus).reduce((result, [key, status]) => {\n if (!status[\"provided\"]) return result\n result.push(key)\n return result\n }, []) ?? []\n )\n }\n\n public async checkIfOauthSupported(service: string): Promise {\n if (!this._oauthSupported) return false\n const response = await fetch(`${this._oauthApiBase}/info/${service}`)\n if (response.status === 200) {\n const result: OauthSupportResponse = await response.json()\n return result.supported\n }\n return false\n }\n\n public async getCredentialsInSeparateWindow(service: string): Promise {\n if (!this._oauthApiBase)\n throw new Error(\n \"Failed to get oauth credentials. Did you forget to set OAUTH_BACKEND_API_BASE environment variable?\"\n )\n\n const oauthWindow = window.open(\n `${this._oauthApiBase}/oauth/${service}/init`,\n `Authorize ${service}`,\n \"toolbar=no, menubar=no, location=no, width=600, height=700, top=100, left=100\"\n )\n\n let endOauthFlow = (result: OauthResult) => {}\n const oauthFlowPromise = new Promise(resolve => {\n endOauthFlow = resolve\n })\n\n let result\n function messageListener(e: MessageEvent) {\n if (e.isTrusted && e.source === oauthWindow) {\n if (oauthWindow !== null) {\n result = e.data\n endOauthFlow(e.data)\n window.removeEventListener(\"message\", messageListener)\n oauthWindow.close()\n }\n }\n }\n\n if (oauthWindow === null) {\n throw new Error(\"OAuth flow failed: can't open a popup window\")\n }\n\n window.addEventListener(\"message\", messageListener)\n\n const timer = setInterval(() => {\n // using polling as a hack for a cross-origin request\n if (oauthWindow.closed && !result) {\n clearInterval(timer)\n endOauthFlow({ status: \"warning\", message: \"Oauth did not complete because popup window has been closed\" })\n window.removeEventListener(\"message\", messageListener)\n }\n }, 400)\n\n result = await oauthFlowPromise\n\n return result\n }\n}\n","/**\n * Class for working with projects and users\n */\nimport {\n LinkProjectRequest,\n Project,\n ProjectPermission,\n ProjectUserPermissions,\n ProjectWithPermissions,\n UserBasicInfo,\n} from \"../../generated/conf-openapi\"\nimport { BackendApiClient } from \"./BackendApiClient\"\nimport { assertHasAllProperties, assertIsArray, assertIsObject } from \"utils/typeCheck\"\nimport { assert } from \"../../utils/typeCheck\"\nimport { withQueryParams } from \"utils/queryParams\"\nimport { concatenateURLs } from \"lib/commons/utils\"\nimport { getFullUiPath } from \"lib/commons/pathHelper\"\nimport { errorIncludes } from \"utils/errorIncludes\"\n\nexport interface ProjectService {\n /**\n * Creates project and links it to an existing user\n * @param projectName\n */\n createProject(projectName: string): Promise\n\n /**\n * Get all projects available for current user\n */\n getAvailableProjects(): Promise\n\n /**\n * Patches the project with provided data. Project ID field is required.\n */\n updateProject(projectId: string, patch: Partial): Promise\n\n /**\n * Patches the project with provided data. Project ID field is required.\n */\n updatePermissions(projectId: string, userId: string, permissions: ProjectPermission[]): Promise\n\n /**\n * Get user\n * @param projectId\n */\n getProjectUsers(projectId: string): Promise\n\n /**\n * Links user with given email to project\n * @return 'invitation_sent' if user non existing and invitation to create account has been sent,\n * or 'user_linked' otherwise\n */\n linkUserToProject(\n projectId: string,\n link: Omit\n ): Promise<\"invitation_sent\" | \"user_linked\">\n\n /**\n * Unlinks user with given ID from project\n * @param projectId\n * @param userId\n */\n unlinkFromProject(projectId: string, userId: string): Promise\n}\n\nexport function createProjectService(backend: BackendApiClient): ProjectService {\n return {\n async updatePermissions(projectId: string, userId: string, permissions: ProjectPermission[]): Promise {\n await backend.post(\n `/project/${projectId}/permissions/${userId}`,\n { permissions: permissions.map(p => ProjectPermission[p]) },\n { version: 2 }\n )\n },\n\n async getProjectUsers(projectId: string): Promise {\n const response = await backend.get(`/project/${projectId}/users`, { version: 2 })\n assertIsArray(response, \"Assertion error in getProjectUsers: response is not an array\")\n return response.map((value, index) => {\n assertIsUserBasicInfo(\n value,\n `Assertion error in getProjectUsers: element with index ${index} is not a valid UserBasicInfo object`\n )\n return value\n })\n },\n\n async linkUserToProject(projectId, link): Promise<\"invitation_sent\" | \"user_linked\"> {\n const response = await backend\n .post(\n `/project/${projectId}/link`,\n { ...link, callback: concatenateURLs(getFullUiPath(), `/reset_password/{{token}}`) },\n { version: 2 }\n )\n .catch(error => {\n if (errorIncludes(error, \"mail service\")) {\n throw new Error(`SMTP is not configured on the server or the configuration is invalid.\\nDetails: ${error}`)\n }\n throw error\n })\n\n assertIsObject(response, `Assertion error in linkUserToProject: response is not an object`)\n assert(\n response.userStatus === \"existing\" || response.userStatus === \"created\",\n `Assertion error in linkUserToProject: response.userStatus can only be \"existing\" or \"created\" but received ${response.userStatus}`\n )\n switch (response.userStatus) {\n case \"existing\":\n return \"user_linked\"\n case \"created\":\n return \"invitation_sent\"\n }\n },\n\n async unlinkFromProject(projectId: string, userId: string): Promise {\n await backend.get(withQueryParams(`/project/${projectId}/unlink`, { userId }), { version: 2 })\n return\n },\n\n async createProject(name: string): Promise {\n const response = await backend.post(\"/projects\", { name }, { version: 2 })\n assertIsProject(response, \"Assertion error in createProject: value returned by POST is not a ProjectInfo object\")\n // return response\n\n // TEMPORARY - remove once backend does set `requiresSetup: true` for a new project\n const result = await backend.patch(`/projects/${response.id}`, { requiresSetup: true }, { version: 2 })\n assertIsProject(result, \"Assertion error in createProject: value returned by PATCH is not a ProjectInfo object\")\n return result\n },\n\n async getAvailableProjects(): Promise {\n const userProjects = await backend.get(`/projects`, { version: 2 })\n assertIsArray(\n userProjects,\n \"Assertion error in getAvailableProjects: value returned by GET /projects is not an array\"\n )\n return userProjects.map((value, index) => {\n assertIsProject(\n value,\n `Assertion error in getAvailableProjects: user project value at index ${index} is not a ProjectInfo object`\n )\n return value\n })\n },\n\n async updateProject(projectId: string, patch: Partial): Promise {\n await backend.patch(`/projects/${projectId}`, patch, { version: 2 })\n return\n },\n }\n}\n\nfunction assertIsProject(value: unknown, message: string): asserts value is Project {\n assertIsObject(value, `${message}\\nError in assertIsProject: value is not an object`)\n assertHasAllProperties(value, [\"id\", \"name\"], `${message}\\nError in assertIsProject`)\n}\n\nfunction assertIsUserBasicInfo(value: unknown, message: string): asserts value is UserBasicInfo {\n assertIsObject(value, `${message}\\nError in assertIsUserBasicInfo: value is not an object`)\n assertHasAllProperties(value, [\"id\", \"email\"], `${message}\\nError in assertIsProject`)\n return\n}\n","import { LoginFeatures, TelemetrySettings, UserEmailStatus, UserService } from \"./UserService\"\nimport { FirebaseApp, initializeApp } from \"firebase/app\"\nimport { ApiAccess, userFromDTO, userToDTO } from \"./model\"\nimport type { User as FirebaseUser } from \"@firebase/auth\"\nimport { BackendApiClient } from \"./BackendApiClient\"\nimport { ServerStorage } from \"./ServerStorage\"\nimport AnalyticsService from \"./analytics\"\nimport { FeatureSettings } from \"./ApplicationServices\"\nimport {\n createUserWithEmailAndPassword,\n getAuth,\n GithubAuthProvider,\n GoogleAuthProvider,\n isSignInWithEmailLink,\n onAuthStateChanged,\n sendEmailVerification,\n sendPasswordResetEmail,\n sendSignInLinkToEmail,\n signInWithCustomToken,\n signInWithEmailAndPassword,\n signInWithEmailLink,\n signInWithPopup,\n signOut,\n updateEmail,\n updatePassword,\n getIdToken,\n} from \"firebase/auth\"\nimport { reloadPage, setDebugInfo } from \"../commons/utils\"\nimport { SignupRequest, User } from \"../../generated/conf-openapi\"\n\nexport class FirebaseUserService implements UserService {\n private firebaseApp: FirebaseApp\n private user?: User\n private _apiAccess: ApiAccess\n private firebaseUser: FirebaseUser\n private backendApi: BackendApiClient\n private readonly storageService: ServerStorage\n private readonly analyticsService: AnalyticsService\n private readonly appFeatures: FeatureSettings\n\n constructor(\n config: any,\n backendApi: BackendApiClient,\n storageService: ServerStorage,\n analyticsService: AnalyticsService,\n appFeatures: FeatureSettings\n ) {\n this.firebaseApp = initializeApp(config)\n this.backendApi = backendApi\n this.storageService = storageService\n this.analyticsService = analyticsService\n this.appFeatures = appFeatures\n }\n\n private async trackSignup(email: string, signupType: \"google\" | \"github\" | \"email\") {\n return this.analyticsService.track(\"saas_signup\", {\n app: this.appFeatures.appName,\n user: { email: email, signup_type: signupType },\n })\n }\n\n initiateGithubLogin(): Promise {\n const provider = new GithubAuthProvider()\n provider.setCustomParameters({\n login: \"\",\n })\n return new Promise((resolve, reject) => {\n signInWithPopup(getAuth(), provider)\n .then(a => {\n resolve(a.user.email)\n return a[\"additionalUserInfo\"]?.isNewUser && this.trackSignup(a.user.email, \"github\")\n })\n .catch(error => {\n reject(error)\n })\n })\n }\n\n initiateGoogleLogin(): Promise {\n return new Promise((resolve, reject) => {\n const provider = new GoogleAuthProvider()\n provider.setCustomParameters({\n prompt: \"select_account\",\n })\n signInWithPopup(getAuth(), provider)\n .then(a => {\n resolve(a.user.email)\n return a[\"additionalUserInfo\"]?.isNewUser && this.trackSignup(a.user.email, \"google\")\n })\n .catch(error => {\n reject(error)\n })\n })\n }\n\n async login(email: string, password: string): Promise {\n let fbLogin = await signInWithEmailAndPassword(getAuth(), email, password)\n this._apiAccess = new ApiAccess(await fbLogin.user.getIdToken(false), null, () => {})\n }\n\n public async waitForUser(token?: string): Promise {\n if (token) {\n await signInWithCustomToken(getAuth(), token)\n }\n let fbUserPromise = new Promise((resolve, reject) => {\n let unregister = onAuthStateChanged(\n getAuth(),\n (user: FirebaseUser) => {\n if (user) {\n this.firebaseUser = user\n setDebugInfo(\"firebaseUser\", user)\n resolve(user)\n } else {\n resolve(null)\n }\n unregister()\n },\n error => {\n reject(error)\n }\n )\n })\n\n let fbUser = await fbUserPromise\n if (fbUser) {\n this._apiAccess = new ApiAccess(await fbUser.getIdToken(false), null, () => {})\n let userDTO = await this.storageService.getUserInfo()\n let user = userFromDTO(userDTO)\n user.id = fbUser.uid\n user.email = fbUser.email\n user.name = user.name || fbUser.displayName\n this.user = user\n }\n }\n\n removeAuth(callback: () => void) {\n signOut(getAuth()).finally(callback)\n }\n\n getUser(): User {\n if (!this.user) {\n throw new Error(\"User is null. Should you call services.userService.hasUser()?\")\n }\n return this.user\n }\n\n getUserEmailStatus(): UserEmailStatus {\n return {\n needsConfirmation: true,\n isConfirmed: this.firebaseUser.emailVerified,\n }\n }\n\n async refreshToken(firebaseUser: FirebaseUser, forceRefresh: boolean) {\n const tokenInfo = await firebaseUser.getIdTokenResult(forceRefresh)\n const expirationMs = new Date(tokenInfo.expirationTime).getTime() - Date.now()\n console.log(\n `Firebase token (force=${forceRefresh}) which expire at ${tokenInfo.expirationTime} in ${expirationMs}ms=(${tokenInfo.expirationTime})`\n )\n this._apiAccess = new ApiAccess(tokenInfo.token, null, () => {})\n setTimeout(() => this.refreshToken(firebaseUser, true), expirationMs / 2)\n }\n\n async createUser(signup: SignupRequest): Promise {\n let firebaseUser = await createUserWithEmailAndPassword(getAuth(), signup.email.trim(), signup.password.trim())\n\n await this.refreshToken(firebaseUser.user, false)\n this._apiAccess = new ApiAccess(await firebaseUser.user.getIdToken(false), null, () => {})\n\n let user: User = {\n suggestedCompanyName: undefined,\n id: firebaseUser.user.uid,\n name: firebaseUser.user.displayName,\n email: firebaseUser.user.email,\n emailOptout: false,\n forcePasswordChange: false,\n created: new Date().toISOString(),\n }\n await this.storageService.saveUserInfo(userToDTO(user))\n await this.trackSignup(signup.email, \"email\")\n }\n\n hasUser(): boolean {\n return !!this.user\n }\n\n sendPasswordReset(email?: string): Promise {\n return sendPasswordResetEmail(getAuth(), email ? email : this.getUser().email, { url: window.location.href })\n }\n\n async sendConfirmationEmail(): Promise {\n return sendEmailVerification(this.firebaseUser)\n }\n\n changePassword(newPassword: string, resetId?: string): Promise {\n return updatePassword(this.firebaseUser, newPassword)\n }\n\n async changeEmail(newEmail: string): Promise {\n await updateEmail(this.firebaseUser, newEmail)\n this.user.email = newEmail\n await this.storageService.saveUserInfo({ _email: newEmail })\n }\n\n async changeTelemetrySettings(newSettings: TelemetrySettings): Promise {\n throw new Error(\"Not Available\")\n }\n\n getLoginFeatures(): LoginFeatures {\n return { oauth: true, password: true, signupEnabled: true }\n }\n\n getSSOProvider(): string {\n return \"\"\n }\n\n getSSOAuthLink(): string {\n return \"\"\n }\n\n sendLoginLink(email: string): Promise {\n return sendSignInLinkToEmail(getAuth(), email, {\n url: document.location.protocol + \"//\" + document.location.host + \"/login-link/\" + btoa(email),\n handleCodeInApp: true,\n })\n }\n\n supportsLoginViaLink(): boolean {\n return true\n }\n\n isEmailLoginLink(href: string): boolean {\n return isSignInWithEmailLink(getAuth(), href)\n }\n\n loginWithLink(email: string, href: string): Promise {\n return signInWithEmailLink(getAuth(), email, href).then()\n }\n\n apiAccess(): ApiAccess {\n return this._apiAccess\n }\n\n refreshAuth(): Promise {\n return this.refreshToken(this.firebaseUser, true)\n }\n\n async getIdToken(): Promise {\n return await getIdToken(this.firebaseUser)\n }\n}\n","import { JSON_FORMAT } from \"./model\"\nimport axios, { AxiosRequestConfig, AxiosResponse } from \"axios\"\nimport * as uuid from \"uuid\"\nimport AnalyticsService from \"./analytics\"\nimport { BackendUserService } from \"./UserServiceBackend\"\nimport { concatenateURLs } from \"lib/commons/utils\"\nimport { assert } from \"utils/typeCheck\"\nimport { APIError, BackendApiClient, JWTBackendClient } from \"./BackendApiClient\"\nimport { HttpServerStorage, ServerStorage } from \"./ServerStorage\"\nimport { UserService } from \"./UserService\"\nimport { ApplicationConfiguration } from \"./ApplicationConfiguration\"\nimport { CurrentSubscription } from \"./billing\"\nimport { ISlackApiService, SlackApiService } from \"./slack\"\nimport { IOauthService, OauthService } from \"./oauth\"\nimport { Project, ProjectPermission, ProjectWithPermissions } from \"../../generated/conf-openapi\"\nimport { createProjectService, ProjectService } from \"./ProjectService\"\nimport { FirebaseUserService } from \"./UserServiceFirebase\"\nimport { UserSettingsService, UserSettingsLocalService, Settings } from \"./UserSettingsService\"\n\nexport interface IApplicationServices {\n init(): Promise\n\n userService: UserService\n activeProject: Project\n storageService: ServerStorage\n analyticsService: AnalyticsService\n backendApiClient: BackendApiClient\n features: FeatureSettings\n applicationConfiguration: ApplicationConfiguration\n slackApiSercice: ISlackApiService\n oauthService: IOauthService\n projectService: ProjectService\n\n showSelfHostedSignUp(): boolean\n}\n\nexport default class ApplicationServices implements IApplicationServices {\n private readonly _applicationConfiguration: ApplicationConfiguration\n private readonly _analyticsService: AnalyticsService\n private readonly _backendApiClient: BackendApiClient\n private readonly _storageService: ServerStorage\n private readonly _slackApiService: ISlackApiService\n private readonly _oauthService: IOauthService\n private readonly _projectService: ProjectService\n\n private _userService: UserService\n private _userSettingsService: UserSettingsService\n private _features: FeatureSettings\n\n public onboardingNotCompleteErrorMessage =\n \"Onboarding process hasn't been fully completed. Please, contact the support\"\n private _currentSubscription: CurrentSubscription\n\n constructor() {\n this._applicationConfiguration = new ApplicationConfiguration()\n this._analyticsService = new AnalyticsService(this._applicationConfiguration)\n this._backendApiClient = new JWTBackendClient(\n this._applicationConfiguration.backendApiBase,\n this._applicationConfiguration.backendApiProxyBase,\n () => this._userService.apiAccess(),\n this._analyticsService\n )\n this._storageService = new HttpServerStorage(this._backendApiClient)\n this._slackApiService = new SlackApiService(() => this._userService.apiAccess())\n this._oauthService = new OauthService(this._applicationConfiguration.oauthApiBase, this._backendApiClient)\n this._projectService = createProjectService(this._backendApiClient)\n }\n\n //load backend configuration and create user service depend on authorization type\n async init() {\n let configuration = await this.loadBackendConfiguration()\n this._features = configuration\n this._analyticsService.configure(this._features)\n\n if (configuration.authorization == \"redis\" || !this._applicationConfiguration.firebaseConfig) {\n this._userService = new BackendUserService(\n this._backendApiClient,\n this._storageService,\n configuration.smtp,\n this._features.ssoProvider,\n this._applicationConfiguration.backendApiBase\n )\n } else if (configuration.authorization == \"firebase\") {\n this._userService = new FirebaseUserService(\n this._applicationConfiguration.firebaseConfig,\n this._backendApiClient,\n this._storageService,\n this._analyticsService,\n this._features\n )\n } else {\n throw new Error(`Unknown backend configuration authorization type: ${configuration.authorization}`)\n }\n this._userSettingsService = new UserSettingsLocalService(this._userService)\n\n const appVersion = await this.getAppVersion()\n if (appVersion) {\n localStorage.setItem(\"app_version\", appVersion)\n }\n }\n\n get projectService(): ProjectService {\n return this._projectService\n }\n\n get userService(): UserService {\n return this._userService\n }\n\n get activeProject(): ProjectWithPermissions {\n return this._userSettingsService.get(Settings.ActiveProject) as ProjectWithPermissions\n }\n\n get currentProjectPermissions(): Set {\n return new Set(this.activeProject.permissions || [])\n }\n\n set activeProject(value: ProjectWithPermissions) {\n this._userSettingsService.set({ [Settings.ActiveProject]: value })\n }\n\n get storageService(): ServerStorage {\n return this._storageService\n }\n\n get analyticsService(): AnalyticsService {\n return this._analyticsService\n }\n\n get currentSubscription(): CurrentSubscription {\n return this._currentSubscription\n }\n\n set currentSubscription(value: CurrentSubscription) {\n this._currentSubscription = value\n }\n\n get backendApiClient(): BackendApiClient {\n return this._backendApiClient\n }\n\n get features(): FeatureSettings {\n return this._features\n }\n\n get slackApiSercice(): ISlackApiService {\n return this._slackApiService\n }\n\n get oauthService(): IOauthService {\n return this._oauthService\n }\n\n get userSettingsService(): UserSettingsService {\n return this._userSettingsService\n }\n\n static get(): ApplicationServices {\n return _get()\n }\n\n public async isAppVersionOutdated(): Promise {\n const appVersion = await this.getAppVersion()\n const currentVersion = localStorage.getItem(\"app_version\")\n return appVersion !== \"0\" && appVersion !== null && appVersion != currentVersion\n }\n\n private async getAppVersion(): Promise {\n const request: AxiosRequestConfig = {\n method: \"GET\",\n url: \"/app-version.json\",\n transformResponse: JSON_FORMAT,\n }\n try {\n const response = await axios(request)\n if (response?.status !== 200) {\n console.warn(`Can't get application version: ${response.statusText}`)\n return \"0\"\n } else {\n return response?.data\n }\n } catch (e) {\n console.warn(`Failed to get data from /app-version.json: ${e?.message || \"unknown error\"}`, e)\n return \"0\"\n }\n }\n\n private async loadBackendConfiguration(): Promise {\n let fullUrl = concatenateURLs(this._applicationConfiguration.backendApiBase, \"/v1/system/configuration\")\n let request: AxiosRequestConfig = {\n method: \"GET\",\n url: fullUrl,\n transformResponse: JSON_FORMAT,\n }\n\n let response = await axios(request)\n\n if (response.status == 200) {\n return mapBackendConfigResponseToAppFeatures(response.data)\n } else {\n throw new APIError(response, request)\n }\n }\n\n generateToken(): any {\n return {\n token: {\n auth: uuid.v4(),\n s2s_auth: uuid.v4(),\n origins: [],\n },\n }\n }\n\n get applicationConfiguration(): ApplicationConfiguration {\n return this._applicationConfiguration\n }\n\n public showSelfHostedSignUp(): boolean {\n return !this._features.users\n }\n\n public loadPluginScript(): Promise {\n if (!this._features?.pluginScript) {\n return\n }\n\n return new Promise((resolve, reject) => {\n const script = document.createElement(\"script\")\n script.src = this._features.pluginScript\n script.async = true\n script.onload = () => {\n resolve()\n }\n script.onerror = () => {\n reject()\n }\n document.body.appendChild(script)\n })\n }\n}\n\nfunction _get(): ApplicationServices {\n if (window[\"_en_instance\"] === undefined) {\n try {\n window[\"_en_instance\"] = new ApplicationServices()\n } catch (e) {\n console.error(\"Failed to initialize application services\", e)\n document.body.innerHTML = `
Fatal error '${e.message}': \\n${e.stack}
`\n if (window.stop) {\n window.stop()\n }\n throw e\n }\n }\n return window[\"_en_instance\"]\n}\n\nexport function mapBackendConfigResponseToAppFeatures(responseData: { [key: string]: unknown }): FeatureSettings {\n let environment: FeatureSettings[\"environment\"] = responseData.selfhosted ? \"custom\" : \"jitsu_cloud\"\n if (responseData.docker_hub_id === \"heroku\") {\n environment = \"heroku\"\n } else if (responseData.docker_hub_id === \"ksense\" || responseData.docker_hub_id === \"jitsucom\") {\n environment = \"docker\" as const\n }\n\n let ssoProvider = \"\"\n if (typeof responseData.sso_provider === \"string\") {\n ssoProvider = responseData.sso_provider\n }\n\n assert(\n responseData.authorization === \"redis\" || responseData.authorization === \"firebase\",\n `Assertion error in mapBackendConfigResponseToAppFeatures: authorization field can be either \"redis\" or \"firebase\", but received ${responseData.authorization}`\n )\n\n assert(\n typeof responseData.smtp === \"boolean\",\n `Assertion error in mapBackendConfigResponseToAppFeatures: smtp field must be a boolean, but received ${responseData.smtp}`\n )\n\n return {\n ...responseData,\n createDemoDatabase: !responseData.selfhosted,\n users: !responseData.selfhosted || !!responseData.users,\n enableCustomDomains: !responseData.selfhosted,\n anonymizeUsers: !!responseData.selfhosted,\n appName: responseData.selfhosted ? \"selfhosted\" : \"jitsu_cloud\",\n chatSupportType: responseData.selfhosted ? \"slack\" : \"chat\",\n billingEnabled: responseData.authorization === \"firebase\" && !!process.env.BILLING_API_BASE_URL,\n authorization: responseData.authorization,\n ssoProvider,\n smtp: responseData.smtp,\n environment: environment,\n onlyAdminCanChangeUserEmail: !!responseData.only_admin_can_change_user_email,\n pluginScript: responseData.plugin_script as string,\n serverPublicUrl: responseData.server_public_url as string,\n }\n}\n\nexport type FeatureSettings = {\n /**\n * Application type (name)\n */\n appName: \"jitsu_cloud\" | \"selfhosted\"\n\n /**\n * Authorization type\n */\n authorization: \"redis\" | \"sso\" | \"firebase\"\n\n /**\n * SSO provider used\n */\n ssoProvider: string\n\n /**\n * If is there any users in backend DB (no users means we need to run a setup flow)\n */\n users: boolean\n /**\n * If SMTP configured on a server and reset password links should work\n */\n smtp: boolean\n /**\n * If demo database should be created\n */\n createDemoDatabase: boolean\n\n /**\n * If custom domains should be enabled\n */\n enableCustomDomains: boolean\n\n /**\n * If statistics we send to Jitsu should be anonymous\n */\n anonymizeUsers: boolean\n\n /**\n * Jitsu Domain\n */\n serverPublicUrl?: string\n\n /**\n * Slack - once user clicks on icon, it should be directed to slack\n *\n */\n chatSupportType: \"slack\" | \"chat\"\n\n /**\n * If billing is enabled\n */\n billingEnabled: boolean\n\n /**\n * Environment in which Jitsu runs\n */\n environment: \"heroku\" | \"docker\" | \"jitsu_cloud\" | \"custom\"\n\n /**\n * If only admin can change user email. For example in self-hosted instances admin token is required for this method\n */\n onlyAdminCanChangeUserEmail?: boolean\n\n /**\n * Plugin script url\n */\n pluginScript: string\n}\n","import { User } from \"../../generated/conf-openapi\"\n\n/**\n * Structure of /database API response\n */\nexport type PgDatabaseCredentials = {\n User: string\n Password: string\n Host: string\n Port: string\n Database: string\n}\n\nexport interface Transformer {\n (data: any, headers?: any): T\n}\n\nexport const JSON_FORMAT: Transformer = undefined\nexport const AS_IS_FORMAT: Transformer = response => (response ? response.toString() : null)\n\n/**\n * User information that was retried from auth method. Might contain\n * some information that will be usefull for autofill during on-boarding process\n */\nexport type SuggestedUserInfo = {\n //mandatory: user email (lower-case)\n email: string\n //user name (Firstname Lastname)\n name?: string\n //Company name\n companyName?: string\n}\n\n/**\n * User internal representation. This class is here for backward compatibility\n */\nexport type UserDTO = {\n $type: \"User\"\n _created: string\n _uid: string\n _name: string\n _email: string\n _emailOptout: boolean\n _forcePasswordChange: boolean\n _lastUpdated: string\n _onboarded: boolean\n _suggestedInfo: {\n companyName?: string\n email?: string\n name?: string\n }\n _project?: {\n $type: \"Project\"\n _id: string\n _name: string | null\n _requireSetup?: boolean\n }\n}\n\nexport function userToDTO(user: User): UserDTO {\n return {\n _uid: user.id,\n _name: user.name,\n _emailOptout: user.emailOptout || false,\n _forcePasswordChange: user.forcePasswordChange || false,\n _lastUpdated: new Date().toISOString(),\n _suggestedInfo: {\n companyName: user.suggestedCompanyName || undefined,\n email: user.email || undefined,\n name: user.name || undefined,\n },\n $type: \"User\",\n _created: user.created || new Date().toISOString(),\n _email: user.email,\n _onboarded: true,\n }\n}\n\nexport function userFromDTO(dto: UserDTO): User {\n return {\n created: dto._created || new Date().toISOString(),\n email: dto._email || dto._suggestedInfo?.email,\n emailOptout: dto._emailOptout || false,\n forcePasswordChange: dto._forcePasswordChange || false,\n name: dto._name || dto._suggestedInfo?.name,\n id: dto._uid,\n suggestedCompanyName: dto._suggestedInfo?.companyName,\n }\n}\n\nexport type Domain = {\n name: string\n status: \"pending\" | \"verified\"\n comment?: string\n}\n\nexport class ApiAccess {\n private _accessToken: string\n private _refreshToken: string\n private _localStorageTokensUpdateCallback: (accessToken: string, refreshToken: string) => void\n\n constructor(\n accessToken: string,\n refreshToken: string,\n localStorageTokensUpdateCallback: (accessToken: string, refreshToken: string) => void\n ) {\n this._accessToken = accessToken\n this._refreshToken = refreshToken\n this._localStorageTokensUpdateCallback = localStorageTokensUpdateCallback\n }\n\n get accessToken(): string {\n return this._accessToken\n }\n\n get refreshToken(): string {\n return this._refreshToken\n }\n\n supportRefreshToken(): boolean {\n return this._refreshToken != null\n }\n\n updateTokens(accessToken: string, refreshToken: string) {\n this._accessToken = accessToken\n this._refreshToken = refreshToken\n this._localStorageTokensUpdateCallback(accessToken, refreshToken)\n }\n}\n"],"sourceRoot":""}