UNPKG

@hhgtech/hhg-components

Version:
346 lines (342 loc) • 16.3 kB
import { a as __awaiter } from './tslib.es6-00ab44b2.js'; import { c as cookie } from './index-dac15b93.js'; import { getCookie } from './miscCookieHelper.js'; import slugify from 'slugify'; import { isProduction } from './constantsIsProduction.js'; import formatString from 'string-format'; import React__default, { createContext, useState, useEffect } from 'react'; import { PATHS } from './togetherApiPaths.js'; import { B as BEARER_TOKEN_COOKIE, b as BEARER_ADMIN_TOKEN_COOKIE, L as LOCALISED_SLUGS } from './constants-367949ba.js'; const DefaultComponentGlobalContextData = { locale: 'vi-VN', env: { isMarryBaby: false, togetherBasePath: '/community', }, router: { basePath: '', asPath: '/', }, }; const TogetherComponentGlobalContext = createContext({ data: DefaultComponentGlobalContextData, action: { pushNotifications: (s) => s, sanitizeFunction: (s) => s, }, formatMessage: () => null, }); let GlobalData = DefaultComponentGlobalContextData; const TogetherComponentGlobalContextProvider = ({ locale = 'vi-VN', children, userInfo, router, env = { isMarryBaby: false, togetherBasePath: '/community', }, sanitizeFunction = (s) => s, pushNotifications = () => false, formatMessage, }) => { const [togetherUserId, setTogetherUserId] = useState(); GlobalData = { userInfo, locale, togetherUserId, router, env, }; useEffect(() => { if (userInfo === null || userInfo === void 0 ? void 0 : userInfo.id) { callApiWithAuth(getApiPath(PATHS.PROFILE, { _locale: locale, }), 'GET').then((res) => { var _a; setTogetherUserId((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.id); }); } }, [userInfo === null || userInfo === void 0 ? void 0 : userInfo.id]); return (React__default.createElement(TogetherComponentGlobalContext.Provider, { value: { data: { userInfo, locale, togetherUserId, router, env, }, action: { pushNotifications, sanitizeFunction, }, formatMessage, } }, children)); }; // import { DISCOVER_PATHS, PATHS } from './paths' // let _apolloClient:ApolloClient<NormalizedCacheObject> const domainLocales = { 'vi-VN': 'hellobacsi.com', 'id-ID': 'hellosehat.com', 'ms-MY': 'hellodoktor.com', 'km-KH': 'hellokrupet.com', 'en-PH': 'hellodoctor.com.ph', 'th-TH': 'hellokhunmor.com', 'my-MM': 'hellosayarwon.com', 'zh-TW': 'helloyishi.com.tw', 'hi-IN': 'helloswasthya.com', }; const domainLocalesMarryBaby = { 'vi-VN': 'marrybaby.vn', }; const locale = (process.env.NEXT_PUBLIC_DEPLOY_LOCALE || 'vi-VN'); const getWebsiteUrlApi = (locale) => { const { env: { isMarryBaby }, } = GlobalData; return `https://${isMarryBaby ? domainLocalesMarryBaby[locale] : domainLocales[locale]}`; }; const cleanFormatString = (url) => { const qIndex = url.indexOf('?'); if (qIndex >= 0) { return (url.slice(0, qIndex + 1) + url .slice(qIndex + 1) .replace(/[^=&]+=(&|$)/g, '') .replace(/&$/, '')); } return url; }; const getCurrentBaseUrl = (locale) => { const { env: { isMarryBaby }, } = GlobalData; if (typeof window !== 'undefined') return window.location.origin; const isStaging = process.env.NEXT_PUBLIC_DEPLOY_ENV === 'staging'; const isDev = process.env.NEXT_PUBLIC_DEPLOY_ENV === 'development'; return isDev ? 'http://localhost:3000' : `https://${isStaging ? isMarryBaby ? 'fe.' : 'discover.' : isMarryBaby ? 'www.' : ''}${domainLocales[locale]}`; }; const getCurrentHref = (locale, basePath, asPath) => { if (typeof window !== 'undefined') return window.location.href; return `${getCurrentBaseUrl(locale)}${basePath}${asPath}`; }; const getApiPath = (path, params, query, baseUrl) => { let queryString = ''; if (query) { queryString = Object.keys(query) .map((key) => key + '=' + query[key]) .join('&'); } const { togetherBaseApiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; let formattedPath = formatString(path, Object.assign(Object.assign({}, ((params === null || params === void 0 ? void 0 : params._locale) ? { website_url: getWebsiteUrlApi(String(params._locale)), } : {})), params)); formattedPath += `${formattedPath.includes('?') ? '&' : '?'}${queryString}`; const baseApiUrl = baseUrl ? baseUrl : togetherBaseApiUrl; return baseApiUrl + 'api/v1/' + cleanFormatString(formattedPath); }; const getDiscoverApiPath = (path, params, useProOnDev) => { const { discoverBaseApiUrl = '', discoverBaseProdApiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; const basePath = !isProduction && useProOnDev ? discoverBaseProdApiUrl : discoverBaseApiUrl; return (basePath + 'wp-json/api/' + cleanFormatString(formatString(path, Object.assign({}, params)))); }; const getMarryBabyApiPath = (path, params, useProOnDev) => { const { marryBabyApiUrl = '', marryBabyProdApiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; const basePath = useProOnDev && !isProduction ? marryBabyProdApiUrl : marryBabyApiUrl; return (basePath + 'wp-json/api/' + cleanFormatString(formatString(path, Object.assign({}, params)))); }; const getCarePath = (path, params) => { const { careBaseApiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; return ((careBaseApiUrl || 'https://service-health-care.hellohealthgroup.com/') + cleanFormatString(formatString(path, Object.assign({}, params)))); }; const getPremiumApiPath = (path, params) => { const { premiumBaseApiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; return ((premiumBaseApiUrl || 'https://premium-content-stag.hellohealthgroup.com/') + cleanFormatString(formatString(path, Object.assign({}, params)))); }; const getSsoApiPath = (path, params) => { const { publicSSO = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; return ((publicSSO || 'https://staging-id.hellobacsi.com/') + 'api/' + cleanFormatString(formatString(path, Object.assign({}, params)))); }; const getChatbotAiApiPath = (path, params) => { const { chatbotAiUrl = '' } = (GlobalData === null || GlobalData === void 0 ? void 0 : GlobalData.env) || {}; return ((chatbotAiUrl || 'https://chatbot-staging-v2.hellohealthgroup.com/') + cleanFormatString(formatString(path, Object.assign(Object.assign({}, ((params === null || params === void 0 ? void 0 : params._locale) ? { website_url: getWebsiteUrlApi(String(params._locale)), } : {})), params)))); }; const fixedEncodeURI = (str) => { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }; const convertApiOptionsToRequestInit = (opts) => { if (opts === null || opts === void 0 ? void 0 : opts.data) { if (opts.data instanceof FormData) { opts.body = opts.data; } else if (typeof opts.data === 'object') { opts.body = JSON.stringify(opts.data); } delete opts.data; } return opts; }; const callApi = (url, method, options, skipEncodeURI = false) => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c; try { const res = yield fetch(skipEncodeURI ? url : fixedEncodeURI(url), Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({}, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json()); if (res) return res; } catch (err) { console.log(err); console.log({ url, status: (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.status, statusText: (_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.statusText, }); // Sentry.captureException(err) return ((_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data) || null; } return null; }); const callApiWithOptionalAuth = (urlData, method = 'GET', options, reqCookie) => __awaiter(void 0, void 0, void 0, function* () { var _d, _e, _f, _g, _h, _j; try { const url = typeof urlData === 'string' ? urlData : urlData.url; const backupUrl = typeof urlData === 'string' ? urlData : urlData.backupUrl; const parsedCookie = cookie.parse(reqCookie || ''); const token = parsedCookie[BEARER_TOKEN_COOKIE]; const cookie$1 = token || getCookie(BEARER_TOKEN_COOKIE); if (cookie$1 && cookie$1.length) { try { const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie$1 }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json()); if ((_d = res === null || res === void 0 ? void 0 : res.messages) === null || _d === void 0 ? void 0 : _d.find((m) => (m === null || m === void 0 ? void 0 : m.toLowerCase()) === 'Unauthenticated')) { return callApi(backupUrl || url, method, options); } if (res) return res; } catch (err) { console.log({ status: (_e = err === null || err === void 0 ? void 0 : err.response) === null || _e === void 0 ? void 0 : _e.status, statusText: (_f = err === null || err === void 0 ? void 0 : err.response) === null || _f === void 0 ? void 0 : _f.statusText, }); // Fallback noauth call return callApi(backupUrl || url, method, options); } } else { return callApi(backupUrl || url, method, options); } } catch (err) { console.log({ status: (_g = err === null || err === void 0 ? void 0 : err.response) === null || _g === void 0 ? void 0 : _g.status, statusText: (_h = err === null || err === void 0 ? void 0 : err.response) === null || _h === void 0 ? void 0 : _h.statusText, }); // Sentry.captureException(err) return ((_j = err === null || err === void 0 ? void 0 : err.response) === null || _j === void 0 ? void 0 : _j.data) || null; } return null; }); const callApiWithAuth = (url, method, options, reqCookie) => __awaiter(void 0, void 0, void 0, function* () { try { const parsedCookie = cookie.parse(reqCookie || ''); const token = parsedCookie[BEARER_TOKEN_COOKIE]; const cookie$1 = token || getCookie(BEARER_TOKEN_COOKIE); if (cookie$1 && cookie$1.length) { const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie$1 }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json()); if (res) return res; } } catch (err) { // Sentry.captureException(err) return null; } return null; }); const callApiWithAdminAuth = (url, method, options, reqCookie) => __awaiter(void 0, void 0, void 0, function* () { try { const parsedCookie = cookie.parse(reqCookie || ''); const token = parsedCookie[BEARER_ADMIN_TOKEN_COOKIE]; const cookie$1 = token || getCookie(BEARER_ADMIN_TOKEN_COOKIE); if (cookie$1 && cookie$1.length) { const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie$1 }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json()); if (res) return res; } } catch (err) { // Sentry.captureException(err) return null; } return null; }); function updateQueryStringParameter(uri, key, value) { const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'); const separator = uri.indexOf('?') !== -1 ? '&' : '?'; if (uri.match(re)) { return uri.replace(re, '$1' + key + '=' + value + '$2'); } else { return uri + separator + key + '=' + value; } } const getUrlToSSOWithReturnUrl = (url, params) => { const { publicSSO } = GlobalData.env; const originalRedirectUrl = url || window.location.href; // const redirectUrl = new URL(originalRedirectUrl) if (params) { Object.keys(params).map((k) => { updateQueryStringParameter(originalRedirectUrl, k, params[k]); }); } updateQueryStringParameter(originalRedirectUrl, 'source', 'communities'); return publicSSO ? `${publicSSO}?returnUrl=${encodeURIComponent(originalRedirectUrl.toString())}` : originalRedirectUrl; }; const getUrlToSignUp = (url, params, togetherBasePath = '/community') => { const currentLocation = url || (typeof window !== 'undefined' ? window.location.href : '/'); let origin = typeof window !== 'undefined' ? window.location.origin : ''; if (!origin) { if (url && (url.startsWith('http://') || url.startsWith('https://'))) { origin = url.split('/').slice(0, 3).join('/'); } } const onBoardingUrl = `${origin}${togetherBasePath}/on-boarding?return=${encodeURIComponent(currentLocation)}`; return getUrlToSSOWithReturnUrl(onBoardingUrl, params); }; const slugifiedNameWithId = (name, id, slug, _locale) => { if (slug && id) { return `${slug}-${id}`; } return `${slugify(name || '', { lower: true, locale: _locale || locale, })}-${id}`; }; const getCareDoctorUrl = ({ name, id, locale, }) => { var _a; return `/care/${(_a = LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.DOCTOR}/${slugifiedNameWithId(name, id)}`; }; const getCareHospitalUrl = ({ name, id, slug, locale, }) => { var _a; return `/care/${(_a = LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.HOSPITAL}/${slugifiedNameWithId(name, id, slug)}`; }; const getCareHospitalUrlAmp = ({ slug, id, locale, }) => { var _a; return `/care/${(_a = LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.HOSPITAL}/${slug}-${id}`; }; export { DefaultComponentGlobalContextData as D, GlobalData as G, TogetherComponentGlobalContext as T, TogetherComponentGlobalContextProvider as a, getCarePath as b, callApi as c, domainLocalesMarryBaby as d, callApiWithAuth as e, getApiPath as f, getDiscoverApiPath as g, getPremiumApiPath as h, getWebsiteUrlApi as i, getSsoApiPath as j, getUrlToSignUp as k, getCurrentBaseUrl as l, domainLocales as m, getCareHospitalUrl as n, getCareDoctorUrl as o, getCurrentHref as p, callApiWithAdminAuth as q, getChatbotAiApiPath as r, getMarryBabyApiPath as s, callApiWithOptionalAuth as t, locale as u, updateQueryStringParameter as v, getUrlToSSOWithReturnUrl as w, slugifiedNameWithId as x, getCareHospitalUrlAmp as y };