@hubspot/cms-dev-server 0.3.3 → 0.4.0

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.
@@ -0,0 +1,48 @@
1
+ import net from 'net';
2
+ import http from 'http';
3
+ import https from 'https';
4
+ function requireHTTPS(message, response) {
5
+ const newLocation = `https://${message.headers.host}${message.url}`;
6
+ response
7
+ .writeHead(302, {
8
+ Location: newLocation,
9
+ })
10
+ .end();
11
+ }
12
+ // Running http and https servers on the same port pulled from https://stackoverflow.com/a/42019773
13
+ export function createHttpsRedirectingServer(opts, handler) {
14
+ const innerHTTPServer = http.createServer(requireHTTPS);
15
+ const innerHTTPSServer = https.createServer(opts, handler);
16
+ const server = net.createServer(socket => {
17
+ socket.once('data', buffer => {
18
+ // Pause the socket
19
+ socket.pause();
20
+ // Determine if this is an HTTP(s) request
21
+ const byte = buffer[0];
22
+ let protocol;
23
+ if (byte === 22) {
24
+ protocol = 'https';
25
+ }
26
+ else if (32 < byte && byte < 127) {
27
+ protocol = 'http';
28
+ }
29
+ else {
30
+ throw new Error('Unknown issue with incoming data, unknown if http or https');
31
+ }
32
+ const proxy = protocol === 'http' ? innerHTTPServer : innerHTTPSServer;
33
+ if (proxy) {
34
+ // Push the buffer back onto the front of the data stream
35
+ socket.unshift(buffer);
36
+ // Emit the socket to the HTTP(s) server
37
+ proxy.emit('connection', socket);
38
+ }
39
+ // As of NodeJS 10.x the socket must be
40
+ // resumed asynchronously or the socket
41
+ // connection hangs, potentially crashing
42
+ // the process. Prior to NodeJS 10.x
43
+ // the socket may be resumed synchronously.
44
+ process.nextTick(() => socket.resume());
45
+ });
46
+ });
47
+ return { server, innerHTTPServer, innerHTTPSServer };
48
+ }
@@ -4,15 +4,15 @@ function getByteSizeOf(props) {
4
4
  function formatBytesToString(bytes) {
5
5
  if (bytes > 1000000) {
6
6
  // If byte size is > 1mb, show size in red
7
- return ['\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`];
7
+ return ['\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`, `\x1b[0m`];
8
8
  }
9
9
  else if (bytes > 10000) {
10
10
  // if byte size is between 10kb and 1mb, show size in yellow
11
- return ['\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`];
11
+ return ['\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`, `\x1b[0m`];
12
12
  }
13
13
  else {
14
14
  // Show size in green
15
- return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`];
15
+ return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`, `\x1b[0m`];
16
16
  }
17
17
  }
18
18
  const getPropsInfo = (props, reportOptions = { showNestedKeySizeIfGreater: null }, recursionDepth = 0) => {
@@ -45,12 +45,10 @@ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath,
45
45
  }
46
46
  return viteServer.transformIndexHtml(url, htmlTemplate);
47
47
  };
48
- export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, devServerHost, devServerPort) => {
49
- const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
48
+ export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) => {
50
49
  // Loading through vite so all of nested `@hubspot/cms-*` imports work
51
50
  const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
52
- let islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock());
53
- islandRuntimeScript = islandRuntimeScript.replace('import RefreshRuntime from "/@react-refresh"', `import RefreshRuntime from "http://${serverDomainAndPort}/@react-refresh"`);
51
+ const islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock());
54
52
  return `${islandRuntimeScript}
55
53
  <script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
56
54
  `;
@@ -1,3 +1,5 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
1
3
  import http from 'http';
2
4
  import https from 'https';
3
5
  export default async function fetchContentMetadata(url, redirects = 0, originalUrl) {
@@ -0,0 +1,29 @@
1
+ import { get as hsGet } from '@hubspot/cli-lib/http.js';
2
+ import { isMissingScopeError, MissingScopeError } from '../lib/errors.js';
3
+ export async function fetchDomains(portalId) {
4
+ try {
5
+ // Works with oauth if content-custom-domain-read scope present (from cms.domains.read scope group)
6
+ const result = (await hsGet(portalId, {
7
+ uri: `/cms/v3/domains`,
8
+ query: { portalId },
9
+ json: true,
10
+ }));
11
+ return result.results;
12
+ }
13
+ catch (error) {
14
+ if (isMissingScopeError(error)) {
15
+ throw new MissingScopeError(error);
16
+ }
17
+ throw error;
18
+ }
19
+ }
20
+ export async function fetchWebsiteDomainNames(portalId) {
21
+ const domains = await fetchDomains(portalId);
22
+ const filteredDomains = domains.filter(domain => {
23
+ return (domain.isUsedForBlogPost ||
24
+ domain.isUsedForSitePage ||
25
+ domain.isUsedForLandingPage);
26
+ });
27
+ const domainNames = filteredDomains.map(r => r.domain);
28
+ return domainNames;
29
+ }
@@ -13,7 +13,7 @@ import { fakeRenderJsComponent } from './utils.js';
13
13
  import renderLocalError from './renderLocalError.js';
14
14
  import fetchPreviewInfo from './fetchPreviewInfo.js';
15
15
  import { buildStaticEnvConfig, } from '@hubspot/cms-components/config';
16
- const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
16
+ export const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
17
17
  const url = new URL(urlToProxy);
18
18
  console.log(`Proxying request to ${url.href}`, {
19
19
  previewKey,
@@ -77,11 +77,14 @@ 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, devServerHost, devServerPort, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
80
+ export default async function proxySpecificPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
81
81
  let accountId;
82
82
  let proxyEnv;
83
83
  try {
84
84
  accountId = getAccountId(portalId);
85
+ if (accountId === null) {
86
+ throw new Error();
87
+ }
85
88
  proxyEnv = getEnv(accountId);
86
89
  }
87
90
  catch (e) {
@@ -148,7 +151,7 @@ export default async function proxySpecificPage(response, portalId, hublet, cont
148
151
  response.write(getServerGlobalsToInject(environmentConfig, fullOriginalUrl));
149
152
  if (islands.length > 0) {
150
153
  const sortedIslandRoots = sortIslandRootsByPriority(islands);
151
- const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
154
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer);
152
155
  response.write(islandRuntimeAndGlobalScriptHtml);
153
156
  }
154
157
  // Write last string chunk located after last placeholder
@@ -1,3 +1,5 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
1
3
  import { Router } from 'express';
2
4
  import { createProxyMiddleware } from 'http-proxy-middleware';
3
5
  import partialRouteHandler from './partial.js';
@@ -9,6 +11,8 @@ import proxyPageResourceRedirect from './proxyPageResourceRedirect.js';
9
11
  import homeRouteHandler from './homeRouteHandler.js';
10
12
  import { debug } from '../lib/debug.js';
11
13
  import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
14
+ import proxyPathPageRouteHandler from './proxyPathPageRouteHandler.js';
15
+ import proxyPathPageResourceRedirect from './proxyPathPageResourceRedirect.js';
12
16
  const STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(domain => `storybook.${domain}`);
13
17
  const createDevServerRoutes = async (viteServer, storybookPort) => {
14
18
  const devServerApp = Router();
@@ -25,11 +29,13 @@ const createDevServerRoutes = async (viteServer, storybookPort) => {
25
29
  }));
26
30
  }
27
31
  devServerApp.use(viteServer.middlewares);
32
+ devServerApp.get('/proxy', proxyPathPageRouteHandler);
28
33
  devServerApp.get('/partials/', linksToAllPartialsRouteHandler);
29
34
  devServerApp.get('/partial/:partial', partialRouteHandler);
30
35
  devServerApp.get('/modules/', linksToAllModulesRouteHandler);
31
36
  devServerApp.get('/module/:moduleName', moduleRouteHandler);
32
37
  devServerApp.get('/', homeRouteHandler);
38
+ devServerApp.get('/*', proxyPathPageResourceRedirect);
33
39
  devServerApp.get('/*', proxyPageResourceRedirect);
34
40
  devServerApp.get('/*', proxyPageRouteHandler);
35
41
  return devServerApp;
@@ -10,9 +10,20 @@ const moduleRouteHandler = async (request, response) => {
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));
13
+ let fieldOverrides = null;
14
+ if (request.query.fields) {
15
+ try {
16
+ if (typeof request.query.fields === 'string') {
17
+ fieldOverrides = JSON.parse(request.query.fields);
18
+ }
19
+ }
20
+ catch (e) {
21
+ console.error(`Error parsing field param for module ${moduleName}: ${request.query.fields}`);
22
+ }
23
+ }
13
24
  const environmentConfig = buildStaticEnvConfig(authedPortalId, authedHublet, authedEnv, false);
14
25
  try {
15
- const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, null, fullOriginalUrlFromRequest(request), environmentConfig);
26
+ const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, fieldOverrides, fullOriginalUrlFromRequest(request), environmentConfig);
16
27
  const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer);
