@hubspot/cms-dev-server 1.1.0-prerelease.7 → 1.1.0-prerelease.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/argHelpers.js +6 -0
- package/dist/lib/cli.js +23 -0
- package/dist/lib/renderHelpers.js +34 -10
- package/dist/plugins/devMockClientEntryPlugin.js +1 -1
- package/dist/routes/module.js +2 -1
- package/dist/routes/partial.js +2 -1
- package/package.json +4 -4
- package/dist/routes/proxyPage.js +0 -205
- package/dist/run.mjs +0 -10
- package/dist/src/components/ModulesList.js +0 -14
- package/dist/src/components/PartialsList.js +0 -13
- package/dist/src/createDevServer.js +0 -45
- package/dist/src/lib/htmlHelpers.js +0 -10
- package/dist/src/lib/moduleGraph.js +0 -9
- package/dist/src/lib/proxyHelpers.js +0 -55
- package/dist/src/lib/proxyHelpers.test.js +0 -136
- package/dist/src/lib/renderComponentWithCSS.js +0 -26
- package/dist/src/lib/renderModule.js +0 -84
- package/dist/src/lib/renderPartial.js +0 -11
- package/dist/src/lib/templates.js +0 -50
- package/dist/src/plugins/devMockClientEntryPlugin.js +0 -52
- package/dist/src/proxyPage/constants.js +0 -4
- package/dist/src/proxyPage/fetchContentMetadata.js +0 -40
- package/dist/src/proxyPage/fetchPreviewInfo.js +0 -25
- package/dist/src/proxyPage/proxyPage.js +0 -147
- package/dist/src/proxyPage/renderLocalError.js +0 -1
- package/dist/src/proxyPage/utils.js +0 -36
- package/dist/src/routes/createDevServerRoutes.js +0 -19
- package/dist/src/routes/homeRouteHandler.js +0 -12
- package/dist/src/routes/linksToAllModulesRouteHandler.js +0 -10
- package/dist/src/routes/linksToAllPartialsRouteHandler.js +0 -10
- package/dist/src/routes/module.js +0 -26
- package/dist/src/routes/partial.js +0 -26
- package/dist/src/routes/proxyPageRouteHandler.js +0 -28
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { hasComponentExtension, removeComponentExtension, } from '@hubspot/cms-js-internal';
|
|
2
|
-
import { findFullPathInModuleGraph } from './moduleGraph.js';
|
|
3
|
-
async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl) {
|
|
4
|
-
// Need to make sure rendering happens in Vite SSR context
|
|
5
|
-
const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
6
|
-
let componentPathWithExtension;
|
|
7
|
-
let componentPathNoExtension;
|
|
8
|
-
// Support paths with or without an extension (do we need/want both?)
|
|
9
|
-
if (hasComponentExtension(componentPath)) {
|
|
10
|
-
componentPathWithExtension = componentPath;
|
|
11
|
-
componentPathNoExtension = removeComponentExtension(componentPath);
|
|
12
|
-
}
|
|
13
|
-
else {
|
|
14
|
-
componentPathNoExtension = componentPath;
|
|
15
|
-
}
|
|
16
|
-
const { html, renderInfoContext } = await renderComponentOnServer(Component, props, pageUrl);
|
|
17
|
-
if (!componentPathWithExtension) {
|
|
18
|
-
componentPathWithExtension = findFullPathInModuleGraph(componentPathNoExtension, viteServer.moduleGraph);
|
|
19
|
-
if (!componentPathWithExtension) {
|
|
20
|
-
throw new Error(`Couldn't find full path to component: ${componentPathNoExtension}`);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
|
|
24
|
-
return { html, cssNeeded, renderInfoContext };
|
|
25
|
-
}
|
|
26
|
-
export default renderComponentWithCSS;
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { join as joinPath } from 'path';
|
|
2
|
-
import { cloneElement } from 'react';
|
|
3
|
-
import { renderToStaticMarkup } from 'react-dom/server';
|
|
4
|
-
import renderComponentWithCSS from './renderComponentWithCSS.js';
|
|
5
|
-
import { traverseFieldsJSON } from '@hubspot/cms-components/fields';
|
|
6
|
-
import { hasComponentExtension } from '@hubspot/cms-js-internal';
|
|
7
|
-
const lookForModuleInFolder = async (modulePath, viteServer) => {
|
|
8
|
-
let componentModule;
|
|
9
|
-
const insideFolderPath = joinPath(modulePath, 'index');
|
|
10
|
-
try {
|
|
11
|
-
componentModule = await viteServer.ssrLoadModule(insideFolderPath);
|
|
12
|
-
}
|
|
13
|
-
catch (e) {
|
|
14
|
-
if (!e.message.includes('failed to load module')) {
|
|
15
|
-
throw e;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
return [componentModule, insideFolderPath];
|
|
19
|
-
};
|
|
20
|
-
async function renderModule(viteServer, requestedModulePath, pageUrl, fieldOverrides = {}) {
|
|
21
|
-
console.log('Rendering module', requestedModulePath);
|
|
22
|
-
let componentModule, foundPath;
|
|
23
|
-
if (!hasComponentExtension(requestedModulePath)) {
|
|
24
|
-
[componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
|
|
25
|
-
}
|
|
26
|
-
if (!componentModule) {
|
|
27
|
-
// Look for non-folder module
|
|
28
|
-
componentModule = await viteServer.ssrLoadModule(requestedModulePath);
|
|
29
|
-
foundPath = componentModule ? requestedModulePath : undefined;
|
|
30
|
-
}
|
|
31
|
-
if (!componentModule) {
|
|
32
|
-
throw new Error(`Couldn't find module: ${requestedModulePath}`);
|
|
33
|
-
}
|
|
34
|
-
const Component = componentModule.Component;
|
|
35
|
-
const fields = componentModule.fields;
|
|
36
|
-
const meta = componentModule.meta;
|
|
37
|
-
if (!Component) {
|
|
38
|
-
throw new Error(`Module does not have a named Component export: ${foundPath}`);
|
|
39
|
-
}
|
|
40
|
-
else if (!fields) {
|
|
41
|
-
throw new Error(`Module does not have a named fields export: ${foundPath}`);
|
|
42
|
-
}
|
|
43
|
-
else if (!meta) {
|
|
44
|
-
throw new Error(`Module does not have a named meta export: ${foundPath}`);
|
|
45
|
-
}
|
|
46
|
-
const fieldsJSON = renderFieldsToJson(fields);
|
|
47
|
-
const props = getPropsForModule(fieldsJSON, fieldOverrides);
|
|
48
|
-
return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl);
|
|
49
|
-
}
|
|
50
|
-
// TODO, move to cms-js-internal?
|
|
51
|
-
function setInHelper(object, nestedKeysArray, value) {
|
|
52
|
-
let curr = object;
|
|
53
|
-
const finalKey = nestedKeysArray.pop();
|
|
54
|
-
for (let nestedKey of nestedKeysArray) {
|
|
55
|
-
if (Number.isInteger(nestedKey)) {
|
|
56
|
-
// TODO support occurences/groups with numeric path keys
|
|
57
|
-
throw new Error('TODO, support traversal of fields with occurances');
|
|
58
|
-
}
|
|
59
|
-
if (curr[nestedKey] === undefined) {
|
|
60
|
-
curr[nestedKey] = {};
|
|
61
|
-
}
|
|
62
|
-
curr = curr[nestedKey];
|
|
63
|
-
}
|
|
64
|
-
curr[finalKey] = value;
|
|
65
|
-
}
|
|
66
|
-
function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
|
|
67
|
-
const props = {};
|
|
68
|
-
traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value, field) => {
|
|
69
|
-
setInHelper(props, fieldPathArray, value);
|
|
70
|
-
});
|
|
71
|
-
return props;
|
|
72
|
-
}
|
|
73
|
-
// TODO, move to cms-js-internal? (also in resolveModulesPlugin.ts)
|
|
74
|
-
function renderFieldsToJson(fields) {
|
|
75
|
-
let moduleJson;
|
|
76
|
-
const outputCallback = (callbackJson) => {
|
|
77
|
-
moduleJson = callbackJson;
|
|
78
|
-
};
|
|
79
|
-
renderToStaticMarkup(cloneElement(fields, {
|
|
80
|
-
outputCallback,
|
|
81
|
-
}));
|
|
82
|
-
return moduleJson;
|
|
83
|
-
}
|
|
84
|
-
export default renderModule;
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import renderComponentWithCSS from './renderComponentWithCSS.js';
|
|
2
|
-
async function renderPartial(viteServer, partialPath, props, pageUrl) {
|
|
3
|
-
console.log('Rendering partial', partialPath);
|
|
4
|
-
const componentModule = await viteServer.ssrLoadModule(partialPath);
|
|
5
|
-
const Component = componentModule.default;
|
|
6
|
-
if (!componentModule) {
|
|
7
|
-
throw new Error(`Couldn't find partial: ${partialPath}`);
|
|
8
|
-
}
|
|
9
|
-
return renderComponentWithCSS(viteServer, partialPath, Component, props, pageUrl);
|
|
10
|
-
}
|
|
11
|
-
export default renderPartial;
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { promises as fsPromises } from 'fs';
|
|
2
|
-
import { rewriteAbsoluteJsAndCssPaths } from './htmlHelpers.js';
|
|
3
|
-
import { sortIslandRootsByPriority, createIslandsGlobalJsForClientInDev, } from '@hubspot/cms-js-internal';
|
|
4
|
-
const { readFile } = fsPromises;
|
|
5
|
-
const ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK = `<script type="module">
|
|
6
|
-
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
|
|
7
|
-
setupIslandHydration();
|
|
8
|
-
</script>
|
|
9
|
-
`;
|
|
10
|
-
const createdPlainHtmlTemplate = async (baseTemplatePath, title) => {
|
|
11
|
-
const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
|
|
12
|
-
return htmlTemplateBase.replace('<!--title-->', title);
|
|
13
|
-
};
|
|
14
|
-
const createIslandHtmlTemplate = async (baseTemplatePath, title) => {
|
|
15
|
-
let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
|
|
16
|
-
htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
|
|
17
|
-
${ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK}
|
|
18
|
-
<!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
|
|
19
|
-
<!--islandsglobal-->
|
|
20
|
-
`);
|
|
21
|
-
return htmlTemplate;
|
|
22
|
-
};
|
|
23
|
-
export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderInfoContext, viteServer) => {
|
|
24
|
-
let htmlTemplate;
|
|
25
|
-
if (renderInfoContext.islands.length) {
|
|
26
|
-
htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title);
|
|
27
|
-
const sortedIslandRoots = sortIslandRootsByPriority(renderInfoContext.islands);
|
|
28
|
-
htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
|
|
29
|
-
${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}
|
|
30
|
-
</script>`);
|
|
31
|
-
}
|
|
32
|
-
else {
|
|
33
|
-
htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
|
|
34
|
-
}
|
|
35
|
-
return await viteServer.transformIndexHtml(url, htmlTemplate);
|
|
36
|
-
};
|
|
37
|
-
export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, devServerHost, devServerPort) => {
|
|
38
|
-
const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
|
|
39
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
40
|
-
const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
41
|
-
let islandRuntimeScript = await viteServer.transformIndexHtml('/', ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK);
|
|
42
|
-
// Need to write JS module URLs to be absolute to localhost for when this island code
|
|
43
|
-
// is injected into a HTML document with a differnt <base> url set
|
|
44
|
-
// Note, :sadtrombone: that https://github.com/vitejs/vite/issues/2196 was closed
|
|
45
|
-
// and that https://github.com/vitejs/vite/pull/5104 doesn't help for JS assets
|
|
46
|
-
islandRuntimeScript = rewriteAbsoluteJsAndCssPaths(islandRuntimeScript, serverDomainAndPort, 'http://');
|
|
47
|
-
islandRuntimeScript = islandRuntimeScript.replace('import RefreshRuntime from "/@react-refresh"', `import RefreshRuntime from "http://${serverDomainAndPort}/@react-refresh"`);
|
|
48
|
-
return `${islandRuntimeScript}
|
|
49
|
-
<script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>`;
|
|
50
|
-
};
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
import { readdirSync } from 'fs';
|
|
3
|
-
const PARTIAL_SOURCE_DIR = 'components/partials';
|
|
4
|
-
function getAllComponentFilenamesIn(dirPath) {
|
|
5
|
-
return readdirSync(dirPath).filter((filename) => {
|
|
6
|
-
const ext = path.extname(filename);
|
|
7
|
-
return ext === '.jsx' || ext === '.tsx';
|
|
8
|
-
});
|
|
9
|
-
}
|
|
10
|
-
const buildMockPartialModule = (entryPointsFileNames) => {
|
|
11
|
-
return entryPointsFileNames
|
|
12
|
-
.map((filename) => {
|
|
13
|
-
const ext = path.extname(filename);
|
|
14
|
-
const withoutExtension = path.basename(filename, ext);
|
|
15
|
-
return `export const ${withoutExtension} = () => import('/${PARTIAL_SOURCE_DIR}/${filename}');`;
|
|
16
|
-
})
|
|
17
|
-
.join('\n');
|
|
18
|
-
};
|
|
19
|
-
// Not needed in dev unless some code wants to do `import { SomePartial } from 'components/partials'`
|
|
20
|
-
export default function devMockClientEntryPlugin(webRoot) {
|
|
21
|
-
const ENTRY_POINTS_PATH = path.resolve(webRoot, PARTIAL_SOURCE_DIR);
|
|
22
|
-
const MOCK_ENTRY_PATH = `${ENTRY_POINTS_PATH}/index.js`;
|
|
23
|
-
return {
|
|
24
|
-
enforce: 'pre',
|
|
25
|
-
name: 'client-entry',
|
|
26
|
-
options(options) {
|
|
27
|
-
if (!options.input) {
|
|
28
|
-
return {
|
|
29
|
-
...options,
|
|
30
|
-
input: [MOCK_ENTRY_PATH],
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
return options;
|
|
34
|
-
},
|
|
35
|
-
async resolveId(source, importer, options) {
|
|
36
|
-
if (source === PARTIAL_SOURCE_DIR /*&& options.isEntry*/) {
|
|
37
|
-
return {
|
|
38
|
-
id: source,
|
|
39
|
-
moduleSideEffects: 'no-treeshake',
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
return null;
|
|
43
|
-
},
|
|
44
|
-
load(id) {
|
|
45
|
-
if (id === PARTIAL_SOURCE_DIR) {
|
|
46
|
-
const entryPointsFileNames = getAllComponentFilenamesIn(ENTRY_POINTS_PATH);
|
|
47
|
-
return buildMockPartialModule(entryPointsFileNames);
|
|
48
|
-
}
|
|
49
|
-
return null;
|
|
50
|
-
},
|
|
51
|
-
};
|
|
52
|
-
}
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import http from 'http';
|
|
2
|
-
import https from 'https';
|
|
3
|
-
export default async function getContentMetadata(url, redirects = 0, originalUrl) {
|
|
4
|
-
if (redirects > 5) {
|
|
5
|
-
throw new Error(`Hit too many redirects to HEAD requests for ${originalUrl}`);
|
|
6
|
-
}
|
|
7
|
-
return new Promise((resolve, reject) => {
|
|
8
|
-
const protocolAPI = url.startsWith('https://') ? https : http;
|
|
9
|
-
protocolAPI
|
|
10
|
-
.request(url, { method: 'HEAD' }, (res) => {
|
|
11
|
-
// Use a lib to better follow various redirects?
|
|
12
|
-
if (res.statusCode >= 300 &&
|
|
13
|
-
res.statusCode < 400 &&
|
|
14
|
-
res.headers.location) {
|
|
15
|
-
console.log(`Redirecting to ${res.headers.location} (from ${url})`);
|
|
16
|
-
return resolve(getContentMetadata(res.headers.location, redirects + 1, originalUrl ?? url));
|
|
17
|
-
}
|
|
18
|
-
const portalIdHeader = res.headers['x-hs-hub-id'];
|
|
19
|
-
const contentId = res.headers['x-hs-content-id'];
|
|
20
|
-
if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
|
|
21
|
-
return reject(new Error(`There were multiple hub ID or content ID headers in the HEAD request to ${url}`));
|
|
22
|
-
}
|
|
23
|
-
else {
|
|
24
|
-
const portalId = parseInt(portalIdHeader, 10);
|
|
25
|
-
if (!portalId || !contentId) {
|
|
26
|
-
return reject(new Error(`Missing hub ID or content ID headers on HEAD request to ${url}`));
|
|
27
|
-
}
|
|
28
|
-
else if (isNaN(portalId)) {
|
|
29
|
-
return reject(new Error(`Hud ID from the HEAD request is not a number: '${portalId}' (${url})`));
|
|
30
|
-
}
|
|
31
|
-
return resolve({ portalId, contentId });
|
|
32
|
-
}
|
|
33
|
-
})
|
|
34
|
-
.on('error', (err) => {
|
|
35
|
-
console.error(err);
|
|
36
|
-
reject(err);
|
|
37
|
-
})
|
|
38
|
-
.end();
|
|
39
|
-
});
|
|
40
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
2
|
-
export default async (accountId, portalId, contentId) => {
|
|
3
|
-
try {
|
|
4
|
-
// Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
|
|
5
|
-
const content = await hsGet(accountId, {
|
|
6
|
-
uri: `/content/api/v4/contents/${contentId}`,
|
|
7
|
-
query: { portalId },
|
|
8
|
-
json: true,
|
|
9
|
-
});
|
|
10
|
-
return {
|
|
11
|
-
previewDomain: content.previewDomain ?? content.resolvedDomain,
|
|
12
|
-
previewKey: content.previewKey,
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
catch (error) {
|
|
16
|
-
console.log(`error`, error);
|
|
17
|
-
if (error.options) {
|
|
18
|
-
console.log(`error.options`, error.options);
|
|
19
|
-
}
|
|
20
|
-
if (error.response && error.response.headers) {
|
|
21
|
-
console.log(`error.response.headers`, error.response.headers);
|
|
22
|
-
}
|
|
23
|
-
throw error;
|
|
24
|
-
}
|
|
25
|
-
};
|
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
|
|
3
|
-
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
4
|
-
import { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
|
|
5
|
-
import renderPartial from '../lib/renderPartial.js';
|
|
6
|
-
import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
|
|
7
|
-
import { addBaseTag, rewriteAbsoluteJsAndCssPaths } from '../lib/htmlHelpers.js';
|
|
8
|
-
import { fakeRenderJsComponent } from './utils.js';
|
|
9
|
-
import renderLocalError from './renderLocalError.js';
|
|
10
|
-
import fetchPreviewInfo from './fetchPreviewInfo.js';
|
|
11
|
-
const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
|
|
12
|
-
const url = new URL(urlToProxy);
|
|
13
|
-
console.log(`Proxying request to ${url.href}`, {
|
|
14
|
-
previewKey,
|
|
15
|
-
contentId,
|
|
16
|
-
});
|
|
17
|
-
const result = hsGet(accountId, {
|
|
18
|
-
baseUrl: url.origin,
|
|
19
|
-
uri: url.pathname,
|
|
20
|
-
query: {
|
|
21
|
-
...url.searchParams,
|
|
22
|
-
hs_preview: `${previewKey}-${contentId}`,
|
|
23
|
-
hsLocalProxy: true
|
|
24
|
-
},
|
|
25
|
-
json: false
|
|
26
|
-
});
|
|
27
|
-
return result.catch((error) => {
|
|
28
|
-
if (error.statusCode >= 400 &&
|
|
29
|
-
error.statusCode < 500 &&
|
|
30
|
-
!!error.response.body) {
|
|
31
|
-
return error.response.body;
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
throw error;
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer, pageUrl) => {
|
|
39
|
-
if (localRenderPlaceholder.path.startsWith('/fake/path/to/')) {
|
|
40
|
-
return fakeRenderJsComponent(indexForThisRender);
|
|
41
|
-
}
|
|
42
|
-
else if (localRenderPlaceholder.path.startsWith('components/partials/')) {
|
|
43
|
-
const partialPath = path.resolve(webRoot, localRenderPlaceholder.path);
|
|
44
|
-
return renderPartial(viteServer, partialPath, localRenderPlaceholder.json, pageUrl);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
throw new Error(`Unimplemented render of ${localRenderPlaceholder.path}`);
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
export default async function proxySpecificPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, urlToProxy, originalUrl) {
|
|
51
|
-
let accountId;
|
|
52
|
-
try {
|
|
53
|
-
accountId = getAccountId(portalId);
|
|
54
|
-
}
|
|
55
|
-
catch (e) {
|
|
56
|
-
response
|
|
57
|
-
.status(500)
|
|
58
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
if (!accountId) {
|
|
62
|
-
response
|
|
63
|
-
.status(500)
|
|
64
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
try {
|
|
68
|
-
const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
|
|
69
|
-
const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
|
|
70
|
-
const { previewDomain, previewKey } = previewInfo;
|
|
71
|
-
let pageHtml;
|
|
72
|
-
pageHtml = await makeProxyPreviewRequest(accountId, urlToProxy, previewKey, contentId);
|
|
73
|
-
pageHtml = addBaseTag(pageHtml, urlToProxy);
|
|
74
|
-
// TODO, this is only needed for asset references that happen _before_ the `<base href="...">` element
|
|
75
|
-
// Is that only a preview URL thing? Or is it in all (most?) rendered CMS pages
|
|
76
|
-
pageHtml = rewriteAbsoluteJsAndCssPaths(pageHtml, previewDomain, 'https://');
|
|
77
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
78
|
-
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
79
|
-
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
80
|
-
const numPlaceholders = localRenderPlaceholders.length;
|
|
81
|
-
const totalNumHtmlChunks = numPlaceholders * 2 + 1;
|
|
82
|
-
let numJsRenderFailures = 0;
|
|
83
|
-
let islands = [];
|
|
84
|
-
const renderPromisesByChunkIndex = new Array(numPlaceholders);
|
|
85
|
-
if (localRenderPlaceholders.length > 0) {
|
|
86
|
-
let offsetSoFar = 0;
|
|
87
|
-
const pageChunks = new Array(numPlaceholders + 1);
|
|
88
|
-
for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
|
|
89
|
-
const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
|
|
90
|
-
pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
|
|
91
|
-
const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer, originalUrl);
|
|
92
|
-
renderPromisesByChunkIndex[indexForThisRender] = renderPromise
|
|
93
|
-
.then((promiseResult) => {
|
|
94
|
-
// eslint-disable-next-line prefer-const
|
|
95
|
-
let { html, cssNeeded, renderInfoContext } = promiseResult;
|
|
96
|
-
console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
|
|
97
|
-
if (renderInfoContext.islands.length > 0) {
|
|
98
|
-
islands = islands.concat(renderInfoContext.islands);
|
|
99
|
-
}
|
|
100
|
-
if (cssNeeded) {
|
|
101
|
-
// Note, this is needed for cases where `<base href="...">` is output by the renderer, so
|
|
102
|
-
// that local asset URLs go to the local dev server
|
|
103
|
-
cssNeeded = rewriteAbsoluteJsAndCssPaths(cssNeeded, serverDomainAndPort, 'http://');
|
|
104
|
-
return `${cssNeeded}\n${html}`;
|
|
105
|
-
}
|
|
106
|
-
return html;
|
|
107
|
-
})
|
|
108
|
-
.catch((e) => {
|
|
109
|
-
numJsRenderFailures += 1;
|
|
110
|
-
console.error(e);
|
|
111
|
-
return renderLocalError(localRenderPlaceholder.path, e);
|
|
112
|
-
});
|
|
113
|
-
offsetSoFar = localRenderPlaceholder.endOffset;
|
|
114
|
-
}
|
|
115
|
-
// Last chunk from end of last placeholder to end of HTML
|
|
116
|
-
pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
|
|
117
|
-
response.writeHead(200);
|
|
118
|
-
for (let i = 0; i < localRenderPlaceholders.length; i++) {
|
|
119
|
-
const chunk = pageChunks[i];
|
|
120
|
-
response.write(chunk);
|
|
121
|
-
const foobar = await renderPromisesByChunkIndex[i];
|
|
122
|
-
// console.log("JS rendered chunk", i, foobar);
|
|
123
|
-
response.write(foobar);
|
|
124
|
-
}
|
|
125
|
-
if (islands.length > 0) {
|
|
126
|
-
const sortedIslandRoots = sortIslandRootsByPriority(islands);
|
|
127
|
-
const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
|
|
128
|
-
response.write(islandRuntimeAndGlobalScriptHtml);
|
|
129
|
-
}
|
|
130
|
-
// Write last string chunk located after last placeholder
|
|
131
|
-
response.write(pageChunks[pageChunks.length - 1]);
|
|
132
|
-
response.end();
|
|
133
|
-
}
|
|
134
|
-
else {
|
|
135
|
-
response.writeHead(200);
|
|
136
|
-
response.write(pageHtml);
|
|
137
|
-
response.end();
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
// TODO change error.stack to error.message before we publish
|
|
142
|
-
response
|
|
143
|
-
.status(500)
|
|
144
|
-
.end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export default (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { createRenderInfoContext } from '@hubspot/cms-components';
|
|
2
|
-
import { VALID_PROXY_DOMAIN_SUFFIXES } from './constants.js';
|
|
3
|
-
export const getSubDomainFromValidLocalDomain = (hostname) => {
|
|
4
|
-
for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
|
|
5
|
-
if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
|
|
6
|
-
return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
return undefined;
|
|
10
|
-
};
|
|
11
|
-
const randomStringWithLotsOf = (char, maxLength) => {
|
|
12
|
-
return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
|
|
13
|
-
};
|
|
14
|
-
export const fakeRenderJsComponent = (indexForThisRender) => {
|
|
15
|
-
return new Promise((resolve, reject) => {
|
|
16
|
-
const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
|
|
17
|
-
setTimeout(() => {
|
|
18
|
-
try {
|
|
19
|
-
const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
|
|
20
|
-
resolve({
|
|
21
|
-
html: fakeJsRenderedOutput,
|
|
22
|
-
cssNeeded: '',
|
|
23
|
-
renderInfoContext: createRenderInfoContext('fake-component'),
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
catch (e) {
|
|
27
|
-
console.log('Error with JS render...');
|
|
28
|
-
console.error(e);
|
|
29
|
-
reject();
|
|
30
|
-
}
|
|
31
|
-
}, randomTimeout);
|
|
32
|
-
});
|
|
33
|
-
};
|
|
34
|
-
export const consoleWarn = (message) => {
|
|
35
|
-
console.warn('\x1b[33m%s\x1b[0m', 'WARNING:', message);
|
|
36
|
-
};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { Router } from 'express';
|
|
2
|
-
import partialRouteHandler from './partial.js';
|
|
3
|
-
import linksToAllPartialsRouteHandler from './linksToAllPartialsRouteHandler.js';
|
|
4
|
-
import linksToAllModulesRouteHandler from './linksToAllModulesRouteHandler.js';
|
|
5
|
-
import moduleRouteHandler from './module.js';
|
|
6
|
-
import proxyPageRouteHandler from './proxyPageRouteHandler.js';
|
|
7
|
-
import homeRouteHandler from './homeRouteHandler.js';
|
|
8
|
-
const createDevServerRoutes = async (packageRoot, webRoot, viteServer) => {
|
|
9
|
-
const devServerApp = Router();
|
|
10
|
-
devServerApp.use(viteServer.middlewares);
|
|
11
|
-
devServerApp.get('/partials/', linksToAllPartialsRouteHandler);
|
|
12
|
-
devServerApp.get('/partial/:partial', partialRouteHandler);
|
|
13
|
-
devServerApp.get('/modules/', linksToAllModulesRouteHandler);
|
|
14
|
-
devServerApp.get('/module/:moduleName', moduleRouteHandler);
|
|
15
|
-
devServerApp.get('/', homeRouteHandler);
|
|
16
|
-
devServerApp.get('/*', proxyPageRouteHandler);
|
|
17
|
-
return devServerApp;
|
|
18
|
-
};
|
|
19
|
-
export default createDevServerRoutes;
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { findAllModulesInRoot, findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
|
|
3
|
-
import ModulesList from '../components/ModulesList.js';
|
|
4
|
-
import PartialsList from '../components/PartialsList.js';
|
|
5
|
-
const homeRouteHandler = async (request, response) => {
|
|
6
|
-
const { webRoot } = request.app.locals;
|
|
7
|
-
const { partialNames } = findAllPartialsInRoot(webRoot);
|
|
8
|
-
const { moduleNames } = findAllModulesInRoot(webRoot);
|
|
9
|
-
const { html: responseHtml } = await renderOnServer(_jsxs(_Fragment, { children: [_jsx("h2", { children: "Partials" }), _jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), _jsx("h2", { children: "Modules" }), _jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames })] }), null);
|
|
10
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
11
|
-
};
|
|
12
|
-
export default homeRouteHandler;
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { findAllModulesInRoot, renderOnServer } from '@hubspot/cms-js-internal';
|
|
3
|
-
import ModulesList from '../components/ModulesList.js';
|
|
4
|
-
const linksToAllModuleRouteHandler = async (request, response) => {
|
|
5
|
-
const { webRoot } = request.app.locals;
|
|
6
|
-
const { moduleNames } = findAllModulesInRoot(webRoot);
|
|
7
|
-
const { html: responseHtml } = await renderOnServer(_jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames }), null);
|
|
8
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
-
};
|
|
10
|
-
export default linksToAllModuleRouteHandler;
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
|
|
3
|
-
import PartialsList from '../components/PartialsList.js';
|
|
4
|
-
const linksToAllPartialRouteHandler = async (request, response) => {
|
|
5
|
-
const { webRoot } = request.app.locals;
|
|
6
|
-
const { partialNames } = findAllPartialsInRoot(webRoot);
|
|
7
|
-
const { html: responseHtml } = await renderOnServer(_jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), null);
|
|
8
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
-
};
|
|
10
|
-
export default linksToAllPartialRouteHandler;
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
import renderModule from '../lib/renderModule.js';
|
|
3
|
-
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
4
|
-
const moduleRouteHandler = async (request, response) => {
|
|
5
|
-
const { packageRoot, webRoot, viteServer } = request.app.locals;
|
|
6
|
-
const moduleName = request.params.moduleName;
|
|
7
|
-
const baseTemplatePath = path.resolve(packageRoot, 'src/baseTemplate.html');
|
|
8
|
-
const modulePath = path.resolve(webRoot, 'components/modules/', moduleName);
|
|
9
|
-
const pageUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
|
|
10
|
-
try {
|
|
11
|
-
const { html: renderedHtml, cssNeeded, renderInfoContext, } = await renderModule(viteServer, modulePath, null);
|
|
12
|
-
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderInfoContext, viteServer);
|
|
13
|
-
const html = htmlShell
|
|
14
|
-
.replace('<!--headend-->', cssNeeded)
|
|
15
|
-
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
16
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
17
|
-
}
|
|
18
|
-
catch (e) {
|
|
19
|
-
console.error(e);
|
|
20
|
-
viteServer.ssrFixStacktrace(e);
|
|
21
|
-
response
|
|
22
|
-
.status(500)
|
|
23
|
-
.end(`Error rendering module (${moduleName})\n\n${e.stack}`);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
export default moduleRouteHandler;
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import path from 'path';
|
|
2
|
-
import renderPartial from '../lib/renderPartial.js';
|
|
3
|
-
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
4
|
-
const partialRouteHandler = async (request, response) => {
|
|
5
|
-
const { packageRoot, webRoot, viteServer } = request.app.locals;
|
|
6
|
-
const partialName = request.params.partial;
|
|
7
|
-
const baseTemplatePath = path.resolve(packageRoot, 'src/baseTemplate.html');
|
|
8
|
-
const partialPath = path.resolve(webRoot, 'components/partials/', partialName);
|
|
9
|
-
const pageUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
|
|
10
|
-
try {
|
|
11
|
-
const { html: renderedHtml, cssNeeded, renderInfoContext, } = await renderPartial(viteServer, partialPath, {}, pageUrl);
|
|
12
|
-
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderInfoContext, viteServer);
|
|
13
|
-
const html = htmlShell
|
|
14
|
-
.replace('<!--headend-->', cssNeeded)
|
|
15
|
-
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
16
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
17
|
-
}
|
|
18
|
-
catch (e) {
|
|
19
|
-
console.error(e);
|
|
20
|
-
viteServer.ssrFixStacktrace(e);
|
|
21
|
-
response
|
|
22
|
-
.status(500)
|
|
23
|
-
.end(`Error rendering partial (${partialName})\n\n${e.stack}`);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
export default partialRouteHandler;
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';
|
|
2
|
-
import proxyPage from '../proxyPage/proxyPage.js';
|
|
3
|
-
import { getSubDomainFromValidLocalDomain, consoleWarn, } from '../proxyPage/utils.js';
|
|
4
|
-
import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
|
|
5
|
-
export default async function proxyPageRouteHandler(request, response) {
|
|
6
|
-
const { viteServer, webRoot, devServerHost, devServerPort } = request.app.locals;
|
|
7
|
-
if (!request.accepts().includes('text/html')) {
|
|
8
|
-
return response.sendStatus(404);
|
|
9
|
-
}
|
|
10
|
-
const originalUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
|
|
11
|
-
const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);
|
|
12
|
-
const pathToProxy = request.path;
|
|
13
|
-
const urlToProxy = `http://${domainToProxy}${pathToProxy}`;
|
|
14
|
-
if (!domainToProxy) {
|
|
15
|
-
if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {
|
|
16
|
-
const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;
|
|
17
|
-
consoleWarn(message);
|
|
18
|
-
return response.status(404).send(message);
|
|
19
|
-
}
|
|
20
|
-
else {
|
|
21
|
-
const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;
|
|
22
|
-
consoleWarn(message);
|
|
23
|
-
return response.status(404).send(message);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
const { portalId, contentId } = await fetchContentMetadata(urlToProxy);
|
|
27
|
-
await proxyPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, urlToProxy, originalUrl);
|
|
28
|
-
}
|