@hubspot/cms-dev-server 0.4.1 → 0.4.3

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.
@@ -14,6 +14,7 @@ import { debug } from './lib/debug.js';
14
14
  import { getEnv, getAccountId, loadConfig, validateConfig, } from '@hubspot/cli-lib/lib/config.js';
15
15
  import { fetchWebsiteDomainNames } from './proxyPage/fetchDomains.js';
16
16
  import { logMissingScopeWarning, MissingScopeError } from './lib/errors.js';
17
+ const sharedDepsEnabled = Boolean(process.env.SHARED_DEPS_ENABLED);
17
18
  const BASE_PATH = '/';
18
19
  const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
19
20
  const SHADOW_PORT = 1442;
@@ -71,7 +72,7 @@ Local proxy functionality will not work without setting up authentication.`);
71
72
  const authedHublet = 'na1';
72
73
  const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
73
74
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
74
- const viteServer = await createViteDevServer(absoluteWebRoot, PORT, sslEnabledOption, domainsToProxy);
75
+ const viteServer = await createViteDevServer(absoluteWebRoot, PORT, sslEnabledOption, domainsToProxy, sharedDepsEnabled);
75
76
  // Get https key and cert from the vite config set by vite-plugin-mkcert (if it worked )
76
77
  const viteHTTPSConfig = viteServer.config.server.https;
77
78
  const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
@@ -87,6 +88,7 @@ Local proxy functionality will not work without setting up authentication.`);
87
88
  expressServer.locals.authedHublet = authedHublet;
88
89
  expressServer.locals.storybookEnabled = storybook;
89
90
  expressServer.locals.storybookPort = STORYBOOK_PORT;
91
+ expressServer.locals.sharedDepsEnabled = sharedDepsEnabled;
90
92
  expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
91
93
  expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
92
94
  expressServer.use(bodyParser.json());