17
28
  const html = htmlShell
18
29
  .replace('<!--headend-->', cssNeeded)
@@ -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, devServerHost, devServerPort, projectName, projectComponentPath, } = request.app.locals;
9
+ const { viteServer, webRoot, projectName, projectComponentPath } = 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, devServerHost, devServerPort, projectName, projectComponentPath, urlToProxy, fullOriginalUrl);
35
+ await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl);
36
36
  }
37
37
  catch (e) {
38
38
  next(e);
@@ -0,0 +1,36 @@
1
+ import fetch from 'node-fetch';
2
+ const HCMS_PATH = '/_hcms/';
3
+ const HS_FS_PATH = '/hs-fs/';
4
+ const HUB_FS_PATH = '/hubfs/';
5
+ // From(ish) https://git.hubteam.com/HubSpot/cloudflare-workers/blob/master/worker-lib/src/Constants.ts
6
+ const isInternalCMSRoute = (req) => req.path.startsWith(HCMS_PATH) ||
7
+ req.path.startsWith(HS_FS_PATH) ||
8
+ req.path.startsWith(HUB_FS_PATH);
9
+ export default function proxyPathPageResourceRedirect(req, res, next) {
10
+ const isAHtmlRequest = req.accepts().includes('text/html');
11
+ // only proxy when referer's path is /proxy && has page query param
12
+ let proxyPageUrl;
13
+ let refererUrl;
14
+ try {
15
+ refererUrl = new URL(req.headers.referer);
16
+ proxyPageUrl = new URL(new URL(req.headers.referer).searchParams.get('page'));
17
+ }
18
+ catch (e) {
19
+ next();
20
+ return;
21
+ }
22
+ if (!refererUrl.pathname.startsWith('/proxy')) {
23
+ next();
24
+ return;
25
+ }
26
+ // handle anchor links, unless internal CMS route
27
+ if (isAHtmlRequest && !isInternalCMSRoute(req)) {
28
+ const encodedPageUrl = encodeURIComponent(`${proxyPageUrl.origin}${req.url}`);
29
+ res.redirect(`/proxy?page=${encodedPageUrl}`);
30
+ return;
31
+ }
32
+ const urlToProxy = `https://${proxyPageUrl.host}${req.url}`;
33
+ fetch(urlToProxy)
34
+ .then(response => response.body.pipe(res))
35
+ .catch(err => console.log(err));
36
+ }
@@ -0,0 +1,43 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /* hs-eslint ignored failing-rules */
3
+ /* eslint-disable consistent-return */
4
+ import { renderOnServer } from '@hubspot/cms-js-internal';
5
+ import fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';
6
+ import proxyPage from '../proxyPage/proxyPage.js';
7
+ import { consoleWarn } from '../proxyPage/utils.js';
8
+ export default async function proxyPathPageRouteHandler(request, response, next) {
9
+ const { viteServer, webRoot, devServerHost, devServerPort, projectName, projectComponentPath, } = request.app.locals;
10
+ if (!request.accepts().includes('text/html')) {
11
+ return response.sendStatus(404);
12
+ }
13
+ // render proxy index page if not supplied with query param
14
+ if (!request.query.page) {
15
+ const { html: responseHtml } = await renderOnServer(_jsxs("div", { children: [_jsx("h2", { children: "Local Proxy" }), _jsxs("form", { action: "/proxy", children: [_jsx("label", { htmlFor: "page", style: { display: 'block' }, children: "Page URL" }), _jsx("input", { style: { width: '300px' }, name: "page", type: "text", placeholder: "https://somecmspage.com/path" }), _jsx("button", { style: { display: 'block' }, children: "Proxy" })] })] }), null, null);
16
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
17
+ return;
18
+ }
19
+ // parse proxy page URL from query param
20
+ let proxyPageUrl;
21
+ try {
22
+ proxyPageUrl = new URL(request.query.page);
23
+ }
24
+ catch (e) {
25
+ const message = 'Please provide a valid page query parameter, e.g., http://localhost:3000/proxy?page=https://yourdomain.com/path';
26
+ consoleWarn(message);
27
+ response.status(400).send(message);
28
+ return;
29
+ }
30
+ // validate proxy page URL query params
31
+ if (proxyPageUrl.searchParams.has('hs_preview')) {
32
+ const message = `Can't make a proxy request, you cannot proxy URLs that include internal query params like hs_preview`;
33
+ consoleWarn(message);
34
+ return response.status(400).send(message);
35
+ }
36
+ try {
37
+ const { portalId, contentId, hublet } = await fetchContentMetadata(proxyPageUrl.href);
38
+ await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, proxyPageUrl.href, proxyPageUrl.href);
39
+ }
40
+ catch (e) {
41
+ next(e);
42
+ }
43
+ }
package/dist/run.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { getDevServerCommandLineOptions } from './lib/cli.js';
3
3
  import createDevServer from './createDevServer.js';
