From 5b88e53992a98a1951466d1aa5f4c01446e5965a Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Fri, 10 May 2024 12:22:24 -0700 Subject: [PATCH 01/12] Consolidate /mobify code references --- .../src/ssr/server/build-dev-server.js | 6 ++--- .../src/ssr/universal/utils.js | 4 ++-- .../src/ssr/server/build-remote-server.js | 10 ++++---- .../src/utils/ssr-server.test.js | 8 +++---- .../src/utils/ssr-server/utils.js | 11 ++++----- .../pwa-kit-runtime/src/utils/ssr-shared.js | 24 +++++++++++++++++-- .../app/components/_app-config/index.jsx | 3 ++- .../app/hooks/use-active-data.js | 7 ++---- 8 files changed, 45 insertions(+), 28 deletions(-) diff --git a/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js b/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js index 5d23f8f072..d017f7d175 100644 --- a/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js +++ b/packages/pwa-kit-dev/src/ssr/server/build-dev-server.js @@ -18,7 +18,7 @@ import webpackHotMiddleware from 'webpack-hot-middleware' import open from 'open' import requireFromString from 'require-from-string' import {RemoteServerFactory} from '@salesforce/pwa-kit-runtime/ssr/server/build-remote-server' -import {proxyConfigs} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' +import {proxyConfigs, getBundlePathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' import { SERVER, CLIENT, @@ -166,7 +166,7 @@ export const DevServerMixin = { app.__hotServerMiddleware = webpackHotServerMiddleware(app.__compiler) } - app.use('/mobify/bundle/development', app.__devMiddleware) + app.use(`${getBundlePathBase()}/development`, app.__devMiddleware) app.__hmrMiddleware = (_, res) => res.status(501).send('Hot Module Reloading is disabled.') const clientCompiler = app.__compiler.compilers.find((compiler) => compiler.name === CLIENT) @@ -209,7 +209,7 @@ export const DevServerMixin = { // Proxy bundle asset requests to the local // build directory. app.use( - '/mobify/bundle/development', + `${getBundlePathBase}/development`, express.static(path.resolve(process.cwd(), 'src'), { dotFiles: 'deny', setHeaders: setLocalAssetHeaders, diff --git a/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js b/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js index 439094a35f..014f84f91d 100644 --- a/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js +++ b/packages/pwa-kit-react-sdk/src/ssr/universal/utils.js @@ -7,7 +7,7 @@ /** * @module progressive-web-sdk/ssr/universal/utils */ -import {proxyConfigs} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' +import {proxyConfigs, getBundlePathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' const onClient = typeof window !== 'undefined' @@ -22,7 +22,7 @@ export const getAssetUrl = (path) => { /* istanbul ignore next */ const publicPath = onClient ? `${window.Progressive.buildOrigin}` - : `/mobify/bundle/${process.env.BUNDLE_ID || 'development'}/` + : `${getBundlePathBase()}/${process.env.BUNDLE_ID || 'development'}/` return path ? `${publicPath}${path}` : publicPath } diff --git a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js index a4218034d4..e2c87b4221 100644 --- a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js +++ b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js @@ -39,7 +39,7 @@ import fs from 'fs' import {RESOLVED_PROMISE} from './express' import http from 'http' import https from 'https' -import {proxyConfigs, updatePackageMobify} from '../../utils/ssr-shared' +import {proxyConfigs, updatePackageMobify, startsWithMobify, getProxyPathBase, getHealtCheckPathBase} from '../../utils/ssr-shared' import {applyProxyRequestHeaders} from '../../utils/ssr-server/configure-proxy' import awsServerlessExpress from 'aws-serverless-express' import expressLogging from 'morgan' @@ -432,7 +432,7 @@ export const RemoteServerFactory = { const processIncomingRequest = (req, res) => { const options = req.app.options // If the request is for a proxy or bundle path, do nothing - if (req.originalUrl.startsWith('/mobify/')) { + if (startsWithMobify(req.originalUrl)) { return } @@ -569,7 +569,7 @@ export const RemoteServerFactory = { // different types of the 'req' object, and will // always contain the original full path. /* istanbul ignore else */ - if (!req.originalUrl.startsWith('/mobify/')) { + if (!startsWithMobify(req.originalUrl)) { req.app.sendMetric( 'RequestTime', Date.now() - locals.requestStart, @@ -615,7 +615,7 @@ export const RemoteServerFactory = { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _setupProxying(app, options) { - app.all('/mobify/proxy/*', (_, res) => { + app.all(`${getProxyPathBase()}/*`, (_, res) => { return res.status(501).json({ message: 'Environment proxies are not set: https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/proxying-requests.html' @@ -702,7 +702,7 @@ export const RemoteServerFactory = { * @private */ _setupHealthcheck(app) { - app.get('/mobify/ping', (_, res) => + app.get(`${getHealtCheckPathBase()}`, (_, res) => res.set('cache-control', NO_CACHE).sendStatus(200).end() ) }, diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server.test.js b/packages/pwa-kit-runtime/src/utils/ssr-server.test.js index 31eb70492b..9ca52a5f42 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server.test.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server.test.js @@ -30,6 +30,7 @@ import { } from './ssr-server' import { + getProxyPathBase, getPackageMobify, getSSRParameters, proxyConfigs, @@ -43,8 +44,7 @@ import { CONTENT_ENCODING, CONTENT_TYPE, X_ORIGINAL_CONTENT_TYPE, - APPLICATION_OCTET_STREAM, - PROXY_PATH_PREFIX + APPLICATION_OCTET_STREAM } from '../ssr/server/constants' const baseMobify = { @@ -117,11 +117,11 @@ describe('utils/ssr-server tests', () => { updatePackageMobify(baseMobify) - expect(getFullRequestURL(`${PROXY_PATH_PREFIX}/base/somepath`)).toBe( + expect(getFullRequestURL(`${getProxyPathBase()}/base/somepath`)).toBe( 'https://www.merlinspotions.com/somepath' ) - expect(getFullRequestURL(`${PROXY_PATH_PREFIX}/base2/somepath`)).toBe( + expect(getFullRequestURL(`${getProxyPathBase()}/base2/somepath`)).toBe( 'https://api.merlinspotions.com/somepath' ) }) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js b/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js index 449649d8e6..7eb72fa9c2 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server/utils.js @@ -11,8 +11,7 @@ // ../ssr-server.js because it would create circular dependencies. import crypto from 'crypto' -import {PROXY_PATH_PREFIX} from '../../ssr/server/constants' -import {proxyConfigs} from '../ssr-shared' +import {getProxyPathBase, getBundlePathBase, proxyConfigs} from '../ssr-shared' // TODO: Clean this up or provide a way to toggle export const verboseProxyLogging = false @@ -21,7 +20,7 @@ export const isRemote = () => Object.prototype.hasOwnProperty.call(process.env, 'AWS_LAMBDA_FUNCTION_NAME') export const getBundleBaseUrl = () => { - return `/mobify/bundle/${isRemote() ? process.env.BUNDLE_ID : 'development'}/` + return `${getBundlePathBase()}/${isRemote() ? process.env.BUNDLE_ID : 'development'}/` } let QUIET = false @@ -82,16 +81,16 @@ export const getHashForString = (text) => { export const getFullRequestURL = (url) => { // If it starts with a protocol (e.g. http(s)://, file://), then it's already a full URL if (/^[a-zA-Z]+:\/\//.test(url)) return url - const proxy = proxyConfigs.find(({path}) => url.startsWith(`${PROXY_PATH_PREFIX}/${path}/`)) + const proxy = proxyConfigs.find(({path}) => url.startsWith(`${getProxyPathBase()}/${path}/`)) if (proxy) { return url.replace( - `${PROXY_PATH_PREFIX}/${proxy.path}`, + `${getProxyPathBase()}/${proxy.path}`, `${proxy.protocol}://${proxy.host}` ) } throw new Error( - `Unable to fetch ${url}, relative paths must begin with ${PROXY_PATH_PREFIX} followed by a configured proxy path.` + `Unable to fetch ${url}, relative paths must begin with ${getProxyPathBase()} followed by a configured proxy path.` ) } diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 4368a3aea7..60c697380d 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -69,6 +69,26 @@ export let ssrFiles = [] */ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ +export const startsWithMobify = (url) => { + return url.startsWith('/mobify/') +} + +export const getProxyPathBase = () => { + return '/mobify/proxy' +} + +export const getBundlePathBase = () => { + return '/mobify/bundle' +} + +export const getCachingPathBase = () => { + return '/mobify/caching' +} + +export const getHealtCheckPathBase = () => { + return '/mobify/ping' +} + /** * Updates the value of _packageMobify and dependent values. * @@ -166,8 +186,8 @@ export const updatePackageMobify = (newValue) => { } // Generate paths - config.proxyPath = `/mobify/proxy/${config.path}` - config.cachingPath = `/mobify/caching/${config.path}` + config.proxyPath = `${getProxyPathBase()}/${config.path}` + config.cachingPath = `${getCachingPathBase()}/${config.path}` proxyConfigs.push(config) } diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index bbdbad4082..2ecf0700d3 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -27,6 +27,7 @@ import { resolveLocaleFromUrl } from '@salesforce/retail-react-app/app/utils/site-utils' import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config' +import {getProxyPathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' import {createUrlTemplate} from '@salesforce/retail-react-app/app/utils/url' import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' @@ -67,7 +68,7 @@ const AppConfig = ({children, locals = {}}) => { // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. // enablePWAKitPrivateClient={true} - OCAPISessionsURL={`${appOrigin}/mobify/proxy/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} + OCAPISessionsURL={`${appOrigin}${getProxyPathBase()}/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} > {children} diff --git a/packages/template-retail-react-app/app/hooks/use-active-data.js b/packages/template-retail-react-app/app/hooks/use-active-data.js index 6ff115e699..22b4d7e24a 100644 --- a/packages/template-retail-react-app/app/hooks/use-active-data.js +++ b/packages/template-retail-react-app/app/hooks/use-active-data.js @@ -6,6 +6,7 @@ */ /*global dw*/ import {ACTIVE_DATA_ENABLED} from '@salesforce/retail-react-app/app/constants' +import {getProxyPathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' const useActiveData = () => { // Returns true when the feature flag is enabled and the tracking scripts have been executed @@ -68,11 +69,7 @@ const useActiveData = () => { if (!canTrack()) return try { var activeDataUrl = - '/mobify/proxy/ocapi/on/demandware.store/Sites-' + - siteId + - '-Site/' + - localeId + - '/__Analytics-Start' + `${getProxyPathBase()}/ocapi/on/demandware.store/Sites-${siteId}-Site/${localeId}/__Analytics-Start` var dwAnalytics = dw.__dwAnalytics.getTracker(activeDataUrl) if (typeof dw.ac == 'undefined') { dwAnalytics.trackPageView() From 5e13872b2dda80e09b2bf6ff9152704ea84cc1f3 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Fri, 10 May 2024 14:47:12 -0700 Subject: [PATCH 02/12] /mobify util for commerce-sdk-react --- packages/commerce-sdk-react/src/auth/index.ts | 6 +++--- .../src/components/StorefrontPreview/utils.ts | 4 ++-- packages/commerce-sdk-react/src/utils.ts | 12 ++++++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/commerce-sdk-react/src/auth/index.ts b/packages/commerce-sdk-react/src/auth/index.ts index d07ba854df..0d31e5941e 100644 --- a/packages/commerce-sdk-react/src/auth/index.ts +++ b/packages/commerce-sdk-react/src/auth/index.ts @@ -15,7 +15,7 @@ import {jwtDecode, JwtPayload} from 'jwt-decode' import {ApiClientConfigParams, Prettify, RemoveStringIndex} from '../hooks/types' import {BaseStorage, LocalStorage, CookieStorage, MemoryStorage, StorageType} from './storage' import {CustomerType} from '../hooks/useCustomerType' -import {getParentOrigin, isOriginTrusted, onClient} from '../utils' +import {getParentOrigin, isOriginTrusted, onClient, getProxyPath, getSLASPath} from '../utils' import { SLAS_SECRET_WARNING_MSG, SLAS_SECRET_PLACEHOLDER, @@ -175,8 +175,8 @@ class Auth { constructor(config: AuthConfig) { // Special endpoint for injecting SLAS private client secret - const baseUrl = config.proxy.split(`/mobify/proxy/api`)[0] - const privateClientEndpoint = `${baseUrl}/mobify/slas/private` + const baseUrl = config.proxy.split(`${getProxyPath()}`)[0] + const privateClientEndpoint = `${baseUrl}${getSLASPath()}` this.client = new ShopperLogin({ proxy: config.enablePWAKitPrivateClient ? privateClientEndpoint : config.proxy, diff --git a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts index dab7fecd30..f1470e14ce 100644 --- a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts +++ b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts @@ -6,7 +6,7 @@ */ import {ApiClients} from '../../hooks/types' -import {DEVELOPMENT_ORIGIN, getParentOrigin, isOriginTrusted} from '../../utils' +import {DEVELOPMENT_ORIGIN, getParentOrigin, isOriginTrusted, getDevelopBundlePath} from '../../utils' /** Detects whether the storefront is running in an iframe as part of Storefront Preview. * @private @@ -22,7 +22,7 @@ export const detectStorefrontPreview = () => { export const getClientScript = () => { const parentOrigin = getParentOrigin() ?? 'https://runtime.commercecloud.com' return parentOrigin === DEVELOPMENT_ORIGIN - ? `${parentOrigin}/mobify/bundle/development/static/storefront-preview.js` + ? `${parentOrigin}${getDevelopBundlePath()}/static/storefront-preview.js` : `${parentOrigin}/cc/b2c/preview/preview.client.js` } diff --git a/packages/commerce-sdk-react/src/utils.ts b/packages/commerce-sdk-react/src/utils.ts index 33e56ebb39..23e32e3212 100644 --- a/packages/commerce-sdk-react/src/utils.ts +++ b/packages/commerce-sdk-react/src/utils.ts @@ -47,6 +47,18 @@ export const isOriginTrusted = (origin: string | undefined) => { ) } +export const getProxyPath = () => { + return '/mobify/proxy/api' +} + +export const getDevelopBundlePath = () => { + return '/mobify/bundle/development' +} + +export const getSLASPath = () => { + return '/mobify/slas/private' +} + /** * Gets the value to use for the `sameSite` cookie attribute. * @returns `undefined` if running on the server, `"none"` if running as an iframe on a trusted site From a092f0b40237eb75dbb6d9427bb0393233dd89a2 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Fri, 10 May 2024 15:26:10 -0700 Subject: [PATCH 03/12] Private client proxy path --- .../src/ssr/server/build-remote-server.js | 15 +++++++-------- packages/pwa-kit-runtime/src/utils/ssr-shared.js | 4 ++++ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js index e2c87b4221..0ef0cbb13c 100644 --- a/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js +++ b/packages/pwa-kit-runtime/src/ssr/server/build-remote-server.js @@ -11,8 +11,7 @@ import { X_MOBIFY_QUERYSTRING, SET_COOKIE, CACHE_CONTROL, - NO_CACHE, - SLAS_CUSTOM_PROXY_PATH + NO_CACHE } from './constants' import { catchAndLog, @@ -39,7 +38,7 @@ import fs from 'fs' import {RESOLVED_PROMISE} from './express' import http from 'http' import https from 'https' -import {proxyConfigs, updatePackageMobify, startsWithMobify, getProxyPathBase, getHealtCheckPathBase} from '../../utils/ssr-shared' +import {proxyConfigs, updatePackageMobify, startsWithMobify, getProxyPathBase, getHealtCheckPathBase, getSLASPrivateProxyPath} from '../../utils/ssr-shared' import {applyProxyRequestHeaders} from '../../utils/ssr-server/configure-proxy' import awsServerlessExpress from 'aws-serverless-express' import expressLogging from 'morgan' @@ -627,7 +626,7 @@ export const RemoteServerFactory = { * @private */ _handleMissingSlasPrivateEnvVar(app) { - app.use(SLAS_CUSTOM_PROXY_PATH, (_, res) => { + app.use(getSLASPrivateProxyPath(), (_, res) => { return res.status(501).json({ message: 'Environment variable PWA_KIT_SLAS_CLIENT_SECRET not set: Please set this environment variable to proceed.' @@ -642,7 +641,7 @@ export const RemoteServerFactory = { if (!options.useSLASPrivateClient) { return } - localDevLog(`Proxying ${SLAS_CUSTOM_PROXY_PATH} to ${options.slasTarget}`) + localDevLog(`Proxying ${getSLASPrivateProxyPath()} to ${options.slasTarget}`) const clientId = options.mobify?.app?.commerceAPI?.parameters?.clientId const clientSecret = process.env.PWA_KIT_SLAS_CLIENT_SECRET @@ -654,16 +653,16 @@ export const RemoteServerFactory = { const encodedSlasCredentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64') app.use( - SLAS_CUSTOM_PROXY_PATH, + getSLASPrivateProxyPath(), createProxyMiddleware({ target: options.slasTarget, changeOrigin: true, - pathRewrite: {[SLAS_CUSTOM_PROXY_PATH]: ''}, + pathRewrite: {[getSLASPrivateProxyPath()]: ''}, onProxyReq: (proxyRequest, incomingRequest) => { applyProxyRequestHeaders({ proxyRequest, incomingRequest, - proxyPath: SLAS_CUSTOM_PROXY_PATH, + proxyPath: getSLASPrivateProxyPath(), targetHost: options.slasHostName, targetProtocol: 'https' }) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 60c697380d..8691344d35 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -89,6 +89,10 @@ export const getHealtCheckPathBase = () => { return '/mobify/ping' } +export const getSLASPrivateProxyPath = () => { + return '/mobify/slas/private' +} + /** * Updates the value of _packageMobify and dependent values. * From 02112872d67eb334312ab44de3a4b9073ce6f73e Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Fri, 10 May 2024 15:26:20 -0700 Subject: [PATCH 04/12] Enable private client --- .../app/components/_app-config/index.jsx | 2 +- packages/template-retail-react-app/app/ssr.js | 2 +- packages/template-retail-react-app/config/default.js | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 2ecf0700d3..550b50548a 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -67,7 +67,7 @@ const AppConfig = ({children, locals = {}}) => { headers={headers} // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. - // enablePWAKitPrivateClient={true} + enablePWAKitPrivateClient={true} OCAPISessionsURL={`${appOrigin}${getProxyPathBase()}/ocapi/s/${locals.site?.id}/dw/shop/v22_8/sessions`} > diff --git a/packages/template-retail-react-app/app/ssr.js b/packages/template-retail-react-app/app/ssr.js index 269f375802..5b3b26cd98 100644 --- a/packages/template-retail-react-app/app/ssr.js +++ b/packages/template-retail-react-app/app/ssr.js @@ -45,7 +45,7 @@ const options = { // Set this to false if using a SLAS public client // When setting this to true, make sure to also set the PWA_KIT_SLAS_CLIENT_SECRET // environment variable as this endpoint will return HTTP 501 if it is not set - useSLASPrivateClient: false + useSLASPrivateClient: true } const runtime = getRuntime() diff --git a/packages/template-retail-react-app/config/default.js b/packages/template-retail-react-app/config/default.js index 0181da007a..65ef37891e 100644 --- a/packages/template-retail-react-app/config/default.js +++ b/packages/template-retail-react-app/config/default.js @@ -24,10 +24,10 @@ module.exports = { commerceAPI: { proxyPath: `/mobify/proxy/api`, parameters: { - clientId: 'c9c45bfd-0ed3-4aa2-9971-40f88962b836', + clientId: 'c131a4df-2d7b-4a67-802f-45152e911cc2', organizationId: 'f_ecom_zzrf_001', - shortCode: '8o7m175y', - siteId: 'RefArchGlobal' + shortCode: 'kv7kzm78', + siteId: 'RefArch' } }, einsteinAPI: { From 0f3500e66b6dbd319b0c6c78b59b5737da5553bf Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Tue, 14 May 2024 14:20:24 -0700 Subject: [PATCH 05/12] POC working ssrnamespace --- packages/commerce-sdk-react/src/auth/index.ts | 6 +-- packages/commerce-sdk-react/src/utils.ts | 10 ++--- .../src/utils/ssr-server/configure-proxy.js | 12 +----- .../pwa-kit-runtime/src/utils/ssr-shared.js | 37 ++++++++++++++++--- .../app/components/_app-config/index.jsx | 12 ++++-- .../config/default.js | 1 + 6 files changed, 48 insertions(+), 30 deletions(-) diff --git a/packages/commerce-sdk-react/src/auth/index.ts b/packages/commerce-sdk-react/src/auth/index.ts index 0d31e5941e..1fb03cd027 100644 --- a/packages/commerce-sdk-react/src/auth/index.ts +++ b/packages/commerce-sdk-react/src/auth/index.ts @@ -15,7 +15,7 @@ import {jwtDecode, JwtPayload} from 'jwt-decode' import {ApiClientConfigParams, Prettify, RemoveStringIndex} from '../hooks/types' import {BaseStorage, LocalStorage, CookieStorage, MemoryStorage, StorageType} from './storage' import {CustomerType} from '../hooks/useCustomerType' -import {getParentOrigin, isOriginTrusted, onClient, getProxyPath, getSLASPath} from '../utils' +import {getParentOrigin, isOriginTrusted, onClient} from '../utils' import { SLAS_SECRET_WARNING_MSG, SLAS_SECRET_PLACEHOLDER, @@ -175,8 +175,8 @@ class Auth { constructor(config: AuthConfig) { // Special endpoint for injecting SLAS private client secret - const baseUrl = config.proxy.split(`${getProxyPath()}`)[0] - const privateClientEndpoint = `${baseUrl}${getSLASPath()}` + const baseUrl = config.proxy.split(`/mobify`)[0] + const privateClientEndpoint = `${baseUrl}/mobify/slas/private` this.client = new ShopperLogin({ proxy: config.enablePWAKitPrivateClient ? privateClientEndpoint : config.proxy, diff --git a/packages/commerce-sdk-react/src/utils.ts b/packages/commerce-sdk-react/src/utils.ts index 23e32e3212..ff621bdb9f 100644 --- a/packages/commerce-sdk-react/src/utils.ts +++ b/packages/commerce-sdk-react/src/utils.ts @@ -47,16 +47,12 @@ export const isOriginTrusted = (origin: string | undefined) => { ) } -export const getProxyPath = () => { - return '/mobify/proxy/api' +export const getNamespace = () => { + return 'abc' } export const getDevelopBundlePath = () => { - return '/mobify/bundle/development' -} - -export const getSLASPath = () => { - return '/mobify/slas/private' + return getNamespace() ? `/${getNamespace()}/mobify/bundle/development` :'/mobify/bundle/development' } /** diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js b/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js index e7fcb32aa9..7722b9d356 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js @@ -6,22 +6,12 @@ */ import {createProxyMiddleware} from 'http-proxy-middleware' import {rewriteProxyRequestHeaders, rewriteProxyResponseHeaders} from '../ssr-proxying' -import {proxyConfigs} from '../ssr-shared' +import {proxyConfigs, generalProxyPathRE} from '../ssr-shared' import {processExpressResponse} from './process-express-response' import {isRemote, localDevLog, verboseProxyLogging} from './utils' export const ALLOWED_CACHING_PROXY_REQUEST_METHODS = ['HEAD', 'GET', 'OPTIONS'] -/** - * This path matching RE matches on /mobify/proxy and then skips one path - * element. For example, /mobify/proxy/heffalump/woozle would be converted to - * /woozle on whatever host /mobify/proxy/heffalump maps to. - * Group 2 is the full path on the proxied host. - * @private - * @type {RegExp} - */ -const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/ - /** * Apply proxy headers to a request that is being proxied. * diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 8691344d35..2f9f3268a1 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -8,6 +8,9 @@ * @module progressive-web-sdk/utils/ssr-shared * @private */ + +import {getConfig} from './ssr-config' + /* The ssr-shared-utils module is used in the PWA and in the Express app. It should contain ONLY the code that is required in both, to avoid adding @@ -58,6 +61,16 @@ export let proxyConfigs = [] */ export let ssrFiles = [] +/** + * A string that can be defined in the namespace property inside the config file. + * @private + */ + +const config = getConfig() + +// TODO - make this available from config file & client side +export let namespace = config.ssrNamespace + /** * RegExp that matches a proxy override string * match[1] is the protocol @@ -69,28 +82,39 @@ export let ssrFiles = [] */ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ +/** + * This path matching RE matches on /mobify/proxy and then skips one path + * element. For example, /mobify/proxy/heffalump/woozle would be converted to + * /woozle on whatever host /mobify/proxy/heffalump maps to. + * Group 2 is the full path on the proxied host. + * @private + * @type {RegExp} + */ +export const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/ + export const startsWithMobify = (url) => { return url.startsWith('/mobify/') } export const getProxyPathBase = () => { - return '/mobify/proxy' + return namespace ? `/${namespace}/mobify/proxy` : '/mobify/proxy' } export const getBundlePathBase = () => { - return '/mobify/bundle' + console.log(`Bundle Path Namespace: ${namespace}`) + return namespace ? `/${namespace}/mobify/bundle` : '/mobify/bundle' } export const getCachingPathBase = () => { - return '/mobify/caching' + return namespace ? `/${namespace}/mobify/caching` : '/mobify/caching' } export const getHealtCheckPathBase = () => { - return '/mobify/ping' + return namespace ? `/${namespace}/mobify/ping` : '/mobify/ping' } export const getSLASPrivateProxyPath = () => { - return '/mobify/slas/private' + return namespace ? `/${namespace}/mobify/slas/private` : '/mobify/slas/private' } /** @@ -102,6 +126,9 @@ export const getSLASPrivateProxyPath = () => { export const updatePackageMobify = (newValue) => { _packageMobify = newValue || _packageMobify || {} + // Read namespace from config if it exists + // namespace = _packageMobify.ssrNamespace || '' + // Clear and update the proxyConfigs array proxyConfigs = [] const ssrParameters = getSSRParameters() diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 550b50548a..539386617c 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -50,9 +50,13 @@ const AppConfig = ({children, locals = {}}) => { 'correlation-id': correlationId } + const appOrigin = getAppOrigin() + const commerceApiConfig = locals.appConfig.commerceAPI - const appOrigin = getAppOrigin() + const proxy = locals.ssrNamespace + ? `${appOrigin}/${locals.ssrNamespace}${commerceApiConfig.proxyPath}` + : `${appOrigin}${commerceApiConfig.proxyPath}` return ( { locale={locals.locale?.id} currency={locals.locale?.preferredCurrency} redirectURI={`${appOrigin}/callback`} - proxy={`${appOrigin}${commerceApiConfig.proxyPath}`} + proxy={proxy} headers={headers} // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. @@ -85,8 +89,7 @@ AppConfig.restore = (locals = {}) => { : `${window.location.pathname}${window.location.search}` const site = resolveSiteFromUrl(path) const locale = resolveLocaleFromUrl(path) - - const {app: appConfig} = getConfig() + const {app: appConfig, ssrNamespace} = getConfig() const apiConfig = { ...appConfig.commerceAPI, einsteinConfig: appConfig.einsteinAPI @@ -95,6 +98,7 @@ AppConfig.restore = (locals = {}) => { apiConfig.parameters.siteId = site.id locals.buildUrl = createUrlTemplate(appConfig, site.alias || site.id, locale.id) + locals.ssrNamespace = ssrNamespace locals.site = site locals.locale = locale locals.appConfig = appConfig diff --git a/packages/template-retail-react-app/config/default.js b/packages/template-retail-react-app/config/default.js index 65ef37891e..d68e4146c5 100644 --- a/packages/template-retail-react-app/config/default.js +++ b/packages/template-retail-react-app/config/default.js @@ -40,6 +40,7 @@ module.exports = { }, externals: [], pageNotFoundURL: '/page-not-found', + ssrNamespace: 'abc', ssrEnabled: true, ssrOnly: ['ssr.js', 'ssr.js.map', 'node_modules/**/*.*'], ssrShared: [ From 76fbe17a20636daaa42390bd495ab3586db65738 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Tue, 14 May 2024 15:21:17 -0700 Subject: [PATCH 06/12] Fix startsWith --- packages/pwa-kit-runtime/src/utils/ssr-shared.js | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 2f9f3268a1..7e8f5fdec4 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -4,13 +4,13 @@ * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ + +import { getConfig } from './ssr-config' + /** * @module progressive-web-sdk/utils/ssr-shared * @private */ - -import {getConfig} from './ssr-config' - /* The ssr-shared-utils module is used in the PWA and in the Express app. It should contain ONLY the code that is required in both, to avoid adding @@ -66,10 +66,8 @@ export let ssrFiles = [] * @private */ -const config = getConfig() - // TODO - make this available from config file & client side -export let namespace = config.ssrNamespace +const namespace = getConfig().ssrNamespace /** * RegExp that matches a proxy override string @@ -93,7 +91,8 @@ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ export const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/ export const startsWithMobify = (url) => { - return url.startsWith('/mobify/') + const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` + return url.startsWith(mobifyPath) } export const getProxyPathBase = () => { From c69eec624ce0e9ca0e3c85037495fc292618489e Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Tue, 14 May 2024 16:00:44 -0700 Subject: [PATCH 07/12] Fix client side calls --- .../src/utils/ssr-server/configure-proxy.js | 12 +++++++++++- packages/pwa-kit-runtime/src/utils/ssr-shared.js | 13 ++----------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js b/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js index 7722b9d356..e7fcb32aa9 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-server/configure-proxy.js @@ -6,12 +6,22 @@ */ import {createProxyMiddleware} from 'http-proxy-middleware' import {rewriteProxyRequestHeaders, rewriteProxyResponseHeaders} from '../ssr-proxying' -import {proxyConfigs, generalProxyPathRE} from '../ssr-shared' +import {proxyConfigs} from '../ssr-shared' import {processExpressResponse} from './process-express-response' import {isRemote, localDevLog, verboseProxyLogging} from './utils' export const ALLOWED_CACHING_PROXY_REQUEST_METHODS = ['HEAD', 'GET', 'OPTIONS'] +/** + * This path matching RE matches on /mobify/proxy and then skips one path + * element. For example, /mobify/proxy/heffalump/woozle would be converted to + * /woozle on whatever host /mobify/proxy/heffalump maps to. + * Group 2 is the full path on the proxied host. + * @private + * @type {RegExp} + */ +const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/ + /** * Apply proxy headers to a request that is being proxied. * diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 7e8f5fdec4..6d1f328194 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -67,7 +67,8 @@ export let ssrFiles = [] */ // TODO - make this available from config file & client side -const namespace = getConfig().ssrNamespace +// const namespace = getConfig().ssrNamespace +const namespace = 'abc' /** * RegExp that matches a proxy override string @@ -80,16 +81,6 @@ const namespace = getConfig().ssrNamespace */ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ -/** - * This path matching RE matches on /mobify/proxy and then skips one path - * element. For example, /mobify/proxy/heffalump/woozle would be converted to - * /woozle on whatever host /mobify/proxy/heffalump maps to. - * Group 2 is the full path on the proxied host. - * @private - * @type {RegExp} - */ -export const generalProxyPathRE = /^\/mobify\/proxy\/([^/]+)(\/.*)$/ - export const startsWithMobify = (url) => { const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` return url.startsWith(mobifyPath) From da2d964993d30cfe908b0e013be2711b7189d51a Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Wed, 15 May 2024 11:16:03 -0700 Subject: [PATCH 08/12] Read namespace from config --- packages/pwa-kit-runtime/src/utils/ssr-shared.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 6d1f328194..5b4f6956ae 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -68,7 +68,7 @@ export let ssrFiles = [] // TODO - make this available from config file & client side // const namespace = getConfig().ssrNamespace -const namespace = 'abc' +// const namespace = 'abc' /** * RegExp that matches a proxy override string @@ -82,28 +82,33 @@ const namespace = 'abc' const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ export const startsWithMobify = (url) => { + const namespace = getConfig().ssrNamespace const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` return url.startsWith(mobifyPath) } export const getProxyPathBase = () => { + const namespace = getConfig().ssrNamespace return namespace ? `/${namespace}/mobify/proxy` : '/mobify/proxy' } export const getBundlePathBase = () => { - console.log(`Bundle Path Namespace: ${namespace}`) + const namespace = getConfig().ssrNamespace return namespace ? `/${namespace}/mobify/bundle` : '/mobify/bundle' } export const getCachingPathBase = () => { + const namespace = getConfig().ssrNamespace return namespace ? `/${namespace}/mobify/caching` : '/mobify/caching' } export const getHealtCheckPathBase = () => { + const namespace = getConfig().ssrNamespace return namespace ? `/${namespace}/mobify/ping` : '/mobify/ping' } export const getSLASPrivateProxyPath = () => { + const namespace = getConfig().ssrNamespace return namespace ? `/${namespace}/mobify/slas/private` : '/mobify/slas/private' } From 76fce5258199ac0a6d69cfaa11175b4a29de9594 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Thu, 16 May 2024 14:58:15 -0700 Subject: [PATCH 09/12] Use siteAlias as the namespace --- .../pwa-kit-runtime/src/utils/ssr-shared.js | 22 ++++++++++++++----- .../app/components/_app-config/index.jsx | 9 ++++---- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index 5b4f6956ae..f4643f788d 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -70,6 +70,16 @@ export let ssrFiles = [] // const namespace = getConfig().ssrNamespace // const namespace = 'abc' +export const getNamespace = () => { + const config = getConfig() + const defaultSiteId = config.app.defaultSite + const siteAliases = config.app.siteAliases + + const alias = siteAliases[defaultSiteId] + + return alias ? alias : defaultSiteId +} + /** * RegExp that matches a proxy override string * match[1] is the protocol @@ -82,33 +92,33 @@ export let ssrFiles = [] const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ export const startsWithMobify = (url) => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` return url.startsWith(mobifyPath) } export const getProxyPathBase = () => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() return namespace ? `/${namespace}/mobify/proxy` : '/mobify/proxy' } export const getBundlePathBase = () => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() return namespace ? `/${namespace}/mobify/bundle` : '/mobify/bundle' } export const getCachingPathBase = () => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() return namespace ? `/${namespace}/mobify/caching` : '/mobify/caching' } export const getHealtCheckPathBase = () => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() return namespace ? `/${namespace}/mobify/ping` : '/mobify/ping' } export const getSLASPrivateProxyPath = () => { - const namespace = getConfig().ssrNamespace + const namespace = getNamespace() return namespace ? `/${namespace}/mobify/slas/private` : '/mobify/slas/private' } diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 539386617c..12659a1970 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -27,7 +27,7 @@ import { resolveLocaleFromUrl } from '@salesforce/retail-react-app/app/utils/site-utils' import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config' -import {getProxyPathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' +import {getNamespace, getProxyPathBase} from '@salesforce/pwa-kit-runtime/utils/ssr-shared' import {createUrlTemplate} from '@salesforce/retail-react-app/app/utils/url' import {CommerceApiProvider} from '@salesforce/commerce-sdk-react' @@ -54,8 +54,8 @@ const AppConfig = ({children, locals = {}}) => { const commerceApiConfig = locals.appConfig.commerceAPI - const proxy = locals.ssrNamespace - ? `${appOrigin}/${locals.ssrNamespace}${commerceApiConfig.proxyPath}` + const proxy = getNamespace() + ? `${appOrigin}/${getNamespace()}${commerceApiConfig.proxyPath}` : `${appOrigin}${commerceApiConfig.proxyPath}` return ( @@ -89,7 +89,7 @@ AppConfig.restore = (locals = {}) => { : `${window.location.pathname}${window.location.search}` const site = resolveSiteFromUrl(path) const locale = resolveLocaleFromUrl(path) - const {app: appConfig, ssrNamespace} = getConfig() + const {app: appConfig} = getConfig() const apiConfig = { ...appConfig.commerceAPI, einsteinConfig: appConfig.einsteinAPI @@ -98,7 +98,6 @@ AppConfig.restore = (locals = {}) => { apiConfig.parameters.siteId = site.id locals.buildUrl = createUrlTemplate(appConfig, site.alias || site.id, locale.id) - locals.ssrNamespace = ssrNamespace locals.site = site locals.locale = locale locals.appConfig = appConfig From 6ace18859fb56e62cc04a56491d426e297b71a28 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Thu, 16 May 2024 16:57:18 -0700 Subject: [PATCH 10/12] Local env var for config files --- packages/pwa-kit-dev/src/configs/jest/jest.config.js | 4 +++- packages/pwa-kit-dev/src/configs/webpack/config.js | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/pwa-kit-dev/src/configs/jest/jest.config.js b/packages/pwa-kit-dev/src/configs/jest/jest.config.js index c3adee91e9..2d7e98464c 100644 --- a/packages/pwa-kit-dev/src/configs/jest/jest.config.js +++ b/packages/pwa-kit-dev/src/configs/jest/jest.config.js @@ -6,6 +6,8 @@ */ import path from 'path' +const LOCAL_ENV_NAMESPACE = process.env.LOCAL_ENV_NAMESPACE ? `/${process.env.LOCAL_ENV_NAMESPACE}` : '' + module.exports = { testURL: 'http://localhost/', verbose: true, @@ -26,7 +28,7 @@ module.exports = { DEBUG: true, NODE_ENV: 'test', Progressive: { - buildOrigin: '/mobify/bundle/development/' + buildOrigin: `${LOCAL_ENV_NAMESPACE}/mobify/bundle/development/` } }, transform: { diff --git a/packages/pwa-kit-dev/src/configs/webpack/config.js b/packages/pwa-kit-dev/src/configs/webpack/config.js index 54634949cf..01d14afdfa 100644 --- a/packages/pwa-kit-dev/src/configs/webpack/config.js +++ b/packages/pwa-kit-dev/src/configs/webpack/config.js @@ -38,6 +38,8 @@ const DEBUG = mode !== production && process.env.DEBUG === 'true' const CI = process.env.CI const disableHMR = process.env.HMR === 'false' +const LOCAL_ENV_NAMESPACE = process.env.LOCAL_ENV_NAMESPACE ? `/${process.env.LOCAL_ENV_NAMESPACE}` : '' + if ([production, development].indexOf(mode) < 0) { throw new Error(`Invalid mode "${mode}"`) } @@ -407,7 +409,7 @@ const enableReactRefresh = (config) => { output: { ...config.output, // Setting this so that *.hot-update.json requests are resolving - publicPath: '/mobify/bundle/development/' + publicPath: `${LOCAL_ENV_NAMESPACE}/mobify/bundle/development/` } } } From af5f000f5805f1ddfad2e37c96e8727e08c5af49 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Thu, 16 May 2024 16:57:36 -0700 Subject: [PATCH 11/12] Alias or siteid --- .../pwa-kit-runtime/src/utils/ssr-shared.js | 22 +++++++++++++------ .../app/components/_app-config/index.jsx | 2 +- .../config/default.js | 2 +- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index f4643f788d..c867448f90 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -72,12 +72,20 @@ export let ssrFiles = [] export const getNamespace = () => { const config = getConfig() + + const isSSRNamespace = config.enableSSRNamespace + + if (!isSSRNamespace) { + return '' + } + console.log(isSSRNamespace) + const defaultSiteId = config.app.defaultSite const siteAliases = config.app.siteAliases const alias = siteAliases[defaultSiteId] - return alias ? alias : defaultSiteId + return alias ? `/${alias}` : `/${defaultSiteId}` } /** @@ -93,33 +101,33 @@ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ export const startsWithMobify = (url) => { const namespace = getNamespace() - const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` + const mobifyPath = namespace ? `${namespace}/mobify` : `/mobify` return url.startsWith(mobifyPath) } export const getProxyPathBase = () => { const namespace = getNamespace() - return namespace ? `/${namespace}/mobify/proxy` : '/mobify/proxy' + return namespace ? `${namespace}/mobify/proxy` : '/mobify/proxy' } export const getBundlePathBase = () => { const namespace = getNamespace() - return namespace ? `/${namespace}/mobify/bundle` : '/mobify/bundle' + return namespace ? `${namespace}/mobify/bundle` : '/mobify/bundle' } export const getCachingPathBase = () => { const namespace = getNamespace() - return namespace ? `/${namespace}/mobify/caching` : '/mobify/caching' + return namespace ? `${namespace}/mobify/caching` : '/mobify/caching' } export const getHealtCheckPathBase = () => { const namespace = getNamespace() - return namespace ? `/${namespace}/mobify/ping` : '/mobify/ping' + return namespace ? `${namespace}/mobify/ping` : '/mobify/ping' } export const getSLASPrivateProxyPath = () => { const namespace = getNamespace() - return namespace ? `/${namespace}/mobify/slas/private` : '/mobify/slas/private' + return namespace ? `${namespace}/mobify/slas/private` : '/mobify/slas/private' } /** diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 12659a1970..646b0c6e2c 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -55,7 +55,7 @@ const AppConfig = ({children, locals = {}}) => { const commerceApiConfig = locals.appConfig.commerceAPI const proxy = getNamespace() - ? `${appOrigin}/${getNamespace()}${commerceApiConfig.proxyPath}` + ? `${appOrigin}${getNamespace()}${commerceApiConfig.proxyPath}` : `${appOrigin}${commerceApiConfig.proxyPath}` return ( diff --git a/packages/template-retail-react-app/config/default.js b/packages/template-retail-react-app/config/default.js index d68e4146c5..0fd1491727 100644 --- a/packages/template-retail-react-app/config/default.js +++ b/packages/template-retail-react-app/config/default.js @@ -40,7 +40,7 @@ module.exports = { }, externals: [], pageNotFoundURL: '/page-not-found', - ssrNamespace: 'abc', + enableSSRNamespace: false, ssrEnabled: true, ssrOnly: ['ssr.js', 'ssr.js.map', 'node_modules/**/*.*'], ssrShared: [ From e31c92eeb70a31ef52be0ee9c9cb466e75ee5299 Mon Sep 17 00:00:00 2001 From: vcua-mobify Date: Thu, 16 May 2024 18:04:02 -0700 Subject: [PATCH 12/12] Namespace cookies and local store --- packages/commerce-sdk-react/src/auth/index.ts | 3 +- .../src/components/StorefrontPreview/utils.ts | 5 +-- packages/commerce-sdk-react/src/provider.tsx | 5 +++ packages/commerce-sdk-react/src/utils.ts | 35 ++++++++++++++----- .../pwa-kit-runtime/src/utils/ssr-shared.js | 16 ++++----- .../app/components/_app-config/index.jsx | 3 +- .../config/default.js | 2 +- 7 files changed, 47 insertions(+), 22 deletions(-) diff --git a/packages/commerce-sdk-react/src/auth/index.ts b/packages/commerce-sdk-react/src/auth/index.ts index 1fb03cd027..39d1b5275f 100644 --- a/packages/commerce-sdk-react/src/auth/index.ts +++ b/packages/commerce-sdk-react/src/auth/index.ts @@ -29,6 +29,7 @@ interface AuthConfig extends ApiClientConfigParams { proxy: string fetchOptions?: ShopperLoginTypes.FetchOptions fetchedToken?: string + envNamespace?: string OCAPISessionsURL?: string enablePWAKitPrivateClient?: boolean clientSecret?: string @@ -202,7 +203,7 @@ class Auth { }) const options = { - keySuffix: config.siteId, + keySuffix: config.envNamespace ? `${config.envNamespace}_${config.siteId}` : config.siteId, // Setting this to true on the server allows us to reuse guest auth tokens across lambda runs sharedContext: !onClient() } diff --git a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts index f1470e14ce..b21de6843c 100644 --- a/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts +++ b/packages/commerce-sdk-react/src/components/StorefrontPreview/utils.ts @@ -6,7 +6,7 @@ */ import {ApiClients} from '../../hooks/types' -import {DEVELOPMENT_ORIGIN, getParentOrigin, isOriginTrusted, getDevelopBundlePath} from '../../utils' +import {DEVELOPMENT_ORIGIN, getParentOrigin, isOriginTrusted, getNamespace} from '../../utils' /** Detects whether the storefront is running in an iframe as part of Storefront Preview. * @private @@ -21,8 +21,9 @@ export const detectStorefrontPreview = () => { */ export const getClientScript = () => { const parentOrigin = getParentOrigin() ?? 'https://runtime.commercecloud.com' + return parentOrigin === DEVELOPMENT_ORIGIN - ? `${parentOrigin}${getDevelopBundlePath()}/static/storefront-preview.js` + ? `${parentOrigin}${getNamespace()}/mobify/bundle/development/static/storefront-preview.js` : `${parentOrigin}/cc/b2c/preview/preview.client.js` } diff --git a/packages/commerce-sdk-react/src/provider.tsx b/packages/commerce-sdk-react/src/provider.tsx index 1a1f7d8c65..25aa0250f1 100644 --- a/packages/commerce-sdk-react/src/provider.tsx +++ b/packages/commerce-sdk-react/src/provider.tsx @@ -31,6 +31,7 @@ export interface CommerceApiProviderProps extends ApiClientConfigParams { fetchOptions?: ShopperBasketsTypes.FetchOptions headers?: Record fetchedToken?: string + envNamespace?: string OCAPISessionsURL?: string enablePWAKitPrivateClient?: boolean clientSecret?: string @@ -107,6 +108,7 @@ const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => { locale, currency, fetchedToken, + envNamespace, OCAPISessionsURL, enablePWAKitPrivateClient, clientSecret, @@ -162,6 +164,7 @@ const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => { redirectURI, fetchOptions, fetchedToken, + envNamespace, OCAPISessionsURL, enablePWAKitPrivateClient, clientSecret, @@ -176,6 +179,7 @@ const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => { redirectURI, fetchOptions, fetchedToken, + envNamespace, OCAPISessionsURL, enablePWAKitPrivateClient, clientSecret, @@ -194,6 +198,7 @@ const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => { proxy, redirectURI, fetchOptions, + envNamespace, siteId, shortCode, locale, diff --git a/packages/commerce-sdk-react/src/utils.ts b/packages/commerce-sdk-react/src/utils.ts index ff621bdb9f..ef555e3149 100644 --- a/packages/commerce-sdk-react/src/utils.ts +++ b/packages/commerce-sdk-react/src/utils.ts @@ -8,6 +8,13 @@ import Cookies, {CookieAttributes} from 'js-cookie' import {IFRAME_HOST_ALLOW_LIST} from './constant' +declare global { + interface Window { + __CONFIG__: any; + } +} + + /** Utility to determine if you are on the browser (client) or not. */ export const onClient = (): boolean => typeof window !== 'undefined' @@ -34,6 +41,26 @@ export const getParentOrigin = () => { } } +export const getNamespace = () => { + /* tslint:disable-next-line */ + + if (!onClient()) { + return '' + } + const config = window.__CONFIG__ + const isSSRNamespace = config.enableSSRNamespace + + if (!isSSRNamespace) { + return '' + } + + const defaultSiteId = config.app.defaultSite + const siteAliases = config.app.siteAliases + const alias = siteAliases[defaultSiteId] + + return alias ? `/${alias}` : `/${defaultSiteId}` +} + /** * Determines whether the given origin is trusted to host the storefront in an iframe. * @private @@ -47,14 +74,6 @@ export const isOriginTrusted = (origin: string | undefined) => { ) } -export const getNamespace = () => { - return 'abc' -} - -export const getDevelopBundlePath = () => { - return getNamespace() ? `/${getNamespace()}/mobify/bundle/development` :'/mobify/bundle/development' -} - /** * Gets the value to use for the `sameSite` cookie attribute. * @returns `undefined` if running on the server, `"none"` if running as an iframe on a trusted site diff --git a/packages/pwa-kit-runtime/src/utils/ssr-shared.js b/packages/pwa-kit-runtime/src/utils/ssr-shared.js index c867448f90..a24c97c0a5 100644 --- a/packages/pwa-kit-runtime/src/utils/ssr-shared.js +++ b/packages/pwa-kit-runtime/src/utils/ssr-shared.js @@ -78,14 +78,12 @@ export const getNamespace = () => { if (!isSSRNamespace) { return '' } - console.log(isSSRNamespace) const defaultSiteId = config.app.defaultSite const siteAliases = config.app.siteAliases - const alias = siteAliases[defaultSiteId] - return alias ? `/${alias}` : `/${defaultSiteId}` + return alias ? `${alias}` : `${defaultSiteId}` } /** @@ -101,33 +99,33 @@ const proxyOverrideRE = /^(http(s)?):\/\/([^/]+)(\/)?([^/]+)?(\/caching)?/ export const startsWithMobify = (url) => { const namespace = getNamespace() - const mobifyPath = namespace ? `${namespace}/mobify` : `/mobify` + const mobifyPath = namespace ? `/${namespace}/mobify` : `/mobify` return url.startsWith(mobifyPath) } export const getProxyPathBase = () => { const namespace = getNamespace() - return namespace ? `${namespace}/mobify/proxy` : '/mobify/proxy' + return namespace ? `/${namespace}/mobify/proxy` : '/mobify/proxy' } export const getBundlePathBase = () => { const namespace = getNamespace() - return namespace ? `${namespace}/mobify/bundle` : '/mobify/bundle' + return namespace ? `/${namespace}/mobify/bundle` : '/mobify/bundle' } export const getCachingPathBase = () => { const namespace = getNamespace() - return namespace ? `${namespace}/mobify/caching` : '/mobify/caching' + return namespace ? `/${namespace}/mobify/caching` : '/mobify/caching' } export const getHealtCheckPathBase = () => { const namespace = getNamespace() - return namespace ? `${namespace}/mobify/ping` : '/mobify/ping' + return namespace ? `/${namespace}/mobify/ping` : '/mobify/ping' } export const getSLASPrivateProxyPath = () => { const namespace = getNamespace() - return namespace ? `${namespace}/mobify/slas/private` : '/mobify/slas/private' + return namespace ? `/${namespace}/mobify/slas/private` : '/mobify/slas/private' } /** diff --git a/packages/template-retail-react-app/app/components/_app-config/index.jsx b/packages/template-retail-react-app/app/components/_app-config/index.jsx index 646b0c6e2c..877bf0be0e 100644 --- a/packages/template-retail-react-app/app/components/_app-config/index.jsx +++ b/packages/template-retail-react-app/app/components/_app-config/index.jsx @@ -55,7 +55,7 @@ const AppConfig = ({children, locals = {}}) => { const commerceApiConfig = locals.appConfig.commerceAPI const proxy = getNamespace() - ? `${appOrigin}${getNamespace()}${commerceApiConfig.proxyPath}` + ? `${appOrigin}/${getNamespace()}${commerceApiConfig.proxyPath}` : `${appOrigin}${commerceApiConfig.proxyPath}` return ( @@ -68,6 +68,7 @@ const AppConfig = ({children, locals = {}}) => { currency={locals.locale?.preferredCurrency} redirectURI={`${appOrigin}/callback`} proxy={proxy} + envNamespace={getNamespace()} headers={headers} // Uncomment 'enablePWAKitPrivateClient' to use SLAS private client login flows. // Make sure to also enable useSLASPrivateClient in ssr.js when enabling this setting. diff --git a/packages/template-retail-react-app/config/default.js b/packages/template-retail-react-app/config/default.js index 0fd1491727..d7fe7ad6cc 100644 --- a/packages/template-retail-react-app/config/default.js +++ b/packages/template-retail-react-app/config/default.js @@ -40,7 +40,7 @@ module.exports = { }, externals: [], pageNotFoundURL: '/page-not-found', - enableSSRNamespace: false, + enableSSRNamespace: true, ssrEnabled: true, ssrOnly: ['ssr.js', 'ssr.js.map', 'node_modules/**/*.*'], ssrShared: [