@@ -0,0 +1,155 @@
1
+ import path from 'path';
2
+ import url from 'url';
3
+ import express from 'express';
4
+ import http from 'http';
5
+ import { spawn } from 'child_process';
6
+ import { normalizePath } from 'vite';
7
+ import createDevServerRoutes from './routes/createDevServerRoutes.js';
8
+ import startShadowDevServer from './shadowDevServer/startShadowDevServer.js';
9
+ import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
10
+ import createViteDevServer from './createViteDevServer.js';
11
+ import { createHttpsRedirectingServer } from './lib/httpsRedirectingServer.js';
12
+ import { debug } from './lib/debug.js';
13
+ import { getEnv, getAccountId, loadConfig, validateConfig, } from '@hubspot/cli-lib/lib/config.js';
14
+ import { fetchWebsiteDomainNames } from './proxyPage/fetchDomains.js';
15
+ import { logMissingScopeWarning, MissingScopeError } from './lib/errors.js';
16
+ async function createDevServer(devServerConfiguration) {
17
+ const { basePath, shadowPort, storybookPort, webRoot, storybookEnabled, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabled, port, } = devServerConfiguration;
18
+ console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
19
+ let authedPortalId = null;
20
+ let authedEnv = null;
21
+ if (hubspotCliConfigPathOption && hubspotCliAccountNameOption) {
22
+ console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration at: ${hubspotCliConfigPathOption}`);
23
+ }
24
+ else if (hubspotCliConfigPathOption) {
25
+ console.log(`Loading HS auth configuration at: ${hubspotCliConfigPathOption}`);
26
+ }
27
+ else if (hubspotCliAccountNameOption) {
28
+ console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration.`);
29
+ }
30
+ // If a custom hubspot.config.yaml config path was set, make sure to force load that before
31
+ // any hs config values are read
32
+ loadConfig(hubspotCliConfigPathOption || null, { useEnv: false });
33
+ if (validateConfig()) {
34
+ authedPortalId = getAccountId(hubspotCliAccountNameOption);
35
+ authedEnv = getEnv(hubspotCliAccountNameOption);
36
+ if (!authedPortalId && hubspotCliAccountNameOption) {
37
+ console.error(`Couldn't find ${hubspotCliAccountNameOption} in your hubspot.config.yaml`);
38
+ process.exit(1);
39
+ }
40
+ }
41
+ else {
42
+ console.warn(`Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).
43
+ If needed you can refer to another config file with --config.
44
+
45
+ Local proxy functionality will not work without setting up authentication.`);
46
+ }
47
+ let domainsToProxy = [];
48
+ if (sslEnabled && authedPortalId) {
49
+ try {
50
+ const portalDomains = await fetchWebsiteDomainNames(authedPortalId);
51
+ domainsToProxy = (process.env.DOMAINS_TO_PROXY || '')
52
+ .split(',')
53
+ .filter(d => !!d);
54
+ domainsToProxy = [...domainsToProxy, ...portalDomains];
55
+ }
56
+ catch (e) {
57
+ if (e instanceof MissingScopeError) {
58
+ logMissingScopeWarning(e);
59
+ }
60
+ else {
61
+ console.warn(`Failed to fetch domains for ${authedPortalId}, HTTPS proxying won't work with them.`);
62
+ }
63
+ }
64
+ }
65
+ const authedHublet = 'na1';
66
+ const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
67
+ const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
68
+ const viteServer = await createViteDevServer(absoluteWebRoot, port, sslEnabled, domainsToProxy);
69
+ // Get https key and cert from the vite config set by vite-plugin-mkcert (if it worked )
70
+ const viteHTTPSConfig = viteServer.config.server.https;
71
+ const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
72
+ const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
73
+ const httpServers = [];
74
+ const expressServer = express();
75
+ expressServer.locals.devServerHost = 'hslocal.net';
76
+ expressServer.locals.devServerPort = port;
77
+ expressServer.locals.webRoot = webRoot;
78
+ expressServer.locals.viteServer = viteServer;
79
+ expressServer.locals.authedPortalId = authedPortalId;
80
+ expressServer.locals.authedEnv = authedEnv;
81
+ expressServer.locals.authedHublet = authedHublet;
82
+ expressServer.locals.storybookEnabled = storybookEnabled;
83
+ expressServer.locals.storybookPort = storybookPort;
84
+ expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
85
+ expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
86
+ expressServer.use(basePath, await createDevServerRoutes(viteServer, storybookEnabled ? storybookPort : null));
87
+ if (sslEnabled) {
88
+ if (httpsKey && httpsCert) {
89
+ const { server, innerHTTPServer, innerHTTPSServer } = createHttpsRedirectingServer({ key: httpsKey, cert: httpsCert }, expressServer);
90
+ server.listen(port);
91
+ httpServers.push(server);
92
+ // Not sure if we need to worry about closing all of these, but🤷
93
+ httpServers.push(innerHTTPServer);
94
+ httpServers.push(innerHTTPSServer);
95
+ }
96
+ else {
97
+ console.error('Failed to start a HTTPS server, try --no-ssl');
98
+ process.exit(1);
99
+ }
100
+ }
101
+ else {
102
+ const httpServer = http.createServer(expressServer);
103
+ httpServer.listen(port);
104
+ httpServers.push(httpServer);
105
+ }
106
+ startShadowDevServer(port, shadowPort);
107
+ let extraServerInfo = '';
108
+ const protocol = sslEnabled ? 'https' : 'http';
109
+ if (authedPortalId) {
110
+ extraServerInfo += `, hubid=${authedPortalId}`;
111
+ }
112
+ if (authedEnv && authedEnv !== 'prod') {
113
+ extraServerInfo += `, env=${authedEnv}`;
114
+ }
115
+ console.log(`
116
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${port}${extraServerInfo})
117
+ `);
118
+ if (storybookEnabled) {
119
+ const packageRoot = path.dirname(url.fileURLToPath(import.meta.url));
120
+ const configPath = path.resolve(packageRoot, './storybook');
121
+ const storybookProcess = spawn('yarn', [
122
+ 'sb',
123
+ 'dev',
124
+ '-p',
125
+ storybookPort.toString(),
126
+ '-c',
127
+ configPath,
128
+ '--quiet',
129
+ '--no-open',
130
+ ], {
131
+ cwd: process.cwd(),
132
+ env: {
133
+ ...process.env,
134
+ WEB_ROOT: path.join(webRoot, 'components'),
135
+ },
136
+ });
137
+ console.log(`Starting storybook server on port ${storybookPort}`);
138
+ if (debug.enabled) {
139
+ storybookProcess.stdout.pipe(process.stdout);
140
+ }
141
+ storybookProcess.stderr.pipe(process.stderr);
142
+ }
143
+ // Return hook to shut down server gracefully
144
+ return {
145
+ close: () => {
146
+ const serverClosePromises = httpServers.map(server => new Promise(resolve => {
147
+ server.close(() => {
148
+ resolve(null);
149
+ });
150
+ }));
151
+ return Promise.allSettled([...serverClosePromises, viteServer.close()]);
152
+ },
153
+ };
154
+ }
155
+ export default createDevServer;
@@ -2,9 +2,9 @@
2
2
  /* eslint-disable require-await */