4
- const { webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption, storybook, } = getDevServerCommandLineOptions(process.argv);
4
+ const { webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption, storybook, } = getDevServerCommandLineOptions(process.argv);
5
5
  if (!webRoot) {
6
6
  throw new Error(`No web root path argument specified`);
7
7
  }
8
- createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption);
8
+ createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption);
@@ -0,0 +1,63 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
3
+ import { Router } from 'express';
4
+ import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
5
+ import cors from 'cors';
6
+ import { findLocalRenderPlaceholders } from '../lib/proxyHelpers.js';
7
+ import { makeProxyPreviewRequest } from '../proxyPage/proxyPage.js';
8
+ import fetchPreviewInfo from '../proxyPage/fetchPreviewInfo.js';
9
+ function getShadowDevServerCheckHandler(devServerPort) {
10
+ return async function shadowDevServerCheckHandler(request, response) {
11
+ const { query } = request;
12
+ if (query) {
13
+ const { hostName, pathName, protocol, contentId, portalId: portalIdString, } = query;
14
+ const pageUrl = `${protocol}//${hostName}${pathName}`;
15
+ const portalId = parseInt(portalIdString, 10);
16
+ let accountId;
17
+ let hasJSBuildingBlocks = false;
18
+ let localProxyUrl;
19
+ try {
20
+ accountId = getAccountId(portalId);
21
+ if (accountId === null) {
22
+ throw new Error();
23
+ }
24
+ }
25
+ catch (e) {
26
+ response
27
+ .status(500)
28
+ .end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
29
+ return;
30
+ }
31
+ try {
32
+ const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
33
+ const { previewKey } = previewInfo;
34
+ const pageHtml = await makeProxyPreviewRequest(accountId, pageUrl, previewKey, contentId);
35
+ const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
36
+ if (localRenderPlaceholders.length) {
37
+ hasJSBuildingBlocks = true;
38
+ localProxyUrl = `http://${hostName}.hslocal.net:${devServerPort}${pathName}`;
39
+ }
40
+ response
41
+ .status(200)
42
+ .set({ 'Content-Type': 'application/json' })
43
+ .json({ hasJSBuildingBlocks, localProxyUrl });
44
+ }
45
+ catch (error) {
46
+ response
47
+ .status(500)
48
+ .end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
49
+ return;
50
+ }
51
+ }
52
+ else {
53
+ response
54
+ .status(500)
55
+ .end(`Missing pageUrl param, cannot check for proxied page without a pageUrl`);
56
+ }
57
+ };
58
+ }
59
+ export default async function createShadowDevServerRoutes(devServerPort) {
60
+ const shadowDevServerRoutes = Router();
61
+ shadowDevServerRoutes.get('/check-if-local-dev-server', cors(), getShadowDevServerCheckHandler(devServerPort));
62
+ return shadowDevServerRoutes;
63
+ }
@@ -0,0 +1,31 @@
1
+ import net from 'net';
2
+ import express from 'express';
3
+ import createShadowDevServerRoutes from './createShadowDevServerRoutes.js';
4
+ const testNetServer = net.createServer();
5
+ export default async function startShadowDevServer(devServerPort, shadowPort) {
6
+ const portIsTaken = await new Promise((res, rej) => {
7
+ console.log(`Starting proxy link server on port ${shadowPort}`);
8
+ testNetServer.once('error', err => {
9
+ if (err['code'] === 'EADDRINUSE') {
10
+ console.error(`Port ${shadowPort} is in use. HubSpot is unable to automatically create proxy links in the Sprocket Menu`);
11
+ res(true);
12
+ }
13
+ else {
14
+ rej(err);
15
+ }
16
+ });
17
+ testNetServer.once('listening', () => {
18
+ testNetServer.close();
19
+ });
20
+ testNetServer.once('close', () => {
21
+ res(false);
22
+ });
23
+ testNetServer.listen(shadowPort);
24
+ });
25
+ if (portIsTaken) {
26
+ return;
27
+ }
28
+ const shadowDevServer = express();
29
+ shadowDevServer.listen(shadowPort);
30
+ shadowDevServer.use('/', await createShadowDevServerRoutes(devServerPort));
31
+ }
@@ -1,3 +1,7 @@
1
+ // src/storybook/moduleStory.tsx
2
+ import React, { useEffect } from "react";
3
+ import { renderToStaticMarkup as renderToStaticMarkup2 } from "react-dom/server";
4
+
1
5
  // ../cms-js-internal/dist/index.js
