@hubspot/cms-dev-server 1.1.0-prerelease.7 → 1.1.0-prerelease.9
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/createIslandsGlobalJsForClientInDev.js +32 -0
- package/dist/lib/renderHelpers.js +34 -10
- package/dist/lib/traverseFieldsJson.js +78 -0
- package/dist/render/renderOnServer.js +40 -0
- package/dist/render/renderOnServer.test.js +24 -0
- package/dist/render/renderStreamToPromise.js +35 -0
- package/dist/resolveSharedDeps.js +28 -0
- package/dist/routes/module.js +2 -1
- package/dist/routes/partial.js +2 -1
- package/package.json +4 -4
- package/dist/plugins/devMockClientEntryPlugin.js +0 -52
- 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
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
|
|
2
|
+
const indentString = new Array(indent).fill(' ').join('');
|
|
3
|
+
return `window.__islands = ${JSON.stringify(tweakedIslandsArray.map(({ id, moduleName, moduleId, props, hydrateOn, clientOnly, priority, url, }) => {
|
|
4
|
+
return {
|
|
5
|
+
id,
|
|
6
|
+
moduleName,
|
|
7
|
+
moduleId,
|
|
8
|
+
props,
|
|
9
|
+
hydrateOn,
|
|
10
|
+
clientOnly,
|
|
11
|
+
priority,
|
|
12
|
+
url,
|
|
13
|
+
};
|
|
14
|
+
}), null, 2).replace(/\n/gm, `\n${indentString}`)};`;
|
|
15
|
+
};
|
|
16
|
+
function getIslandUrls(roots, viteDevServer) {
|
|
17
|
+
return roots.map(island => {
|
|
18
|
+
const islandModule = viteDevServer.moduleGraph.getModuleById(island.moduleId);
|
|
19
|
+
if (!islandModule) {
|
|
20
|
+
throw new Error(`Unknown island moduleId: ${island.moduleId}`);
|
|
21
|
+
}
|
|
22
|
+
const tweakedIsland = {
|
|
23
|
+
...island,
|
|
24
|
+
url: islandModule.url,
|
|
25
|
+
};
|
|
26
|
+
return tweakedIsland;
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export const createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
|
|
30
|
+
// Assuming island roots have already been sorted before being passed in here
|
|
31
|
+
return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
|
|
32
|
+
};
|
|
@@ -1,21 +1,45 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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`];
|
|
6
8
|
}
|
|
7
|
-
else if (
|
|
8
|
-
// if
|
|
9
|
-
return ['\x1b[33m', `${(
|
|
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`];
|
|
10
12
|
}
|
|
11
13
|
else {
|
|
12
14
|
// Show size in green
|
|
13
|
-
return ['\x1b[32m', `${(
|
|
15
|
+
return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`];
|
|
14
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();
|
|
15
39
|
};
|
|
16
40
|
export const logPartialInfo = (partialPath, props) => {
|
|
17
41
|
console.log('Rendering partial', partialPath);
|
|
18
42
|
console.group();
|
|
19
|
-
console.log('Props size: ', ...getPropsInfo(props));
|
|
43
|
+
console.log('Props size: ', ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 }));
|
|
20
44
|
console.groupEnd();
|
|
21
45
|
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const traverseFieldsJSONHelper = (fields, values, handle, path // Number path elements are for repeaters
|
|
2
|
+
) => {
|
|
3
|
+
if (!fields) {
|
|
4
|
+
return;
|
|
5
|
+
}
|
|
6
|
+
for (const field of fields) {
|
|
7
|
+
let value = values ? values[field.name] : undefined;
|
|
8
|
+
if (value === undefined) {
|
|
9
|
+
value = getDefaultValue(field);
|
|
10
|
+
}
|
|
11
|
+
if (field.occurrence) {
|
|
12
|
+
if (Array.isArray(value)) {
|
|
13
|
+
value.forEach((v, i) => {
|
|
14
|
+
handle([...path, field.name, i], v, field);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
else if (field.type === 'group') {
|
|
19
|
+
traverseFieldsJSONHelper(field.children, value, handle, [
|
|
20
|
+
...path,
|
|
21
|
+
field.name,
|
|
22
|
+
]);
|
|
23
|
+
}
|
|
24
|
+
else if (value !== undefined) {
|
|
25
|
+
handle([...path, field.name], value, field);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const traverseFieldsJSON = (fields, values, handle) => {
|
|
30
|
+
return traverseFieldsJSONHelper(fields, values, handle, []);
|
|
31
|
+
};
|
|
32
|
+
const getDefaultValue = (field) => {
|
|
33
|
+
if (field.type === 'group') {
|
|
34
|
+
if (field.occurrence) {
|
|
35
|
+
const count = field.occurrence.default || field.occurrence.min;
|
|
36
|
+
return new Array(count).fill(field.default[0]);
|
|
37
|
+
}
|
|
38
|
+
const result = {};
|
|
39
|
+
for (const childField of field.children) {
|
|
40
|
+
if (childField.type !== 'group' && childField.default) {
|
|
41
|
+
result[childField.name] = getDefaultValue(childField);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
else if (field.occurrence) {
|
|
47
|
+
const scalarValue = getDefaultScalarValue(field);
|
|
48
|
+
const count = field.occurrence.default || field.occurrence.min;
|
|
49
|
+
return new Array(count).fill(scalarValue);
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
return field.default;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
// If occurrence.default is set, then default value could be an array
|
|
56
|
+
// and we just want to grab the scalar value from that array
|
|
57
|
+
function getDefaultScalarValue(field) {
|
|
58
|
+
if (Array.isArray(field.default)) {
|
|
59
|
+
const firstValue = field.default[0];
|
|
60
|
+
// email field values are arrays of strings (email addresses)
|
|
61
|
+
// so check if it's an array of arrays
|
|
62
|
+
if (valueIsArray(field)) {
|
|
63
|
+
return Array.isArray(firstValue) ? firstValue : field.default;
|
|
64
|
+
}
|
|
65
|
+
return firstValue;
|
|
66
|
+
}
|
|
67
|
+
return field.default;
|
|
68
|
+
}
|
|
69
|
+
const CHOICE_FIELD_TYPE = 'choice';
|
|
70
|
+
const EMAIL_FIELD_TYPE = 'email';
|
|
71
|
+
const SIMPLE_MENU_FIELD_TYPE = 'simple_menu';
|
|
72
|
+
// Stolen from https://git.hubteam.com/HubSpot/ContentUILib/blob/ede7354d6265d7976c29bc55b692602885c28c96/ContentUtils/static/js/helpers/FieldHelpers.js#L56
|
|
73
|
+
function valueIsArray(field) {
|
|
74
|
+
return (field.type === EMAIL_FIELD_TYPE ||
|
|
75
|
+
field.type === SIMPLE_MENU_FIELD_TYPE ||
|
|
76
|
+
(field.type === CHOICE_FIELD_TYPE && field.multiple));
|
|
77
|
+
}
|
|
78
|
+
export default traverseFieldsJSON;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { renderStreamToPromise } from '@hubspot/cms-js-internal';
|
|
3
|
+
import { ServerRenderContext, createServerRenderContext, } from '@hubspot/cms-components';
|
|
4
|
+
// Slightly useful to have this so some files don't have to be tsx just to make
|
|
5
|
+
// the renderOnServer call (i.e. need JSX to do `<Component {...props} />`)
|
|
6
|
+
export async function renderComponentOnServer(Component, props, pageUrl) {
|
|
7
|
+
const componentDebugName = Component.displayName || Component.name;
|
|
8
|
+
return renderOnServer(_jsx(Component, { ...props }), pageUrl, componentDebugName);
|
|
9
|
+
}
|
|
10
|
+
export async function renderOnServer(elements, pageUrl, debugName) {
|
|
11
|
+
const renderContext = createServerRenderContext(pageUrl);
|
|
12
|
+
let html = await renderStreamToPromise(_jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }));
|
|
13
|
+
if (renderContext.messagesForBrowser.length > 0) {
|
|
14
|
+
html = `${html}${scriptTagToLogServerMessages(renderContext.messagesForBrowser, `Server messages rendering: ${debugName}`)}`;
|
|
15
|
+
}
|
|
16
|
+
return { html, renderContext };
|
|
17
|
+
}
|
|
18
|
+
function scriptTagToLogServerMessages(messagesForBrowser, groupLabel) {
|
|
19
|
+
if (!messagesForBrowser) {
|
|
20
|
+
return '';
|
|
21
|
+
}
|
|
22
|
+
const consoleLines = [];
|
|
23
|
+
for (const message of messagesForBrowser) {
|
|
24
|
+
const funcString = message.level === 'error' ? 'console.error' : 'console.warn';
|
|
25
|
+
const argString = message.parameters
|
|
26
|
+
.map(arg => JSON.stringify(arg))
|
|
27
|
+
.join(', ');
|
|
28
|
+
consoleLines.push(` ${funcString}(${argString});`);
|
|
29
|
+
}
|
|
30
|
+
let groupStart = '';
|
|
31
|
+
let groupEnd = '';
|
|
32
|
+
if (groupLabel !== null) {
|
|
33
|
+
groupStart = `\n console.group(${JSON.stringify(groupLabel)});`;
|
|
34
|
+
groupEnd = ` console.groupEnd()\n`;
|
|
35
|
+
}
|
|
36
|
+
return `<script>${groupStart}
|
|
37
|
+
${consoleLines.join('\n')}
|
|
38
|
+
${groupEnd}</script>
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { renderComponentOnServer, renderOnServer } from './renderOnServer.js';
|
|
4
|
+
import { getByText } from '@testing-library/dom';
|
|
5
|
+
import { JSDOM } from 'jsdom';
|
|
6
|
+
function TestComponent({ text }) {
|
|
7
|
+
return _jsx("div", { children: text });
|
|
8
|
+
}
|
|
9
|
+
describe('renderOnServer', () => {
|
|
10
|
+
it('should render elements', async () => {
|
|
11
|
+
const result = await renderOnServer(_jsx(TestComponent, { text: 'test' }), 'http://test.com', 'debug_name');
|
|
12
|
+
const dom = new JSDOM(result.html);
|
|
13
|
+
expect(getByText(dom.window.document.body, 'test')).toBeTruthy();
|
|
14
|
+
expect(result.renderContext.pageUrl).toBe('http://test.com');
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
describe('renderComponentOnServer', () => {
|
|
18
|
+
it('should render components', async () => {
|
|
19
|
+
const result = await renderComponentOnServer(TestComponent, { text: 'test' }, 'http://test.com');
|
|
20
|
+
const dom = new JSDOM(result.html);
|
|
21
|
+
expect(getByText(dom.window.document.body, 'test')).toBeTruthy();
|
|
22
|
+
expect(result.renderContext.pageUrl).toBe('http://test.com');
|
|
23
|
+
});
|
|
24
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import stream from 'stream';
|
|
2
|
+
import { renderToPipeableStream } from 'react-dom/server';
|
|
3
|
+
const promiseForNewWritableStream = () => {
|
|
4
|
+
const chunks = [];
|
|
5
|
+
const writableStream = new stream.Writable();
|
|
6
|
+
writableStream._write = (chunk, encoding, done) => {
|
|
7
|
+
chunks.push(Buffer.from(chunk));
|
|
8
|
+
done();
|
|
9
|
+
};
|
|
10
|
+
const streamDonePromise = new Promise((resolve, reject) => {
|
|
11
|
+
writableStream.on('error', error => {
|
|
12
|
+
reject(error);
|
|
13
|
+
});
|
|
14
|
+
writableStream._final = done => {
|
|
15
|
+
resolve(Buffer.concat(chunks).toString('utf8'));
|
|
16
|
+
done();
|
|
17
|
+
};
|
|
18
|
+
});
|
|
19
|
+
return { streamDonePromise, writableStream };
|
|
20
|
+
};
|
|
21
|
+
export const renderStreamToPromise = async (reactElements) => {
|
|
22
|
+
const { streamDonePromise, writableStream } = promiseForNewWritableStream();
|
|
23
|
+
const { pipe /* abort */ } = renderToPipeableStream(reactElements, {
|
|
24
|
+
onShellReady() {
|
|
25
|
+
// customOutputStream.write('<!-- After onCompleteShell -->\n');
|
|
26
|
+
},
|
|
27
|
+
onAllReady() {
|
|
28
|
+
pipe(writableStream);
|
|
29
|
+
},
|
|
30
|
+
// We will log the error sent to the writable, any need to do something in these callbacks?
|
|
31
|
+
// onShellError(error) {},
|
|
32
|
+
// onError(error) {},
|
|
33
|
+
});
|
|
34
|
+
return streamDonePromise;
|
|
35
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import enhancedResolve from 'enhanced-resolve';
|
|
2
|
+
import { cwd } from 'process';
|
|
3
|
+
/**
|
|
4
|
+
* Vite plugin that resolves dependencies to cms-js-platform over webRoot
|
|
5
|
+
* client build: resolve deps to cms-js-platform version
|
|
6
|
+
* server build: mark deps as external
|
|
7
|
+
*/
|
|
8
|
+
export default function resolveSharedDeps(absoluteWebRoot) {
|
|
9
|
+
console.log(absoluteWebRoot);
|
|
10
|
+
const sharedDeps = [
|
|
11
|
+
'@hubspot/cms-components',
|
|
12
|
+
'@hubspot/cms-js-internal',
|
|
13
|
+
'react',
|
|
14
|
+
'react-dom',
|
|
15
|
+
];
|
|
16
|
+
return {
|
|
17
|
+
name: 'resolve-shared-deps',
|
|
18
|
+
enforce: 'pre',
|
|
19
|
+
async resolveId(source, __importer, __options) {
|
|
20
|
+
if (sharedDeps.some(sharedDep => source.startsWith(sharedDep))) {
|
|
21
|
+
const resolvedSource = enhancedResolve.sync(cwd(), source);
|
|
22
|
+
console.log(`RESOLVING::: ${source} TO ${resolvedSource}`);
|
|
23
|
+
return { id: resolvedSource, external: 'relative' };
|
|
24
|
+
}
|
|
25
|
+
return Promise.resolve(null);
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
package/dist/routes/module.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import path from 'path';
|
|
2
|
+
import url from 'url';
|
|
2
3
|
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
3
4
|
import renderModule from '../lib/renderModule.js';
|
|
4
5
|
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
5
6
|
const moduleRouteHandler = async (request, response) => {
|
|
6
7
|
const { webRoot, viteServer } = request.app.locals;
|
|
7
8
|
const moduleName = request.params.moduleName;
|
|
8
|
-
const baseTemplatePath = path.join(import.meta.url
|
|
9
|
+
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
9
10
|
const modulePath = path.resolve(webRoot, 'components/modules/', moduleName);
|
|
10
11
|
try {
|
|
11
12
|
const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, null, fullOriginalUrlFromRequest(request));
|
package/dist/routes/partial.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import path from 'path';
|
|
2
|
+
import url from 'url';
|
|
2
3
|
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
3
4
|
import renderPartial from '../lib/renderPartial.js';
|
|
4
5
|
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
5
6
|
const partialRouteHandler = async (request, response) => {
|
|
6
7
|
const { webRoot, viteServer } = request.app.locals;
|
|
7
8
|
const partialName = request.params.partial;
|
|
8
|
-
const baseTemplatePath = path.join(import.meta.url
|
|
9
|
+
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
9
10
|
const partialPath = path.resolve(webRoot, 'components/partials/', partialName);
|
|
10
11
|
try {
|
|
11
12
|
const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hubspot/cms-dev-server",
|
|
3
|
-
"version": "1.1.0-prerelease.
|
|
3
|
+
"version": "1.1.0-prerelease.9",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/createViteDevServer.js",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@hubspot/cli-lib": "^3.0.12",
|
|
24
|
-
"@hubspot/cms-components": "^1.1.0-prerelease.
|
|
25
|
-
"@hubspot/cms-js-internal": "^1.1.0-prerelease.
|
|
24
|
+
"@hubspot/cms-components": "^1.1.0-prerelease.9",
|
|
25
|
+
"@hubspot/cms-js-internal": "^1.1.0-prerelease.9",
|
|
26
26
|
"@vitejs/plugin-react": "^2.0.0",
|
|
27
27
|
"ansi-to-html": "0.7.x",
|
|
28
28
|
"express": "^4.17.3",
|
|
@@ -64,5 +64,5 @@
|
|
|
64
64
|
"publishConfig": {
|
|
65
65
|
"access": "public"
|
|
66
66
|
},
|
|
67
|
-
"gitHead": "
|
|
67
|
+
"gitHead": "028b27c763f9c6f7ce36f17ab9abc980b506159d"
|
|
68
68
|
}
|
|
@@ -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) {
|
|
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
|
-
}
|
package/dist/routes/proxyPage.js
DELETED
|
@@ -1,205 +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 { createRenderInfoContext } from '@hubspot/cms-components';
|
|
5
|
-
import { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
|
|
6
|
-
import renderPartial from '../lib/renderPartial.js';
|
|
7
|
-
import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
|
|
8
|
-
import { rewriteAbsoluteJsAndCssPaths } from '../lib/htmlHelpers.js';
|
|
9
|
-
const fetchPreviewInfo = async (accountId, portalId, contentId) => {
|
|
10
|
-
try {
|
|
11
|
-
// Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
|
|
12
|
-
const content = await hsGet(accountId, {
|
|
13
|
-
uri: `/content/api/v4/contents/${contentId}`,
|
|
14
|
-
query: { portalId },
|
|
15
|
-
json: true,
|
|
16
|
-
});
|
|
17
|
-
return {
|
|
18
|
-
previewDomain: content.previewDomain ?? content.resolvedDomain,
|
|
19
|
-
previewKey: content.previewKey,
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
catch (error) {
|
|
23
|
-
console.log(`error`, error);
|
|
24
|
-
if (error.options) {
|
|
25
|
-
console.log(`error.options`, error.options);
|
|
26
|
-
}
|
|
27
|
-
if (error.response && error.response.headers) {
|
|
28
|
-
console.log(`error.response.headers`, error.response.headers);
|
|
29
|
-
}
|
|
30
|
-
throw error;
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
const createPreviewQueryParams = (previewInfo) => {
|
|
34
|
-
const { previewKey } = previewInfo;
|
|
35
|
-
return {
|
|
36
|
-
_preview: true,
|
|
37
|
-
preview_key: previewKey,
|
|
38
|
-
};
|
|
39
|
-
};
|
|
40
|
-
const createPreviewPath = (contentId) => {
|
|
41
|
-
return `/_hcms/preview/content/${contentId}`;
|
|
42
|
-
};
|
|
43
|
-
const makeProxyPreviewRequest = (accountId, host, path, queryParams) => {
|
|
44
|
-
console.log(`Proxying request to https://${host}${path}`);
|
|
45
|
-
const result = hsGet(accountId, {
|
|
46
|
-
baseUrl: `https://${host}`,
|
|
47
|
-
uri: `${path}`,
|
|
48
|
-
query: {
|
|
49
|
-
...queryParams,
|
|
50
|
-
// Makes render_js_partial return comments instead of actually rendering
|
|
51
|
-
hsLocalProxy: true,
|
|
52
|
-
},
|
|
53
|
-
json: false,
|
|
54
|
-
});
|
|
55
|
-
console.log('hsGet', `https://${host}${path}`, queryParams);
|
|
56
|
-
return result.catch((error) => {
|
|
57
|
-
if (error.statusCode >= 400 &&
|
|
58
|
-
error.statusCode < 500 &&
|
|
59
|
-
!!error.response.body) {
|
|
60
|
-
return error.response.body;
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
throw error;
|
|
64
|
-
}
|
|
65
|
-
});
|
|
66
|
-
};
|
|
67
|
-
const createLocalJsRenderErrorOutput = (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
|
|
68
|
-
const randomStringWithLotsOf = (char, maxLength) => {
|
|
69
|
-
return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
|
|
70
|
-
};
|
|
71
|
-
const fakeRenderJsComponent = (indexForThisRender) => {
|
|
72
|
-
return new Promise((resolve, reject) => {
|
|
73
|
-
const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
|
|
74
|
-
setTimeout(() => {
|
|
75
|
-
try {
|
|
76
|
-
const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
|
|
77
|
-
resolve({
|
|
78
|
-
html: fakeJsRenderedOutput,
|
|
79
|
-
cssNeeded: '',
|
|
80
|
-
renderInfoContext: createRenderInfoContext(),
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
catch (e) {
|
|
84
|
-
console.log('Error with JS render...');
|
|
85
|
-
console.error(e);
|
|
86
|
-
reject();
|
|
87
|
-
}
|
|
88
|
-
}, randomTimeout);
|
|
89
|
-
});
|
|
90
|
-
};
|
|
91
|
-
const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer) => {
|
|
92
|
-
if (localRenderPlaceholder.path.startsWith('/fake/path/to/')) {
|
|
93
|
-
return fakeRenderJsComponent(indexForThisRender);
|
|
94
|
-
}
|
|
95
|
-
else if (localRenderPlaceholder.path.startsWith('components/partials/')) {
|
|
96
|
-
const partialPath = path.resolve(webRoot, localRenderPlaceholder.path);
|
|
97
|
-
return renderPartial(viteServer, partialPath, localRenderPlaceholder.json);
|
|
98
|
-
}
|
|
99
|
-
else {
|
|
100
|
-
throw new Error(`Unimplemented render of ${localRenderPlaceholder.path}`);
|
|
101
|
-
}
|
|
102
|
-
};
|
|
103
|
-
async function proxySpecificPage(response, portalId, contentId, currentUrl, webRoot, viteServer, devServerHost, devServerPort) {
|
|
104
|
-
let accountId;
|
|
105
|
-
try {
|
|
106
|
-
accountId = getAccountId(portalId);
|
|
107
|
-
}
|
|
108
|
-
catch (e) {
|
|
109
|
-
response
|
|
110
|
-
.status(500)
|
|
111
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
if (!accountId) {
|
|
115
|
-
response
|
|
116
|
-
.status(500)
|
|
117
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
try {
|
|
121
|
-
const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
|
|
122
|
-
const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
|
|
123
|
-
const { previewDomain } = previewInfo;
|
|
124
|
-
const previewPath = createPreviewPath(contentId);
|
|
125
|
-
const previewQueryParams = createPreviewQueryParams(previewInfo);
|
|
126
|
-
let pageHtml = await makeProxyPreviewRequest(accountId, previewDomain, previewPath, previewQueryParams);
|
|
127
|
-
// TODO, this is only needed for asset references that happen _before_ the `<base href="...">` element
|
|
128
|
-
// Is that only a preview URL thing? Or is it in all (most?) rendered CMS pages
|
|
129
|
-
pageHtml = rewriteAbsoluteJsAndCssPaths(pageHtml, previewDomain, 'https://');
|
|
130
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
131
|
-
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
132
|
-
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
133
|
-
const numPlaceholders = localRenderPlaceholders.length;
|
|
134
|
-
const totalNumHtmlChunks = numPlaceholders * 2 + 1;
|
|
135
|
-
let numJsRenderFailures = 0;
|
|
136
|
-
let islands = [];
|
|
137
|
-
const renderPromisesByChunkIndex = new Array(numPlaceholders);
|
|
138
|
-
if (localRenderPlaceholders.length > 0) {
|
|
139
|
-
let offsetSoFar = 0;
|
|
140
|
-
const pageChunks = new Array(numPlaceholders + 1);
|
|
141
|
-
for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
|
|
142
|
-
const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
|
|
143
|
-
pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
|
|
144
|
-
const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer);
|
|
145
|
-
renderPromisesByChunkIndex[indexForThisRender] = renderPromise
|
|
146
|
-
.then((promiseResult) => {
|
|
147
|
-
// eslint-disable-next-line prefer-const
|
|
148
|
-
let { html, cssNeeded, renderInfoContext } = promiseResult;
|
|
149
|
-
console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
|
|
150
|
-
if (renderInfoContext.islands.length > 0) {
|
|
151
|
-
islands = islands.concat(renderInfoContext.islands);
|
|
152
|
-
}
|
|
153
|
-
if (cssNeeded) {
|
|
154
|
-
// Note, this is needed for cases where `<base href="...">` is output by the renderer, so
|
|
155
|
-
// that local asset URLs go to the local dev server
|
|
156
|
-
cssNeeded = rewriteAbsoluteJsAndCssPaths(cssNeeded, serverDomainAndPort, 'http://');
|
|
157
|
-
return `${cssNeeded}\n${html}`;
|
|
158
|
-
}
|
|
159
|
-
return html;
|
|
160
|
-
})
|
|
161
|
-
.catch((e) => {
|
|
162
|
-
numJsRenderFailures += 1;
|
|
163
|
-
console.error(e);
|
|
164
|
-
return createLocalJsRenderErrorOutput(localRenderPlaceholder.path, e);
|
|
165
|
-
});
|
|
166
|
-
offsetSoFar = localRenderPlaceholder.endOffset;
|
|
167
|
-
}
|
|
168
|
-
// Last chunk from end of last placeholder to end of HTML
|
|
169
|
-
pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
|
|
170
|
-
response.writeHead(200);
|
|
171
|
-
for (let i = 0; i < localRenderPlaceholders.length; i++) {
|
|
172
|
-
const chunk = pageChunks[i];
|
|
173
|
-
response.write(chunk);
|
|
174
|
-
const foobar = await renderPromisesByChunkIndex[i];
|
|
175
|
-
// console.log("JS rendered chunk", i, foobar);
|
|
176
|
-
response.write(foobar);
|
|
177
|
-
}
|
|
178
|
-
if (islands.length > 0) {
|
|
179
|
-
const sortedIslandRoots = sortIslandRootsByPriority(islands);
|
|
180
|
-
const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
|
|
181
|
-
response.write(islandRuntimeAndGlobalScriptHtml);
|
|
182
|
-
}
|
|
183
|
-
// Write last string chunk located after last placeholder
|
|
184
|
-
response.write(pageChunks[pageChunks.length - 1]);
|
|
185
|
-
response.end();
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
response.writeHead(200);
|
|
189
|
-
response.write(pageHtml);
|
|
190
|
-
response.end();
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
catch (error) {
|
|
194
|
-
// TODO change error.stack to error.message before we publish
|
|
195
|
-
response
|
|
196
|
-
.status(500)
|
|
197
|
-
.end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
async function proxyPageHandler(request, response) {
|
|
202
|
-
const { packageRoot, viteServer, webRoot, devServerHost, devServerPort } = request.app.locals;
|
|
203
|
-
await proxySpecificPage(response, parseInt(request.params.portalId, 10), request.params.contentId, request.originalUrl, webRoot, viteServer, devServerHost, devServerPort);
|
|
204
|
-
}
|
|
205
|
-
export default proxyPageHandler;
|
package/dist/run.mjs
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import createDevServer from './src/createDevServer.js';
|
|
3
|
-
import { dirname } from 'path';
|
|
4
|
-
import { fileURLToPath } from 'url';
|
|
5
|
-
const packageRoot = dirname(fileURLToPath(import.meta.url));
|
|
6
|
-
const webRoot = process.argv[2];
|
|
7
|
-
if (!webRoot) {
|
|
8
|
-
throw new Error(`No web root path argument specified`);
|
|
9
|
-
}
|
|
10
|
-
createDevServer(packageRoot, webRoot);
|
|
@@ -1,14 +0,0 @@
|
|
|
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;
|
|
@@ -1,13 +0,0 @@
|
|
|
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
|
-
}
|