3
3
  import { createServer as createViteServer } from 'vite';
4
4
  import { default as react } from '@vitejs/plugin-react';
5
- import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
5
+ import { clientIslandEntryPlugin, resolveIslandPlugin, } from '@hubspot/cms-js-internal';
6
6
  import mkcert from 'vite-plugin-mkcert';
7
- async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = []) {
7
+ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = [], sharedDepsEnabled) {
8
8
  const additionalMkcertHosts = domainsToProxy
9
9
  .map(proxyDomain => [
10
10
  `${proxyDomain}.localhost`,
@@ -40,7 +40,8 @@ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = [
40
40
  plugins: [
41
41
  sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
42
42
  react(),
43
- resolveIslandPlugin(),
43
+ sharedDepsEnabled && clientIslandEntryPlugin(),
44
+ resolveIslandPlugin({ sharedDepsEnabled }),
44
45
  ],
45
46
  css: {
46
47
  postcss: webRoot,
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ function resolveIslandPlugin() {
28
28
  viteCommand = config.command;
29
29
  },
30
30
  load(id) {
31
- if (id.endsWith("?island")) {
31
+ if (id.endsWith("?island") || id.endsWith("?client")) {
32
32
  const [idWithNoParam] = id.split("?");
33
33
  const componentExtension = path.extname(idWithNoParam);
34
34
  const componentFilenameWithNoExtension = path.basename(
@@ -71,9 +71,9 @@ var collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /
71
71
  ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
72
72
  `;
73
73
  };
74
- var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
74
+ var serializeIslandDataToJSON = (tweakedIslandsArray, indent = 0) => {
75
75
  const indentString = new Array(indent).fill(" ").join("");
76
- return `window.__islands = ${JSON.stringify(
76
+ return `${JSON.stringify(
77
77
  tweakedIslandsArray.map(
78
78
  ({
79
79
  id,
@@ -83,24 +83,50 @@ var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
83
83
  hydrateOn,
84
84
  clientOnly,
85
85
  priority,
86
- url
86
+ url,
87
+ sharedStateID
87
88
  }) => {
88
- return {
89
+ const output = {
89
90
  id,
90
91
  moduleName,
91
92
  moduleId,
92
- props,
93
93
  hydrateOn,
94
94
  clientOnly,
95
95
  priority,
96
+ props,
96
97
  url
97
98
  };
99
+ if (sharedStateID) {
100
+ output.sharedStateID = sharedStateID;
101
+ }
102
+ return output;
98
103
  }
99
104
  ),
100
105
  null,
101
106
  2
102
107
  ).replace(/\n/gm, `
103
- ${indentString}`)};`;
108
+ ${indentString}`)}`;
109
+ };
110
+ var writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0) => {
111
+ const indentString = new Array(indent).fill(" ").join("");
112
+ const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x) => !!x);
113
+ if (sharedStateIDs.length > 0) {
114
+ const stateByID = {};
115
+ sharedStateIDs.forEach(
116
+ (id) => stateByID[id] = perServerRequestData.get(id)
117
+ );
118
+ const stringifiedState = JSON.stringify(stateByID, null, 2);
119
+ return `
120
+
121
+ var newState = ${stringifiedState};
122
+ if(window.__hsSSInit) {
123
+ window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
124
+ } else {
125
+ window.__hsSSInit = newState;
126
+ }`.replace(/\n/gm, `
127
+ ${indentString}`);
128
+ }
129
+ return "";
104
130
  };
105
131
  function getIslandUrls(roots, viteDevServer) {
106
132
  return roots.map((island) => {
@@ -117,8 +143,12 @@ function getIslandUrls(roots, viteDevServer) {
117
143
  return tweakedIsland;
118
144
  });
119
145
  }
120
- var createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
121
- return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
146
+ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent) => {
147
+ const islands = getIslandUrls(roots, viteDevServer);
148
+ return `window.__islands = ${serializeIslandDataToJSON(
149
+ islands,
150
+ indent
151
+ )}${writeSharedStateToJsGlobal(islands, perServerRequestData, indent)}`;
122
152
  };
123
153
  var viteRoot;
124
154
  var viteCommand;
@@ -131,7 +161,7 @@ function resolveIslandPlugin() {
131
161
  viteCommand = config.command;
132
162
  },
133
163
  load(id) {
134
- if (id.endsWith("?island")) {
164
+ if (id.endsWith("?island") || id.endsWith("?client")) {
135
165
  const [idWithNoParam] = id.split("?");
136
166
  const componentExtension = path.extname(idWithNoParam);
137
167
  const componentFilenameWithNoExtension = path.basename(
@@ -386,5 +416,6 @@ export {
386
416
  renderOnServer,
387
417
  renderStreamToPromise,
388
418
  resolveIslandPlugin,
419
+ serializeIslandDataToJSON,
389
420
  setIn
390
421
  };
@@ -0,0 +1,63 @@
1
+ import { resolve } from 'path';
2
+ const BASE_PATH = '/';
3
+ const AUTHED_HUBLET = 'na1';
4
+ /**
5
+ * Command line options
6
+ * --ssl
7
+ * --c (--config)
8
+ * --a (--account)
9
+ */
10
+ export function getDevServerConfiguration(args) {
11
+ const commandLineOptions = getCommandLineOptions(args);
12
+ const environmentVariables = getEnvironmentVariables();
13
+ return {
14
+ ...commandLineOptions,
15
+ ...environmentVariables,
16
+ authedHublet: AUTHED_HUBLET,
17
+ };
18
+ }
19
+ function getCommandLineOptions(args) {
20
+ const webRoot = args[2];
21
+ let hubspotCliConfigPathOption;
22
+ let hubspotCliAccountNameOption;
23
+ // Very basic CLI option parsing
24
+ const configOptionIndex = args.findIndex(arg => arg === '-c' || arg === '--config');
25
+ if (configOptionIndex > 0 && args.length > configOptionIndex) {
26
+ hubspotCliConfigPathOption = resolve(args[configOptionIndex + 1]);
27
+ args.splice(configOptionIndex, 2);
28
+ }
29
+ const accountOptionIndex = args.findIndex(arg => arg === '-a' || arg === '--account');
30
+ if (accountOptionIndex > 0 && args.length > accountOptionIndex) {
31
+ hubspotCliAccountNameOption = args[accountOptionIndex + 1];
32
+ args.splice(accountOptionIndex, 2);
33
+ }
34
+ const sslEnabled = args.includes('--ssl') && !args.includes('--no-ssl');
35
+ const storybookEnabled = args.findIndex(arg => arg === '--storybook') > 0;
36
+ return {
37
+ hubspotCliConfigPathOption,
38
+ hubspotCliAccountNameOption,
39
+ sslEnabled,
40
+ storybookEnabled,
41
+ webRoot,
42
+ };
43
+ }
44
+ function getEnvironmentVariables() {
45
+ // Ports
46
+ const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
47
+ const storybookPort = process.env.STORYBOOK_PORT
48
+ ? parseInt(process.env.STORYBOOK_PORT, 10)
49
+ : 3123;
50
+ const shadowPort = process.env.SHADOW_PORT
51
+ ? parseInt(process.env.SHADOW_PORT, 10)
52
+ : 1442;
53
+ const domainsToProxy = (process.env.DOMAINS_TO_PROXY || '')
54
+ .split(',')
55
+ .filter(d => !!d);
56
+ return {
57
+ basePath: BASE_PATH,
58
+ port,
59
+ storybookPort,
60
+ shadowPort,
61
+ domainsToProxy,
62
+ };
63
+ }
@@ -3,7 +3,18 @@
3
3
  import { promises as fsPromises } from 'fs';
4
4
  import { createIslandsGlobalJsForClientInDev, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
5
5
  const { readFile } = fsPromises;
6
- const generateIslandSetupScriptBlock = () => {
6
+ const generateIslandSetupScriptBlock = sharedDepsEnabled => {
7
+ if (sharedDepsEnabled) {
8
+ return `<script type="module">
9
+ import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
10
+ initConfigSingletonFromJSON(window.__hsEnvConfig);
11
+ </script>
12
+ <script type="module">
13
+ import { setupIslandHydration } from '@hubspot/cms-components/island-runtime-shared';
14
+ setupIslandHydration();
15
+ </script>
16
+ `;
17
+ }
7
18
  return `<script type="module">
8
19
  import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
9
20
  initConfigSingletonFromJSON(window.__hsEnvConfig);
@@ -20,20 +31,20 @@ const createdPlainHtmlTemplate = async (baseTemplatePath, title, globalScriptBlo
20
31
  ${globalScriptBlock}
21
32
  <!--bodyend-->`);
22
33
  };
23
- const createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
34
+ const createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock, sharedDepsEnabled) => {
24
35
  let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
25
36
  htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
26
- ${generateIslandSetupScriptBlock()}
37
+ ${generateIslandSetupScriptBlock(sharedDepsEnabled)}
27
38
  <!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
28
39
  <!--islandsglobal-->
29
40
  `);
30
41
  return htmlTemplate;
31
42
  };
32
- export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer) => {
43
+ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer, sharedDepsEnabled) => {
33
44
  let htmlTemplate;
34
45
  if (renderContext.islands.length) {
35
46
  const globalScriptBlock = getServerGlobalsToInject(renderContext.environmentConfig, renderContext.pageUrl);
36
- htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
47
+ htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title, globalScriptBlock, sharedDepsEnabled);
37
48
  htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
38
49
  ${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
39
50
  </script>
@@ -45,10 +56,10 @@ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath,
45
56
  }
46
57
  return viteServer.transformIndexHtml(url, htmlTemplate);
47
58
  };
48
- export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) => {
59
+ export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, sharedDepsEnabled) => {
49
60
  // Loading through vite so all of nested `@hubspot/cms-*` imports work
50
61
  const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
51
- const islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock());
62
+ const islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock(sharedDepsEnabled));
52
63
  return `${islandRuntimeScript}
53
64
  <script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
54
65
  `;
@@ -77,7 +77,7 @@ const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholde
77
77
  throw new Error(`Unimplemented render of ${placeholderPath}.`);
78
78
  }
79
79
  };
80
- export default async function proxySpecificPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
80
+ export default async function proxySpecificPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, sharedDepsEnabled, urlToProxy, fullOriginalUrl) {
81
81
  let accountId;
82
82
  let proxyEnv;
83
83
  try {
@@ -151,7 +151,7 @@ export default async function proxySpecificPage(response, portalId, hublet, cont
151
151
  response.write(getServerGlobalsToInject(environmentConfig, fullOriginalUrl));
152
152
  if (islands.length > 0) {
153
153
  const sortedIslandRoots = sortIslandRootsByPriority(islands);
154
- const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer);
154
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, sharedDepsEnabled);
155
155
  response.write(islandRuntimeAndGlobalScriptHtml);
156
156
  }
157
157
  // Write last string chunk located after last placeholder
@@ -6,7 +6,7 @@ import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
6
6
  import renderModule from '../lib/renderModule.js';
7
7
  import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
8
8
  const moduleRouteHandler = async (request, response) => {
9
- const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer } = request.app.locals;
9
+ const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer, sharedDepsEnabled, } = request.app.locals;
10
10
  const moduleName = request.params.moduleName;
11
11
  const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
12
12
  const modulePath = normalizePath(path.resolve(webRoot, 'components/modules/', moduleName));
@@ -24,7 +24,7 @@ const moduleRouteHandler = async (request, response) => {
24
24
  const environmentConfig = buildStaticEnvConfig(authedPortalId, authedHublet, authedEnv, false);
25
25
  try {
26
26
  const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, fieldOverrides, fullOriginalUrlFromRequest(request), environmentConfig);
27
- const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer);
27
+ const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer, sharedDepsEnabled);
28
28
  const html = htmlShell
29
29
  .replace('<!--headend-->', cssNeeded)
30
30
  .replace(`<!--ssr-outlet-->`, renderedHtml);
@@ -6,14 +6,14 @@ import renderPartial from '../lib/renderPartial.js';
6
6
  import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
7
7
  import { buildStaticEnvConfig } from '@hubspot/cms-components/config';
8
8
  const partialRouteHandler = async (request, response) => {
9
- const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer } = request.app.locals;
9
+ const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer, sharedDepsEnabled, } = request.app.locals;
10
10
  const partialName = request.params.partial;
11
11
  const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
12
12
  const partialPath = normalizePath(path.resolve(webRoot, 'components/partials/', partialName));
13
13
  const environmentConfig = buildStaticEnvConfig(authedPortalId, authedHublet, authedEnv, false);
14
14
  try {
15
15
  const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request), environmentConfig);
16
- const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderContext, viteServer);
16
+ const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderContext, viteServer, sharedDepsEnabled);
17
17
  const html = htmlShell
18
18
  .replace('<!--headend-->', cssNeeded)
19
19
  .replace(`<!--ssr-outlet-->`, renderedHtml);
@@ -6,7 +6,7 @@ import { getSubDomainFromValidLocalDomain, consoleWarn, } from '../proxyPage/uti
6
6
  import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
7
7
  import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
8
8
  export default async function proxyPageRouteHandler(request, response, next) {
9
- const { viteServer, webRoot, projectName, projectComponentPath } = request.app.locals;
9
+ const { viteServer, webRoot, projectName, projectComponentPath, sharedDepsEnabled, } = request.app.locals;
10
10
  if (!request.accepts().includes('text/html')) {
11
11
  return response.sendStatus(404);
12
12
  }
@@ -32,7 +32,7 @@ export default async function proxyPageRouteHandler(request, response, next) {
32
32
  }
33
33
  try {
34
34
  const { portalId, contentId, hublet } = await fetchContentMetadata(urlToProxy);
35
- await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl);
35
+ await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, sharedDepsEnabled, urlToProxy, fullOriginalUrl);
36
36
  }
37
37
  catch (e) {
38
38
  next(e);
@@ -6,7 +6,7 @@ import fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';
6
6
  import proxyPage from '../proxyPage/proxyPage.js';
7
7
  import { consoleWarn } from '../proxyPage/utils.js';
8
8
  export default async function proxyPathPageRouteHandler(request, response, next) {
9
- const { viteServer, webRoot, devServerHost, devServerPort, projectName, projectComponentPath, } = request.app.locals;
9
+ const { viteServer, webRoot, devServerHost, devServerPort, projectName, projectComponentPath, sharedDepsEnabled, } = request.app.locals;
10
10
  if (!request.accepts().includes('text/html')) {
11
11
  return response.sendStatus(404);
12
12
  }
@@ -35,7 +35,7 @@ export default async function proxyPathPageRouteHandler(request, response, next)
35
35
  }
36
36
  try {
37
37
  const { portalId, contentId, hublet } = await fetchContentMetadata(proxyPageUrl.href);
38
- await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, proxyPageUrl.href, proxyPageUrl.href);
38
+ await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, sharedDepsEnabled, proxyPageUrl.href, proxyPageUrl.href);
39
39
  }
40
40
  catch (e) {
41
41
  next(e);
package/dist/run.js CHANGED
@@ -69,9 +69,9 @@ import { join as joinPosix } from "path/posix";
69
69
  import { basename } from "path";
70
70
  import { cloneElement } from "react";
71
71
  import { renderToStaticMarkup } from "react-dom/server";
72
- var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
72
+ var serializeIslandDataToJSON = (tweakedIslandsArray, indent = 0) => {
73
73
  const indentString = new Array(indent).fill(" ").join("");
74
- return `window.__islands = ${JSON.stringify(
74
+ return `${JSON.stringify(
75
75
  tweakedIslandsArray.map(
76
76
  ({
77
77
  id,
@@ -81,24 +81,50 @@ var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
81
81
  hydrateOn,
82
82
  clientOnly,
83
83
  priority,
84
- url: url3
84
+ url: url3,
85
+ sharedStateID
85
86
  }) => {
86
- return {
87
+ const output = {
87
88
  id,
88
89
  moduleName,
89
90
  moduleId,
90
- props,
91
91
  hydrateOn,
92
92
  clientOnly,
93
93
  priority,
94
+ props,
94
95
  url: url3
95
96
  };
97
+ if (sharedStateID) {
98
+ output.sharedStateID = sharedStateID;
99
+ }
100
+ return output;
96
101
  }
97
102
  ),
98
103
  null,
99
104
  2
100
105
  ).replace(/\n/gm, `
101
- ${indentString}`)};`;
106
+ ${indentString}`)}`;
107
+ };
108
+ var writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0) => {
109
+ const indentString = new Array(indent).fill(" ").join("");
110
+ const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x) => !!x);
111
+ if (sharedStateIDs.length > 0) {
112
+ const stateByID = {};
113
+ sharedStateIDs.forEach(
114
+ (id) => stateByID[id] = perServerRequestData.get(id)
115
+ );
116
+ const stringifiedState = JSON.stringify(stateByID, null, 2);
117
+ return `
118
+
119
+ var newState = ${stringifiedState};
120
+ if(window.__hsSSInit) {
121
+ window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
122
+ } else {
123
+ window.__hsSSInit = newState;
124
+ }`.replace(/\n/gm, `
125
+ ${indentString}`);
126
+ }
127
+ return "";
102
128
  };
103
129
  function getIslandUrls(roots, viteDevServer) {
104
130
  return roots.map((island) => {
@@ -115,8 +141,12 @@ function getIslandUrls(roots, viteDevServer) {
115
141
  return tweakedIsland;
116
142
  });
117
143
  }
118
- var createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
119
- return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
144
+ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent) => {
145
+ const islands = getIslandUrls(roots, viteDevServer);
146
+ return `window.__islands = ${serializeIslandDataToJSON(
147
+ islands,
148
+ indent
149
+ )}${writeSharedStateToJsGlobal(islands, perServerRequestData, indent)}`;
120
150
  };
121
151
  var viteRoot;
122
152
  var viteCommand;
@@ -129,7 +159,7 @@ function resolveIslandPlugin() {
129
159
  viteCommand = config.command;
130
160
  },
131
161
  load(id) {
132
- if (id.endsWith("?island")) {
162
+ if (id.endsWith("?island") || id.endsWith("?client")) {
133
163
  const [idWithNoParam] = id.split("?");
134
164
  const componentExtension = path.extname(idWithNoParam);
135
165
  const componentFilenameWithNoExtension = path.basename(
@@ -529,7 +559,12 @@ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, tit
529
559
  htmlTemplate = htmlTemplate.replace(
530
560
  "<!--islandsglobal-->",
531
561
  `<script>
532
- ${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
562
+ ${createIslandsGlobalJsForClientInDev(
563
+ renderContext.islands,
564
+ renderContext.perServerRequestData,
565
+ viteServer,
566
+ 4
567
+ )}
533
568
  </script>
534
569
  `
535
570
  );
@@ -545,7 +580,7 @@ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, tit
545
580
  }
546
581
  return viteServer.transformIndexHtml(url3, htmlTemplate);
547
582
  };
548
- var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) => {
583
+ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, perServerRequestData, viteServer) => {
549
584
  const internalSsrPath = packagePath(import.meta.url, "internalSsr");
550
585
  const { createIslandsGlobalJsForClientInDev: createIslandsGlobalJsForClientInDev2 } = await viteServer.ssrLoadModule(internalSsrPath);
551
586
  const islandRuntimeScript = await viteServer.transformIndexHtml(
@@ -555,6 +590,7 @@ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) =>
555
590
  return `${islandRuntimeScript}
556
591
  <script>${createIslandsGlobalJsForClientInDev2(
557
592
  sortedIslandRoots,
593
+ perServerRequestData,
558
594
  viteServer,
559
595
  4
560
596
  )}</script>
@@ -1086,6 +1122,9 @@ ${error.error.message}`);
1086
1122
  import {
1087
1123
  buildStaticEnvConfig as buildStaticEnvConfig3
1088
1124
  } from "@hubspot/cms-components/config";
1125
+ import {
1126
+ mergeServerRequestData_internal
1127
+ } from "@hubspot/cms-components";
1089
1128
  var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
1090
1129
  const url3 = new URL(urlToProxy);
1091
1130
  console.log(`Proxying request to ${url3.href}`, {
@@ -1207,6 +1246,7 @@ async function proxySpecificPage(response, portalId, hublet, contentId, webRoot2
1207
1246
  const numPlaceholders = localRenderPlaceholders.length;
1208
1247
  let numJsRenderFailures = 0;
1209
1248
  let islands = [];
1249
+ let mergedPerRequestState = /* @__PURE__ */ new Map();
1210
1250
  const renderPromisesByChunkIndex = new Array(
1211
1251
  numPlaceholders
1212
1252
  );
@@ -1237,6 +1277,10 @@ async function proxySpecificPage(response, portalId, hublet, contentId, webRoot2
1237
1277
  if (renderContext.islands.length > 0) {
1238
1278
  islands = islands.concat(renderContext.islands);
1239
1279
  }
1280
+ mergedPerRequestState = mergeServerRequestData_internal(
1281
+ mergedPerRequestState,
1282
+ renderContext.perServerRequestData
1283
+ );
1240
1284
  if (cssNeeded) {
1241
1285
  return `${cssNeeded}
1242
1286
  ${html}`;
@@ -1244,6 +1288,12 @@ ${html}`;
1244
1288
  return html;
1245
1289
  }).catch((e) => {
1246
1290
  numJsRenderFailures += 1;
1291
+ console.log(
1292
+ "Attempted to render",
1293
+ localRenderPlaceholder.path,
1294
+ "with props",
1295
+ localRenderPlaceholder.json
1296
+ );
1247
1297
  console.error(e);
1248
1298
  return renderLocalError_default(localRenderPlaceholder.path, e);
1249
1299
  });
@@ -1264,6 +1314,7 @@ ${html}`;
1264
1314
  const sortedIslandRoots = sortIslandRootsByPriority(islands);
1265
1315
  const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
1266
1316
  sortedIslandRoots,
1317
+ mergedPerRequestState,
1267
1318
  viteServer
1268
1319
  );
1269
1320
  response.write(islandRuntimeAndGlobalScriptHtml);
@@ -2,6 +2,7 @@ import path from 'path';
2
2
  import { mergeConfig } from 'vite';
3
3
  const webRoot = process.env.WEB_ROOT;
4
4
  const storyPath = path.resolve(process.cwd(), webRoot, '**/*.stories.*');
5
+ const sharedDepsEnabled = Boolean(process.env.SHARED_DEPS_ENABLED);
5
6
  export default {
6
7
  addons: ['@storybook/addon-essentials'],
7
8
  framework: '@storybook/react-vite',
@@ -23,7 +24,7 @@ export default {
23
24
  css: {
24
25
  postcss: webRoot,
25
26
  },
26
- plugins: [resolveIslandPlugin()],
27
+ plugins: [resolveIslandPlugin({ sharedDepsEnabled })],
27
28
  };
28
29
  return mergeConfig(config, viteConfig);
29
30
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@hubspot/cli-lib": "^3.0.12",
27
- "@hubspot/cms-components": "^0.4.1",
27
+ "@hubspot/cms-components": "^0.4.3",
28
28
  "@storybook/addon-actions": "^7.0.0-beta.19",
29
29
  "@storybook/addon-essentials": "^7.0.0-beta.19",
30
30
  "@storybook/addon-interactions": "^7.0.0-beta.19",
@@ -77,8 +77,8 @@
77
77
  "types"
78
78
  ],
79
79
  "nodemonConfig": {
80
- "delay": "2000ms",
81
80
  "ext": "js,json,ts,tsx,jsx,html",
81
+ "delay": "2000ms",
82
82
  "ignore": [
83
83
  "testApp/*",
84
84
  "./dist/*"
@@ -95,5 +95,5 @@
95
95
  "publishConfig": {
96
96
  "access": "public"
97
97
  },
98
- "gitHead": "d2e7b02c414f07b8bc24b4d97b81bf7e9ba48dc0"
98
+ "gitHead": "7d2696951f3aeeae3085382ebe1a66ba94ecc748"
99
99
  }
Binary file