2
6
  import { renderToPipeableStream } from "react-dom/server";
3
7
  import {
@@ -97,14 +101,62 @@ function getNestedFieldObjectForArgs(_args) {
97
101
 
98
102
  // src/storybook/moduleStory.tsx
99
103
  import { jsx as jsx2 } from "react/jsx-runtime";
104
+ function moduleFieldsToJson(fields) {
105
+ let moduleJson;
106
+ const outputCallback = (callbackJson) => {
107
+ moduleJson = callbackJson;
108
+ };
109
+ renderToStaticMarkup2(
110
+ React.cloneElement(fields, {
111
+ outputCallback
112
+ })
113
+ );
114
+ if (!moduleJson) {
115
+ throw new Error("couldn't render module fields definition to fields.json");
116
+ }
117
+ return moduleJson;
118
+ }
100
119
  function moduleStory(ModuleComponent, fields) {
101
120
  const moduleJson = renderFieldsToJson(fields);
102
121
  const argTypes = getFieldsArgTypes(moduleJson);
122
+ const story = (_args) => /* @__PURE__ */ jsx2(ModuleComponent, {
123
+ ..._args
124
+ });
125
+ const storyWithArgs = story.bind({});
126
+ storyWithArgs.argTypes = argTypes;
127
+ storyWithArgs.args = {};
128
+ return storyWithArgs;
129
+ }
130
+ function moduleStoryWithIsland(moduleName, fields) {
131
+ const moduleJson = moduleFieldsToJson(fields);
132
+ const argTypes = getFieldsArgTypes(moduleJson);
103
133
  const story = (_args) => {
104
134
  const fieldValues = getNestedFieldObjectForArgs(_args);
105
- return /* @__PURE__ */ jsx2(ModuleComponent, {
106
- ...fieldValues
107
- });
135
+ const fieldValuesString = JSON.stringify(fieldValues);
136
+ const domain = `${window.location.protocol}//${window.location.hostname.replace("storybook.", "")}:3000`;
137
+ const fieldValuesJson = encodeURIComponent(fieldValuesString);
138
+ const iframeSrc = `${domain}/module/${moduleName}?fields=${fieldValuesJson}`;
139
+ useEffect(() => {
140
+ const existingElement = document.querySelector("#hs-module-iframe");
141
+ if (existingElement) {
142
+ existingElement.setAttribute("src", iframeSrc);
143
+ return () => {
144
+ existingElement.remove();
145
+ };
146
+ }
147
+ const iframeElement = document.createElement("iframe");
148
+ iframeElement.setAttribute("src", iframeSrc);
149
+ iframeElement.setAttribute("id", "hs-module-iframe");
150
+ iframeElement.setAttribute(
151
+ "style",
152
+ `border: none;width: 100%;height: 100%;overflow: auto;`
153
+ );
154
+ document.body.appendChild(iframeElement);
155
+ return () => {
156
+ iframeElement.remove();
157
+ };
158
+ }, [iframeSrc]);
159
+ return /* @__PURE__ */ jsx2("div", {});
108
160
  };
109
161
  const storyWithArgs = story.bind({});
110
162
  storyWithArgs.argTypes = argTypes;
@@ -112,5 +164,7 @@ function moduleStory(ModuleComponent, fields) {
112
164
  return storyWithArgs;
113
165
  }
114
166
  export {
115
- moduleStory
167
+ moduleFieldsToJson,
168
+ moduleStory,
169
+ moduleStoryWithIsland
116
170
  };
@@ -1,13 +1,58 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import React, { useEffect } from 'react';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
2
4
  import { renderFieldsToJson } from '@hubspot/cms-js-internal';
3
5
  import getFieldsArgTypes from './getFieldsArgTypes.js';
4
6
  import getNestedFieldObjectForArgs from './getNestedFieldObjectForArgs.js';
7
+ export function moduleFieldsToJson(fields) {
8
+ let moduleJson;
9
+ const outputCallback = (callbackJson) => {
10
+ moduleJson = callbackJson;
11
+ };
12
+ renderToStaticMarkup(React.cloneElement(fields, {
13
+ outputCallback,
14
+ }));
15
+ if (!moduleJson) {
16
+ throw new Error("couldn't render module fields definition to fields.json");
17
+ }
18
+ return moduleJson;
19
+ }
5
20
  export function moduleStory(ModuleComponent, fields) {
6
21
  const moduleJson = renderFieldsToJson(fields);
7
22
  const argTypes = getFieldsArgTypes(moduleJson);
23
+ const story = (_args) => _jsx(ModuleComponent, { ..._args });
24
+ const storyWithArgs = story.bind({});
25
+ storyWithArgs.argTypes = argTypes;
26
+ storyWithArgs.args = {};
27
+ return storyWithArgs;
28
+ }
29
+ export function moduleStoryWithIsland(moduleName, fields) {
30
+ const moduleJson = moduleFieldsToJson(fields);
31
+ const argTypes = getFieldsArgTypes(moduleJson);
8
32
  const story = (_args) => {
9
33
  const fieldValues = getNestedFieldObjectForArgs(_args);
10
- return _jsx(ModuleComponent, { ...fieldValues });
34
+ const fieldValuesString = JSON.stringify(fieldValues);
35
+ const domain = `${window.location.protocol}//${window.location.hostname.replace('storybook.', '')}:3000`;
36
+ const fieldValuesJson = encodeURIComponent(fieldValuesString);
37
+ const iframeSrc = `${domain}/module/${moduleName}?fields=${fieldValuesJson}`;
38
+ useEffect(() => {
39
+ const existingElement = document.querySelector('#hs-module-iframe');
40
+ if (existingElement) {
41
+ existingElement.setAttribute('src', iframeSrc);
42
+ return () => {
43
+ existingElement.remove();
44
+ };
45
+ }
46
+ const iframeElement = document.createElement('iframe');
47
+ iframeElement.setAttribute('src', iframeSrc);
48
+ iframeElement.setAttribute('id', 'hs-module-iframe');
49
+ iframeElement.setAttribute('style', `border: none;width: 100%;height: 100%;overflow: auto;`);
50
+ document.body.appendChild(iframeElement);
51
+ return () => {
52
+ iframeElement.remove();
53
+ };
54
+ }, [iframeSrc]);
55
+ return _jsx("div", {});
11
56
  };
12
57
  const storyWithArgs = story.bind({});
13
58
  storyWithArgs.argTypes = argTypes;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -8,21 +8,24 @@
8
8
  },
9
9
  "scripts": {
10
10
  "build": "tsc --build && yarn run copy-html && yarn build-types && node scripts/build.mjs",
11
+ "build:watch": "nodemon --exec 'yarn build'",
11
12
  "copy-html": "copyfiles -u 1 'src/html/**' 'dist'",
12
13
  "build-types": "tsc --project tsconfig.types.json",
13
14
  "clean": "tsc --build --clean",
14
- "dev": "nodemon --exec 'ts-node-esm --transpileOnly runWhenDeveloping.ts'",
15
- "dev-inspect": "nodemon --exec 'node --loader ts-node/esm --inspect runWhenDeveloping.ts'",
15
+ "dev": "nodemon --exec 'yarn start'",
16
+ "dev-inspect": "nodemon --exec 'yarn start-inspect'",
16
17
  "es-watch": "esbuild --outfile=dist-esbuild/runWhenDeveloping.cjs --bundle --watch --platform=node --external:fsevents --external:vite --external:react-refresh runWhenDeveloping.ts",
17
18
  "package": "npm run build && npm pack",
18
19
  "prepare": "npm run build",
19
20
  "runBuild": "node dist/run.js",
21
+ "start": "ts-node-esm --transpileOnly runWhenDeveloping.ts",
22
+ "start-inspect": "node --loader ts-node/esm --inspect runWhenDeveloping.ts",
20
23
  "test": "NODE_ENV=test vitest run"
21
24
  },
22
25
  "dependencies": {
23
26
  "@hubspot/cli-lib": "^3.0.12",
24
- "@hubspot/cms-components": "^0.3.3",
25
- "@hubspot/cms-js-internal": "^0.3.3",
27
+ "@hubspot/cms-components": "^0.4.0",
28
+ "@hubspot/cms-js-internal": "^0.4.0",
26
29
  "@storybook/addon-actions": "^7.0.0-beta.19",
27
30
  "@storybook/addon-essentials": "^7.0.0-beta.19",
28
31
  "@storybook/addon-interactions": "^7.0.0-beta.19",
@@ -33,6 +36,7 @@
33
36
  "@storybook/testing-library": "^0.0.13",
34
37
  "@vitejs/plugin-react": "^3.0.0",
35
38
  "ansi-to-html": "0.7.x",
39
+ "cors": "^2.8.5",
36
40
  "debug": "^4.3.4",
37
41
  "express": "^4.17.3",
38
42
  "http-proxy-middleware": "^2.0.6",
@@ -41,20 +45,23 @@
41
45
  "request": "^2.88.2",
42
46
  "typescript": "~4.7.0",
43
47
  "vite": "^4.0.0",
44
- "vite-plugin-inspect": "^0.4.3"
48
+ "vite-plugin-inspect": "^0.4.3",
49
+ "vite-plugin-mkcert": "^1.10.1"
45
50
  },
46
51
  "devDependencies": {
52
+ "@testing-library/dom": "^8.20.0",
47
53
  "@types/express": "^4.17.13",
48
54
  "@types/react": "^18.0.0",
49
55
  "@types/react-dom": "^18.0.0",
50
56
  "copyfiles": "^2.4.1",
57
+ "node-fetch": "^3.3.0",
51
58
  "nodemon": "^2.0.15",
52
59
  "ts-node": "^10.7.0",
53
60
  "vitest": "0.25.8"
54
61
  },
55
- "main": "./dist/createViteDevServer.js",
62
+ "main": "./dist/createDevServer.js",
56
63
  "exports": {
57
- ".": "./dist/createViteDevServer.js",
64
+ ".": "./dist/createDevServer.js",
58
65
  "./storybook": {
59
66
  "types": "./types/storybook/index.d.ts",
60
67
  "default": "./dist/storybook/index.js"
@@ -85,5 +92,5 @@
85
92
  "publishConfig": {
86
93
  "access": "public"
87
94
  },
88
- "gitHead": "d5b1da55b81aef5a486b5298a3c65f6e3f8e5ef7"
95
+ "gitHead": "9b7c19f05fd3befbddfa392c4d2029e883e701f2"
89
96
  }
@@ -1,2 +1,5 @@
1
1
  import React from 'react';
2
+ import { Field } from '@hubspot/cms-components/fields';
3
+ export declare function moduleFieldsToJson(fields: JSX.Element): Field[];
2
4
  export declare function moduleStory(ModuleComponent: React.ComponentType, fields: JSX.Element): any;
5
+ export declare function moduleStoryWithIsland(moduleName: string, fields: JSX.Element): any;