@hubspot/cms-dev-server 0.2.11
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/LICENSE +12 -0
- package/README.md +3 -0
- package/dist/components/ModulesList.js +14 -0
- package/dist/components/PartialsList.js +13 -0
- package/dist/createDevServer.js +63 -0
- package/dist/createViteDevServer.js +26 -0
- package/dist/html/baseTemplate.html +12 -0
- package/dist/lib/argHelpers.js +6 -0
- package/dist/lib/cli.js +23 -0
- package/dist/lib/fullOriginalUrlFromRequest.js +3 -0
- package/dist/lib/htmlHelpers.js +10 -0
- package/dist/lib/moduleGraph.js +11 -0
- package/dist/lib/proxyHelpers.js +70 -0
- package/dist/lib/proxyHelpers.test.js +136 -0
- package/dist/lib/renderComponentWithCSS.js +26 -0
- package/dist/lib/renderHelpers.js +45 -0
- package/dist/lib/renderModule.js +88 -0
- package/dist/lib/renderPartial.js +12 -0
- package/dist/lib/templates.js +48 -0
- package/dist/plugins/devMockClientEntryPlugin.js +52 -0
- package/dist/proxyPage/constants.js +4 -0
- package/dist/proxyPage/fetchContentMetadata.js +51 -0
- package/dist/proxyPage/fetchPreviewInfo.js +37 -0
- package/dist/proxyPage/proxyPage.js +167 -0
- package/dist/proxyPage/renderLocalError.js +27 -0
- package/dist/proxyPage/utils.js +38 -0
- package/dist/routes/createDevServerRoutes.js +21 -0
- package/dist/routes/homeRouteHandler.js +12 -0
- package/dist/routes/linksToAllModulesRouteHandler.js +10 -0
- package/dist/routes/linksToAllPartialsRouteHandler.js +10 -0
- package/dist/routes/module.js +28 -0
- package/dist/routes/partial.js +28 -0
- package/dist/routes/proxyPageResourceRedirect.js +12 -0
- package/dist/routes/proxyPageRouteHandler.js +40 -0
- package/dist/run.js +8 -0
- package/package.json +68 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Copyright 2022 HubSpot, Inc.
|
|
2
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
+
you may not use this file except in compliance with the License.
|
|
4
|
+
You may obtain a copy of the License at
|
|
5
|
+
|
|
6
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
|
|
8
|
+
Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
See the License for the specific language governing permissions and
|
|
12
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
function EmptyModulesList({ webRoot }) {
|
|
3
|
+
return (_jsxs("p", { children: ["No modules in ", _jsxs("code", { children: [webRoot, "components/modules"] })] }));
|
|
4
|
+
}
|
|
5
|
+
function ModuleLinkInLI({ moduleName }) {
|
|
6
|
+
return (_jsx("li", { children: _jsx("a", { href: `/module/${moduleName}`, children: moduleName }) }));
|
|
7
|
+
}
|
|
8
|
+
function ModulesList({ webRoot, moduleNames }) {
|
|
9
|
+
if (moduleNames.length === 0) {
|
|
10
|
+
return _jsx(EmptyModulesList, { webRoot: webRoot });
|
|
11
|
+
}
|
|
12
|
+
return (_jsx("ul", { children: moduleNames.map(moduleName => (_jsx(ModuleLinkInLI, { moduleName: moduleName }, moduleName))) }));
|
|
13
|
+
}
|
|
14
|
+
export default ModulesList;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
function EmptyPartialsList({ webRoot }) {
|
|
3
|
+
return (_jsxs("p", { children: ["No partials in ", _jsxs("code", { children: [webRoot, "components/partials"] })] }));
|
|
4
|
+
}
|
|
5
|
+
function PartialLinkInLI({ partialName }) {
|
|
6
|
+
return (_jsx("li", { children: _jsx("a", { href: `/partial/${partialName}`, children: partialName }) }));
|
|
7
|
+
}
|
|
8
|
+
export default function PartialsList({ webRoot, partialNames }) {
|
|
9
|
+
if (partialNames.length === 0) {
|
|
10
|
+
return _jsx(EmptyPartialsList, { webRoot: webRoot });
|
|
11
|
+
}
|
|
12
|
+
return (_jsx("ul", { children: partialNames.map(partialName => (_jsx(PartialLinkInLI, { partialName: partialName }, partialName))) }));
|
|
13
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import { normalizePath } from 'vite';
|
|
4
|
+
import createDevServerRoutes from './routes/createDevServerRoutes.js';
|
|
5
|
+
import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
|
|
6
|
+
import createViteDevServer from './createViteDevServer.js';
|
|
7
|
+
import { getEnv, getAccountId, loadConfig, validateConfig, } from '@hubspot/cli-lib/lib/config.js';
|
|
8
|
+
const BASE_PATH = '/';
|
|
9
|
+
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
|
|
10
|
+
async function createDevServer(webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption) {
|
|
11
|
+
console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
|
|
12
|
+
let authedPortalId = null;
|
|
13
|
+
let authedEnv = null;
|
|
14
|
+
if (hubspotCliConfigPathOption && hubspotCliAccountNameOption) {
|
|
15
|
+
console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration at: ${hubspotCliConfigPathOption}`);
|
|
16
|
+
}
|
|
17
|
+
else if (hubspotCliConfigPathOption) {
|
|
18
|
+
console.log(`Loading HS auth configuration at: ${hubspotCliConfigPathOption}`);
|
|
19
|
+
}
|
|
20
|
+
else if (hubspotCliAccountNameOption) {
|
|
21
|
+
console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration.`);
|
|
22
|
+
}
|
|
23
|
+
// If a custom hubspot.config.yaml config path was set, make sure to force load that before
|
|
24
|
+
// any hs config values are read
|
|
25
|
+
loadConfig(hubspotCliConfigPathOption || null, { useEnv: false });
|
|
26
|
+
if (validateConfig()) {
|
|
27
|
+
authedPortalId = getAccountId(hubspotCliAccountNameOption);
|
|
28
|
+
authedEnv = getEnv(hubspotCliAccountNameOption);
|
|
29
|
+
if (!authedPortalId && hubspotCliAccountNameOption) {
|
|
30
|
+
console.error(`Couldn't find ${hubspotCliAccountNameOption} in your hubspot.config.yaml`);
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
console.warn(`Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).
|
|
36
|
+
If needed you can refer to another config file with --config.
|
|
37
|
+
|
|
38
|
+
Local proxy functionality will not work without setting up authentication.`);
|
|
39
|
+
}
|
|
40
|
+
const expressServer = express();
|
|
41
|
+
const viteServer = await createViteDevServer();
|
|
42
|
+
const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
|
|
43
|
+
const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
|
|
44
|
+
expressServer.locals.devServerHost = 'localhost';
|
|
45
|
+
expressServer.locals.devServerPort = PORT;
|
|
46
|
+
expressServer.locals.webRoot = webRoot;
|
|
47
|
+
expressServer.locals.viteServer = viteServer;
|
|
48
|
+
expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
|
|
49
|
+
expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
|
|
50
|
+
expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer));
|
|
51
|
+
expressServer.listen(PORT);
|
|
52
|
+
let extraServerInfo = '';
|
|
53
|
+
if (authedPortalId) {
|
|
54
|
+
extraServerInfo += `, hubid=${authedPortalId}`;
|
|
55
|
+
}
|
|
56
|
+
if (authedEnv && authedEnv !== 'prod') {
|
|
57
|
+
extraServerInfo += `, env=${authedEnv}`;
|
|
58
|
+
}
|
|
59
|
+
console.log(`
|
|
60
|
+
HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at http://localhost:${PORT}${extraServerInfo})
|
|
61
|
+
`);
|
|
62
|
+
}
|
|
63
|
+
export default createDevServer;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createServer as createViteServer } from 'vite';
|
|
2
|
+
import { default as react } from '@vitejs/plugin-react';
|
|
3
|
+
import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
|
|
4
|
+
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
|
|
5
|
+
async function createViteDevServer() {
|
|
6
|
+
return createViteServer({
|
|
7
|
+
appType: 'custom',
|
|
8
|
+
server: {
|
|
9
|
+
middlewareMode: true,
|
|
10
|
+
origin: `http://localhost:${PORT}`,
|
|
11
|
+
},
|
|
12
|
+
ssr: {
|
|
13
|
+
// TODO: might need more entries here to get things to resolve through
|
|
14
|
+
// resolveWebRootDepsPlugin
|
|
15
|
+
noExternal: '@hubspot/cms-components',
|
|
16
|
+
},
|
|
17
|
+
resolve: {
|
|
18
|
+
dedupe: ['react', 'react-dom', '@hubspot/cms-components'],
|
|
19
|
+
},
|
|
20
|
+
optimizeDeps: {
|
|
21
|
+
include: ['react', 'react-dom', 'react-dom/client'],
|
|
22
|
+
},
|
|
23
|
+
plugins: [react(), resolveIslandPlugin()],
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
export default createViteDevServer;
|
package/dist/lib/cli.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { resolve } from 'path';
|
|
2
|
+
export function getDevServerCommandLineOptions(argv) {
|
|
3
|
+
const args = [...argv];
|
|
4
|
+
const webRoot = args[2];
|
|
5
|
+
let hubspotCliConfigPathOption;
|
|
6
|
+
let hubspotCliAccountNameOption;
|
|
7
|
+
// Very basic CLI option parsing
|
|
8
|
+
const configOptionIndex = args.findIndex(arg => arg === '-c' || arg === '--config');
|
|
9
|
+
if (configOptionIndex > 0 && args.length > configOptionIndex) {
|
|
10
|
+
hubspotCliConfigPathOption = resolve(args[configOptionIndex + 1]);
|
|
11
|
+
args.splice(configOptionIndex, 2);
|
|
12
|
+
}
|
|
13
|
+
const accountOptionIndex = args.findIndex(arg => arg === '-a' || arg === '--account');
|
|
14
|
+
if (accountOptionIndex > 0 && args.length > accountOptionIndex) {
|
|
15
|
+
hubspotCliAccountNameOption = args[accountOptionIndex + 1];
|
|
16
|
+
args.splice(accountOptionIndex, 2);
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
webRoot,
|
|
20
|
+
hubspotCliConfigPathOption,
|
|
21
|
+
hubspotCliAccountNameOption,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const rewriteAbsoluteJsAndCssPaths = (body, host, protocol = 'https://') => {
|
|
2
|
+
// TODO, do we need to worry about any fully relative references? (./whatever/...)
|
|
3
|
+
// Maybe the renderer doesn't typically output those, and when customers do that manually
|
|
4
|
+
// it (probably?) is after the `<base>` element?
|
|
5
|
+
return body.replace(/(src|href)="(\/[^/])/g, `$1="${protocol}${host}$2`);
|
|
6
|
+
};
|
|
7
|
+
export const addBaseTag = (html, urlToProxy) => {
|
|
8
|
+
const baseDomain = new URL(urlToProxy).origin;
|
|
9
|
+
return html.replace('<head>', `<head>\n<base href="${baseDomain}">\n`);
|
|
10
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable consistent-return */
|
|
3
|
+
import { COMPONENT_EXTENSIONS } from '@hubspot/cms-js-internal';
|
|
4
|
+
export const findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
|
|
5
|
+
for (const extension of COMPONENT_EXTENSIONS) {
|
|
6
|
+
const pathToTry = `${modulePathNoExtension}${extension}`;
|
|
7
|
+
if (moduleGraph.fileToModulesMap.has(pathToTry)) {
|
|
8
|
+
return pathToTry;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable consistent-return */
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import { resolve } from 'path';
|
|
5
|
+
const localJsRenderStartString = '<!-- proxy local render of "';
|
|
6
|
+
// const localJsRenderStartRegex = /<!-- proxy local render of "([^"]+)"/;
|
|
7
|
+
const localJsRenderEndString = 'end proxy local render -->';
|
|
8
|
+
export const findLocalRenderPlaceholders = (body) => {
|
|
9
|
+
let offsetSoFar = 0;
|
|
10
|
+
const result = [];
|
|
11
|
+
while (offsetSoFar < body.length && offsetSoFar !== -1) {
|
|
12
|
+
// Get start of local render block
|
|
13
|
+
const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
|
|
14
|
+
offsetSoFar = startOffset;
|
|
15
|
+
if (startOffset >= 0) {
|
|
16
|
+
const nextNewlineOffset = body.indexOf('\n', startOffset + localJsRenderStartString.length);
|
|
17
|
+
const pathEndOffset = body.indexOf('"', startOffset + localJsRenderStartString.length);
|
|
18
|
+
const nearestNewlineOrQuoteAfterBlockOpen = Math.min(nextNewlineOffset, pathEndOffset);
|
|
19
|
+
// Keep on moving our "where we've scanned so far" pointer
|
|
20
|
+
offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
|
|
21
|
+
if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
|
|
22
|
+
// Pull the path out of double quotes after the block opening
|
|
23
|
+
const path = body.substring(startOffset + localJsRenderStartString.length, pathEndOffset);
|
|
24
|
+
offsetSoFar = pathEndOffset + 1;
|
|
25
|
+
// console.log(`${startOffset}: path = ${path}`);
|
|
26
|
+
// If we're in a valid bloc so far that exists and has a path...
|
|
27
|
+
if (startOffset >= 0 && path) {
|
|
28
|
+
const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);
|
|
29
|
+
const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
|
|
30
|
+
offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
|
|
31
|
+
// Make sure that there is an ending to the block and there is not another
|
|
32
|
+
// HTML end comment string before it
|
|
33
|
+
if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
|
|
34
|
+
// Then pull out the JSON in the middle and try to parse it
|
|
35
|
+
const jsonString = body
|
|
36
|
+
.substring(pathEndOffset + 1, endOffset)
|
|
37
|
+
.trim();
|
|
38
|
+
// console.log(`${endOffset}: jsonString = ${jsonString}`);
|
|
39
|
+
try {
|
|
40
|
+
const json = JSON.parse(jsonString);
|
|
41
|
+
result.push({
|
|
42
|
+
startOffset,
|
|
43
|
+
endOffset: endOffset + localJsRenderEndString.length,
|
|
44
|
+
path,
|
|
45
|
+
json,
|
|
46
|
+
});
|
|
47
|
+
offsetSoFar = endOffset + localJsRenderEndString.length;
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
console.error(`Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`);
|
|
51
|
+
offsetSoFar = endOffset;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
};
|
|
60
|
+
const getHSProjectConfig = hsProjectConfigPath => {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(fs.readFileSync(hsProjectConfigPath, 'utf8'));
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
console.warn(`Missing hsproject.json file (${resolve(hsProjectConfigPath)}): `, e.message);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
export const getProjectNameFromHSConfig = hsProjectConfigPath => {
|
|
69
|
+
return getHSProjectConfig(hsProjectConfigPath).name;
|
|
70
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { findLocalRenderPlaceholders } from './proxyHelpers.js';
|
|
3
|
+
describe('proxyHelpers', () => {
|
|
4
|
+
describe('findLocalRenderPlaceholders', () => {
|
|
5
|
+
it('should do nothing with an empty string', () => {
|
|
6
|
+
const result = findLocalRenderPlaceholders('');
|
|
7
|
+
expect(result).toEqual([]);
|
|
8
|
+
});
|
|
9
|
+
it('should do nothing with a regular HTML comment', () => {
|
|
10
|
+
const result = findLocalRenderPlaceholders('<!-- -->');
|
|
11
|
+
expect(result).toEqual([]);
|
|
12
|
+
});
|
|
13
|
+
it('should do nothing with a regular HTML comment across newlines', () => {
|
|
14
|
+
const result = findLocalRenderPlaceholders(`<!--
|
|
15
|
+
-->`);
|
|
16
|
+
expect(result).toEqual([]);
|
|
17
|
+
});
|
|
18
|
+
it('should do nothing with a never ending HTML comment', () => {
|
|
19
|
+
const result = findLocalRenderPlaceholders(`<!--`);
|
|
20
|
+
expect(result).toEqual([]);
|
|
21
|
+
});
|
|
22
|
+
it('extracts placeholder with nothing before or after it', () => {
|
|
23
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
24
|
+
{
|
|
25
|
+
"the": "props",
|
|
26
|
+
"that": ["need", "to"],
|
|
27
|
+
"be": {
|
|
28
|
+
"passed": "along"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
end proxy local render -->`);
|
|
32
|
+
expect(result.length).toBe(1);
|
|
33
|
+
expect(result[0]).toMatchSnapshot();
|
|
34
|
+
});
|
|
35
|
+
it('extracts placeholder with some HTML around it', () => {
|
|
36
|
+
const result = findLocalRenderPlaceholders(`
|
|
37
|
+
<p>asdf</p>
|
|
38
|
+
<div>
|
|
39
|
+
<!-- proxy local render of "/some/path/to/entry.js"
|
|
40
|
+
{
|
|
41
|
+
"the": "props",
|
|
42
|
+
"that": ["need", "to"],
|
|
43
|
+
"be": {
|
|
44
|
+
"passed": "along"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
end proxy local render -->
|
|
48
|
+
</div>
|
|
49
|
+
|
|
50
|
+
<em>FIN</em>
|
|
51
|
+
`);
|
|
52
|
+
expect(result.length).toBe(1);
|
|
53
|
+
expect(result[0]).toMatchSnapshot();
|
|
54
|
+
});
|
|
55
|
+
it('extacts two placholder blocks immediately after one another', () => {
|
|
56
|
+
const result = findLocalRenderPlaceholders(`<p>asdf</p>
|
|
57
|
+
<div>
|
|
58
|
+
<!-- proxy local render of "/some/path/to/entry.js"
|
|
59
|
+
{
|
|
60
|
+
"the": "props",
|
|
61
|
+
"that": ["need", "to"],
|
|
62
|
+
"be": {
|
|
63
|
+
"passed": "along"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
end proxy local render --><!-- proxy local render of "/some/path/to/entry2.js"
|
|
67
|
+
{
|
|
68
|
+
"the": "props22222",
|
|
69
|
+
"that": ["need", "to"],
|
|
70
|
+
"be": {
|
|
71
|
+
"passed": "along"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
end proxy local render -->
|
|
75
|
+
</div>
|
|
76
|
+
|
|
77
|
+
<em>FIN</em>
|
|
78
|
+
`);
|
|
79
|
+
expect(result.length).toBe(2);
|
|
80
|
+
expect(result[0]).toMatchSnapshot();
|
|
81
|
+
expect(result[1]).toMatchSnapshot();
|
|
82
|
+
});
|
|
83
|
+
it('extacts a placeholder with empty json', () => {
|
|
84
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
85
|
+
{
|
|
86
|
+
}
|
|
87
|
+
end proxy local render -->`);
|
|
88
|
+
expect(result.length).toBe(1);
|
|
89
|
+
expect(result[0]).toMatchSnapshot();
|
|
90
|
+
});
|
|
91
|
+
it('extacts a placeholder with empty json - 2', () => {
|
|
92
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
93
|
+
{}
|
|
94
|
+
end proxy local render -->`);
|
|
95
|
+
expect(result.length).toBe(1);
|
|
96
|
+
expect(result[0]).toMatchSnapshot();
|
|
97
|
+
});
|
|
98
|
+
it('extacts one placholder after a broken incomplete path', () => {
|
|
99
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "incomplete path
|
|
100
|
+
-->
|
|
101
|
+
<!-- proxy local render of "/some/path/to/afterMissingPath.js"
|
|
102
|
+
{
|
|
103
|
+
}
|
|
104
|
+
end proxy local render -->`);
|
|
105
|
+
expect(result.length).toBe(1);
|
|
106
|
+
expect(result[0]).toMatchSnapshot();
|
|
107
|
+
});
|
|
108
|
+
it('extacts one placholder after a uncompleted regular HTML comment', () => {
|
|
109
|
+
const result = findLocalRenderPlaceholders(`<!-- WHATEVER
|
|
110
|
+
-->
|
|
111
|
+
<!-- proxy local render of "/some/path/to/afterBustedHtmlComment.js"
|
|
112
|
+
{
|
|
113
|
+
}
|
|
114
|
+
end proxy local render -->`);
|
|
115
|
+
expect(result.length).toBe(1);
|
|
116
|
+
expect(result[0]).toMatchSnapshot();
|
|
117
|
+
});
|
|
118
|
+
it('extacts one placeholder after one with broken missing json', () => {
|
|
119
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "path/Before/missingJson"
|
|
120
|
+
-->
|
|
121
|
+
<!-- proxy local render of "/some/path/to/afterMissingJson.js"
|
|
122
|
+
{
|
|
123
|
+
}
|
|
124
|
+
end proxy local render -->`);
|
|
125
|
+
expect(result.length).toBe(1);
|
|
126
|
+
expect(result[0]).toMatchSnapshot();
|
|
127
|
+
});
|
|
128
|
+
it('does not extact broken placeholder with invalid json', () => {
|
|
129
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
130
|
+
Invalid json
|
|
131
|
+
}
|
|
132
|
+
end proxy local render -->`);
|
|
133
|
+
expect(result).toEqual([]);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
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, renderContext } = 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, renderContext };
|
|
25
|
+
}
|
|
26
|
+
export default renderComponentWithCSS;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
function getByteSizeOf(props) {
|
|
2
|
+
return Buffer.from(JSON.stringify(props)).length;
|
|
3
|
+
}
|
|
4
|
+
function formatBytesToString(bytes) {
|
|
5
|
+
if (bytes > 1000000) {
|
|
6
|
+
// If byte size is > 1mb, show size in red
|
|
7
|
+
return ['\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`];
|
|
8
|
+
}
|
|
9
|
+
else if (bytes > 10000) {
|
|
10
|
+
// if byte size is between 10kb and 1mb, show size in yellow
|
|
11
|
+
return ['\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`];
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
// Show size in green
|
|
15
|
+
return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const getPropsInfo = (props, reportOptions = { showNestedKeySizeIfGreater: null }, recursionDepth = 0) => {
|
|
19
|
+
if (recursionDepth > 8) {
|
|
20
|
+
return [];
|
|
21
|
+
}
|
|
22
|
+
const propsSizeInBytes = getByteSizeOf(props);
|
|
23
|
+
const result = formatBytesToString(propsSizeInBytes);
|
|
24
|
+
if (!Array.isArray(props) &&
|
|
25
|
+
Object.keys(props).length > 0 &&
|
|
26
|
+
reportOptions.showNestedKeySizeIfGreater != null &&
|
|
27
|
+
propsSizeInBytes > reportOptions.showNestedKeySizeIfGreater) {
|
|
28
|
+
for (const [key, value] of Object.entries(props)) {
|
|
29
|
+
const size = getPropsInfo(value, reportOptions, recursionDepth + 1);
|
|
30
|
+
if (Array.isArray(value)) {
|
|
31
|
+
result.push('\n', `${key}[${value.length}]`, ...size);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
result.push('\n', key, ...size);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return result.flat();
|
|
39
|
+
};
|
|
40
|
+
export const logPartialInfo = (partialPath, props) => {
|
|
41
|
+
console.log('Rendering partial', partialPath);
|
|
42
|
+
console.group();
|
|
43
|
+
console.log('Props size: ', ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 }));
|
|
44
|
+
console.groupEnd();
|
|
45
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { join as joinPosix } from 'path/posix';
|
|
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 = joinPosix(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, fieldOverrides = {}, pageUrl) {
|
|
21
|
+
console.log('Rendering module', requestedModulePath);
|
|
22
|
+
let componentModule;
|
|
23
|
+
let foundPath;
|
|
24
|
+
if (!hasComponentExtension(requestedModulePath)) {
|
|
25
|
+
[componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
|
|
26
|
+
}
|
|
27
|
+
if (!componentModule) {
|
|
28
|
+
// Look for non-folder module
|
|
29
|
+
componentModule = await viteServer.ssrLoadModule(requestedModulePath);
|
|
30
|
+
foundPath = componentModule ? requestedModulePath : undefined;
|
|
31
|
+
}
|
|
32
|
+
if (!componentModule) {
|
|
33
|
+
throw new Error(`Couldn't find module: ${requestedModulePath}`);
|
|
34
|
+
}
|
|
35
|
+
const Component = componentModule.Component;
|
|
36
|
+
const fields = componentModule.fields;
|
|
37
|
+
const meta = componentModule.meta;
|
|
38
|
+
if (!Component) {
|
|
39
|
+
throw new Error(`Module does not have a named Component export: ${foundPath}`);
|
|
40
|
+
}
|
|
41
|
+
else if (!fields) {
|
|
42
|
+
throw new Error(`Module does not have a named fields export: ${foundPath}`);
|
|
43
|
+
}
|
|
44
|
+
else if (!meta) {
|
|
45
|
+
throw new Error(`Module does not have a named meta export: ${foundPath}`);
|
|
46
|
+
}
|
|
47
|
+
const fieldsJSON = renderFieldsToJson(fields);
|
|
48
|
+
const props = getPropsForModule(fieldsJSON, fieldOverrides);
|
|
49
|
+
return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl);
|
|
50
|
+
}
|
|
51
|
+
// TODO, move to cms-js-internal?
|
|
52
|
+
function setInHelper(object, nestedKeysArray, value) {
|
|
53
|
+
let curr = object;
|
|
54
|
+
const finalKey = nestedKeysArray.pop();
|
|
55
|
+
for (let index = 0; index < nestedKeysArray.length; index++) {
|
|
56
|
+
const currentKey = nestedKeysArray[index];
|
|
57
|
+
const nextKey = nestedKeysArray[index + 1];
|
|
58
|
+
if (Number.isInteger(nextKey) || (!nextKey && Number.isInteger(finalKey))) {
|
|
59
|
+
if (curr[currentKey] === undefined) {
|
|
60
|
+
curr[currentKey] = [];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (curr[currentKey] === undefined) {
|
|
64
|
+
curr[currentKey] = {};
|
|
65
|
+
}
|
|
66
|
+
curr = curr[currentKey];
|
|
67
|
+
}
|
|
68
|
+
curr[finalKey] = value;
|
|
69
|
+
}
|
|
70
|
+
function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
|
|
71
|
+
const props = {};
|
|
72
|
+
traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
|
|
73
|
+
setInHelper(props, fieldPathArray, value);
|
|
74
|
+
});
|
|
75
|
+
return props;
|
|
76
|
+
}
|
|
77
|
+
// TODO, move to cms-js-internal? (also in resolveModulesPlugin.ts)
|
|
78
|
+
function renderFieldsToJson(fields) {
|
|
79
|
+
let moduleJson;
|
|
80
|
+
const outputCallback = callbackJson => {
|
|
81
|
+
moduleJson = callbackJson;
|
|
82
|
+
};
|
|
83
|
+
renderToStaticMarkup(cloneElement(fields, {
|
|
84
|
+
outputCallback,
|
|
85
|
+
}));
|
|
86
|
+
return moduleJson;
|
|
87
|
+
}
|
|
88
|
+
export default renderModule;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import renderComponentWithCSS from './renderComponentWithCSS.js';
|
|
2
|
+
import { logPartialInfo } from './renderHelpers.js';
|
|
3
|
+
async function renderPartial(viteServer, partialPath, props, pageUrl) {
|
|
4
|
+
logPartialInfo(partialPath, props);
|
|
5
|
+
const componentModule = await viteServer.ssrLoadModule(partialPath);
|
|
6
|
+
const Component = componentModule.default;
|
|
7
|
+
if (!componentModule) {
|
|
8
|
+
throw new Error(`Couldn't find partial: ${partialPath}`);
|
|
9
|
+
}
|
|
10
|
+
return renderComponentWithCSS(viteServer, partialPath, Component, props, pageUrl);
|
|
11
|
+
}
|
|
12
|
+
export default renderPartial;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-shadow */
|
|
3
|
+
import { promises as fsPromises } from 'fs';
|
|
4
|
+
import { createIslandsGlobalJsForClientInDev, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
|
|
5
|
+
const { readFile } = fsPromises;
|
|
6
|
+
const ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK = `<script type="module">
|
|
7
|
+
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
|
|
8
|
+
setupIslandHydration();
|
|
9
|
+
</script>
|
|
10
|
+
`;
|
|
11
|
+
const createdPlainHtmlTemplate = async (baseTemplatePath, title) => {
|
|
12
|
+
const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
|
|
13
|
+
return htmlTemplateBase.replace('<!--title-->', title);
|
|
14
|
+
};
|
|
15
|
+
const createIslandHtmlTemplate = async (baseTemplatePath, title) => {
|
|
16
|
+
let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
|
|
17
|
+
htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
|
|
18
|
+
${ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK}
|
|
19
|
+
<!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
|
|
20
|
+
<!--islandsglobal-->
|
|
21
|
+
`);
|
|
22
|
+
return htmlTemplate;
|
|
23
|
+
};
|
|
24
|
+
export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer) => {
|
|
25
|
+
let htmlTemplate;
|
|
26
|
+
if (renderContext.islands.length) {
|
|
27
|
+
htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title);
|
|
28
|
+
htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
|
|
29
|
+
${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
|
|
30
|
+
</script>
|
|
31
|
+
${getServerGlobalsToInject(renderContext.pageUrl)}
|
|
32
|
+
`);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
|
|
36
|
+
}
|
|
37
|
+
return viteServer.transformIndexHtml(url, htmlTemplate);
|
|
38
|
+
};
|
|
39
|
+
export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, devServerHost, devServerPort) => {
|
|
40
|
+
const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
|
|
41
|
+
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
42
|
+
const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
43
|
+
let islandRuntimeScript = await viteServer.transformIndexHtml('/', ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK);
|
|
44
|
+
islandRuntimeScript = islandRuntimeScript.replace('import RefreshRuntime from "/@react-refresh"', `import RefreshRuntime from "http://${serverDomainAndPort}/@react-refresh"`);
|
|
45
|
+
return `${islandRuntimeScript}
|
|
46
|
+
<script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
|
|
47
|
+
`;
|
|
48
|
+
};
|