@hubspot/cms-dev-server 0.3.4 → 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.
@@ -1,20 +1,26 @@
1
1
  import path from 'path';
2
2
  import url from 'url';
3
3
  import express from 'express';
4
+ import http from 'http';
5
+ import bodyParser from 'body-parser';
4
6
  import { spawn } from 'child_process';
5
7
  import { normalizePath } from 'vite';
6
8
  import createDevServerRoutes from './routes/createDevServerRoutes.js';
7
9
  import startShadowDevServer from './shadowDevServer/startShadowDevServer.js';
8
10
  import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
9
11
  import createViteDevServer from './createViteDevServer.js';
12
+ import { createHttpsRedirectingServer } from './lib/httpsRedirectingServer.js';
10
13
  import { debug } from './lib/debug.js';
11
14
  import { getEnv, getAccountId, loadConfig, validateConfig, } from '@hubspot/cli-lib/lib/config.js';
15
+ import { fetchWebsiteDomainNames } from './proxyPage/fetchDomains.js';
16
+ import { logMissingScopeWarning, MissingScopeError } from './lib/errors.js';
12
17
  const BASE_PATH = '/';
13
18
  const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
19
+ const SHADOW_PORT = 1442;
14
20
  const STORYBOOK_PORT = process.env.STORYBOOK_PORT
15
21
  ? parseInt(process.env.STORYBOOK_PORT, 10)
16
22
  : 3123;
17
- async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption) {
23
+ async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption) {
18
24
  console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
19
25
  let authedPortalId = null;
20
26
  let authedEnv = null;
@@ -44,12 +50,35 @@ If needed you can refer to another config file with --config.
44
50
 
45
51
  Local proxy functionality will not work without setting up authentication.`);
46
52
  }
53
+ let domainsToProxy = [];
54
+ if (sslEnabledOption && authedPortalId) {
55
+ try {
56
+ const portalDomains = await fetchWebsiteDomainNames(authedPortalId);
57
+ domainsToProxy = (process.env.DOMAINS_TO_PROXY || '')
58
+ .split(',')
59
+ .filter(d => !!d);
60
+ domainsToProxy = [...domainsToProxy, ...portalDomains];
61
+ }
62
+ catch (e) {
63
+ if (e instanceof MissingScopeError) {
64
+ logMissingScopeWarning(e);
65
+ }
66
+ else {
67
+ console.warn(`Failed to fetch domains for ${authedPortalId}, HTTPS proxying won't work with them.`);
68
+ }
69
+ }
70
+ }
47
71
  const authedHublet = 'na1';
48
72
  const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
49
73
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
74
+ const viteServer = await createViteDevServer(absoluteWebRoot, PORT, sslEnabledOption, domainsToProxy);
75
+ // Get https key and cert from the vite config set by vite-plugin-mkcert (if it worked )
76
+ const viteHTTPSConfig = viteServer.config.server.https;
77
+ const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
78
+ const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
79
+ const httpServers = [];
50
80
  const expressServer = express();
51
- const viteServer = await createViteDevServer(absoluteWebRoot);
52
- expressServer.locals.devServerHost = 'localhost';
81
+ expressServer.locals.devServerHost = 'hslocal.net';
53
82
  expressServer.locals.devServerPort = PORT;
54
83
  expressServer.locals.webRoot = webRoot;
55
84
  expressServer.locals.viteServer = viteServer;
@@ -60,10 +89,30 @@ Local proxy functionality will not work without setting up authentication.`);
60
89
  expressServer.locals.storybookPort = STORYBOOK_PORT;
61
90
  expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
62
91
  expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
92
+ expressServer.use(bodyParser.json());
63
93
  expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer, storybook ? STORYBOOK_PORT : null));
64
- const httpServer = expressServer.listen(PORT);
65
- startShadowDevServer(PORT);
94
+ if (sslEnabledOption) {
95
+ if (httpsKey && httpsCert) {
96
+ const { server, innerHTTPServer, innerHTTPSServer } = createHttpsRedirectingServer({ key: httpsKey, cert: httpsCert }, expressServer);
97
+ server.listen(PORT);
98
+ httpServers.push(server);
99
+ // Not sure if we need to worry about closing all of these, but🤷
100
+ httpServers.push(innerHTTPServer);
101
+ httpServers.push(innerHTTPSServer);
102
+ }
103
+ else {
104
+ console.error('Failed to start a HTTPS server, try --no-ssl');
105
+ process.exit(1);
106
+ }
107
+ }
108
+ else {
109
+ const httpServer = http.createServer(expressServer);
110
+ httpServer.listen(PORT);
111
+ httpServers.push(httpServer);
112
+ }
113
+ startShadowDevServer(PORT, SHADOW_PORT);
66
114
  let extraServerInfo = '';
115
+ const protocol = sslEnabledOption ? 'https' : 'http';
67
116
  if (authedPortalId) {
68
117
  extraServerInfo += `, hubid=${authedPortalId}`;
69
118
  }
@@ -71,7 +120,7 @@ Local proxy functionality will not work without setting up authentication.`);
71
120
  extraServerInfo += `, env=${authedEnv}`;
72
121
  }
73
122
  console.log(`
74
- HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at http://localhost:${PORT}${extraServerInfo})
123
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
75
124
  `);
76
125
  if (storybook) {
77
126
  const packageRoot = path.dirname(url.fileURLToPath(import.meta.url));
@@ -101,12 +150,12 @@ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressSer
101
150
  // Return hook to shut down server gracefully
102
151
  return {
103
152
  close: () => {
104
- const httpServerClosePromise = new Promise(resolve => {
105
- httpServer.close(() => {
153
+ const serverClosePromises = httpServers.map(server => new Promise(resolve => {
154
+ server.close(() => {
106
155
  resolve(null);
107
156
  });
108
- });
109
- return Promise.allSettled([httpServerClosePromise, viteServer.close()]);
157
+ }));
158
+ return Promise.allSettled([...serverClosePromises, viteServer.close()]);
110
159
  },
111
160
  };
112
161
  }
@@ -1,13 +1,30 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
1
3
  import { createServer as createViteServer } from 'vite';
2
4
  import { default as react } from '@vitejs/plugin-react';
3
5
  import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
4
- const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
5
- async function createViteDevServer(webRoot) {
6
+ import mkcert from 'vite-plugin-mkcert';
7
+ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = []) {
8
+ const additionalMkcertHosts = domainsToProxy
9
+ .map(proxyDomain => [
10
+ `${proxyDomain}.localhost`,
11
+ `${proxyDomain}.hslocal.net`,
12
+ ])
13
+ .flat();
14
+ additionalMkcertHosts.push('*.hslocal.net', 'hslocal.net');
15
+ const origin = sslEnabled
16
+ ? `https://hslocal.net:${port}`
17
+ : `http://hslocal.net:${port}`;
6
18
  const viteConfig = {
7
19
  appType: 'custom',
8
20
  server: {
9
21
  middlewareMode: true,
10
- origin: `http://localhost:${PORT}`,
22
+ host: 'hslocal.net',
23
+ origin,
24
+ https: sslEnabled,
25
+ hmr: {
26
+ protocol: sslEnabled ? 'wss' : undefined,
27
+ },
11
28
  },
12
29
  ssr: {
13
30
  // TODO: might need more entries here to get things to resolve through
@@ -20,10 +37,14 @@ async function createViteDevServer(webRoot) {
20
37
  optimizeDeps: {
21
38
  include: ['react', 'react-dom', 'react-dom/client'],
22
39
  },
40
+ plugins: [
41
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
42
+ react(),
43
+ resolveIslandPlugin(),
44
+ ],
23
45
  css: {
24
46
  postcss: webRoot,
25
47
  },
26
- plugins: [react(), resolveIslandPlugin()],
27
48
  };
28
49
  return createViteServer(viteConfig);
29
50
  }
Binary file
package/dist/index.js CHANGED
@@ -1 +1,84 @@
1
- export { default as createViteDevServer } from './createViteDevServer.js';
1
+ // src/createViteDevServer.ts
2
+ import { createServer as createViteServer } from "vite";
3
+ import { default as react } from "@vitejs/plugin-react";
4
+
5
+ // ../cms-js-internal/dist/index.js
6
+ import path from "path";
7
+ import stream from "stream";
8
+ import { renderToPipeableStream } from "react-dom/server";
9
+ import {
10
+ ServerRenderContext,
11
+ createServerRenderContext
12
+ } from "@hubspot/cms-components";
13
+ import { jsx } from "react/jsx-runtime";
14
+ import path2 from "path";
15
+ import { existsSync, readdirSync, lstatSync } from "fs";
16
+ import { join as joinPosix } from "path/posix";
17
+ import { basename } from "path";
18
+ import { cloneElement } from "react";
19
+ import { renderToStaticMarkup } from "react-dom/server";
20
+ var viteRoot;
21
+ var viteCommand;
22
+ function resolveIslandPlugin() {
23
+ return {
24
+ enforce: "pre",
25
+ name: "resolve-islands",
26
+ configResolved(config) {
27
+ viteRoot = config.root;
28
+ viteCommand = config.command;
29
+ },
30
+ load(id) {
31
+ if (id.endsWith("?island")) {
32
+ const [idWithNoParam] = id.split("?");
33
+ const componentExtension = path.extname(idWithNoParam);
34
+ const componentFilenameWithNoExtension = path.basename(
35
+ idWithNoParam,
36
+ componentExtension
37
+ );
38
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
39
+ return `
40
+ const moduleId = '${viteCommand === "serve" ? idWithNoParam : modulePath}';
41
+
42
+ const lazyComponent = () => import('${idWithNoParam}');
43
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
44
+ lazyComponent.moduleId = moduleId;
45
+
46
+ export default lazyComponent;
47
+ `;
48
+ }
49
+ return null;
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/createViteDevServer.ts
55
+ var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
56
+ async function createViteDevServer(webRoot) {
57
+ const viteConfig = {
58
+ appType: "custom",
59
+ server: {
60
+ middlewareMode: true,
61
+ origin: `http://localhost:${PORT}`
62
+ },
63
+ ssr: {
64
+ // TODO: might need more entries here to get things to resolve through
65
+ // resolveWebRootDepsPlugin
66
+ noExternal: "@hubspot/cms-components"
67
+ },
68
+ resolve: {
69
+ dedupe: ["react", "react-dom", "@hubspot/cms-components"]
70
+ },
71
+ optimizeDeps: {
72
+ include: ["react", "react-dom", "react-dom/client"]
73
+ },
74
+ css: {
75
+ postcss: webRoot
76
+ },
77
+ plugins: [react(), resolveIslandPlugin()]
78
+ };
79
+ return createViteServer(viteConfig);
80
+ }
81
+ var createViteDevServer_default = createViteDevServer;
82
+ export {
83
+ createViteDevServer_default as createViteDevServer
84
+ };
@@ -0,0 +1,390 @@
1
+ // ../cms-js-internal/dist/index.js
2
+ import path from "path";
3
+ import stream from "stream";
4
+ import { renderToPipeableStream } from "react-dom/server";
5
+ import {
6
+ ServerRenderContext,
7
+ createServerRenderContext
8
+ } from "@hubspot/cms-components";
9
+ import { jsx } from "react/jsx-runtime";
10
+ import path2 from "path";
11
+ import { existsSync, readdirSync, lstatSync } from "fs";
12
+ import { join as joinPosix } from "path/posix";
13
+ import { basename } from "path";
14
+ import { cloneElement } from "react";
15
+ import { renderToStaticMarkup } from "react-dom/server";
16
+ var collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
17
+ const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
18
+ modulePathToStartWith
19
+ );
20
+ if (!appModulesForPath || appModulesForPath.size === 0) {
21
+ throw new Error(`No modules at: ${modulePathToStartWith}`);
22
+ } else if (appModulesForPath.size > 1) {
23
+ throw new Error(`More than one module at: ${modulePathToStartWith}`);
24
+ }
25
+ const appModule = Array.from(appModulesForPath.values())[0];
26
+ const allServerSideModulesImported = /* @__PURE__ */ new Set();
27
+ const newCssModules = [];
28
+ const moduleQueue = Array.from(appModule.importedModules);
29
+ for (const importedModule of moduleQueue) {
30
+ if (allServerSideModulesImported.has(importedModule.id)) {
31
+ continue;
32
+ }
33
+ allServerSideModulesImported.add(importedModule.id);
34
+ const isCss = importedModule.file.endsWith(".css");
35
+ const moduleModulesToQueue = Array.from(importedModule.importedModules);
36
+ if (isCss && !cssModulesImported.has(importedModule)) {
37
+ cssModulesImported.add(importedModule);
38
+ newCssModules.push(importedModule);
39
+ }
40
+ moduleQueue.push(...moduleModulesToQueue);
41
+ }
42
+ return newCssModules;
43
+ };
44
+ function createPreloadLink(assetPath, basePath = "") {
45
+ if (assetPath && assetPath[0] !== "/") {
46
+ assetPath = `/${assetPath}`;
47
+ }
48
+ if (assetPath.endsWith(".js")) {
49
+ return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
50
+ } else if (assetPath.endsWith(".css")) {
51
+ return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
52
+ } else if (assetPath.endsWith(".woff")) {
53
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
54
+ } else if (assetPath.endsWith(".woff2")) {
55
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
56
+ } else if (assetPath.endsWith(".gif")) {
57
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
58
+ } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
59
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
60
+ } else if (assetPath.endsWith(".png")) {
61
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
62
+ } else {
63
+ throw new Error(`Unknown preload type for ${assetPath}`);
64
+ }
65
+ }
66
+ var collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
67
+ return `${collectCssModules(
68
+ modulePathToStartWith,
69
+ viteServer,
70
+ cssModulesImported
71
+ ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
72
+ `;
73
+ };
74
+ var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
75
+ const indentString = new Array(indent).fill(" ").join("");
76
+ return `window.__islands = ${JSON.stringify(
77
+ tweakedIslandsArray.map(
78
+ ({
79
+ id,
80
+ moduleName,
81
+ moduleId,
82
+ props,
83
+ hydrateOn,
84
+ clientOnly,
85
+ priority,
86
+ url
87
+ }) => {
88
+ return {
89
+ id,
90
+ moduleName,
91
+ moduleId,
92
+ props,
93
+ hydrateOn,
94
+ clientOnly,
95
+ priority,
96
+ url
97
+ };
98
+ }
99
+ ),
100
+ null,
101
+ 2
102
+ ).replace(/\n/gm, `
103
+ ${indentString}`)};`;
104
+ };
105
+ function getIslandUrls(roots, viteDevServer) {
106
+ return roots.map((island) => {
107
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
108
+ island.moduleId
109
+ );
110
+ if (!islandModule) {
111
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
112
+ }
113
+ const tweakedIsland = {
114
+ ...island,
115
+ url: islandModule.url
116
+ };
117
+ return tweakedIsland;
118
+ });
119
+ }
120
+ var createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
121
+ return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
122
+ };
123
+ var viteRoot;
124
+ var viteCommand;
125
+ function resolveIslandPlugin() {
126
+ return {
127
+ enforce: "pre",
128
+ name: "resolve-islands",
129
+ configResolved(config) {
130
+ viteRoot = config.root;
131
+ viteCommand = config.command;
132
+ },
133
+ load(id) {
134
+ if (id.endsWith("?island")) {
135
+ const [idWithNoParam] = id.split("?");
136
+ const componentExtension = path.extname(idWithNoParam);
137
+ const componentFilenameWithNoExtension = path.basename(
138
+ idWithNoParam,
139
+ componentExtension
140
+ );
141
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
142
+ return `
143
+ const moduleId = '${viteCommand === "serve" ? idWithNoParam : modulePath}';
144
+
145
+ const lazyComponent = () => import('${idWithNoParam}');
146
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
147
+ lazyComponent.moduleId = moduleId;
148
+
149
+ export default lazyComponent;
150
+ `;
151
+ }
152
+ return null;
153
+ }
154
+ };
155
+ }
156
+ var promiseForNewWritableStream = () => {
157
+ const chunks = [];
158
+ const writableStream = new stream.Writable();
159
+ writableStream._write = (chunk, encoding, done) => {
160
+ chunks.push(Buffer.from(chunk));
161
+ done();
162
+ };
163
+ const streamDonePromise = new Promise((resolve, reject) => {
164
+ writableStream.on("error", (error) => {
165
+ reject(error);
166
+ });
167
+ writableStream._final = (done) => {
168
+ resolve(Buffer.concat(chunks).toString("utf8"));
169
+ done();
170
+ };
171
+ });
172
+ return { streamDonePromise, writableStream };
173
+ };
174
+ var renderStreamToPromise = async (reactElements) => {
175
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
176
+ const {
177
+ pipe
178
+ /* abort */
179
+ } = renderToPipeableStream(reactElements, {
180
+ onShellReady() {
181
+ },
182
+ onAllReady() {
183
+ pipe(writableStream);
184
+ }
185
+ // We will log the error sent to the writable, any need to do something in these callbacks?
186
+ // onShellError(error) {},
187
+ // onError(error) {},
188
+ });
189
+ return streamDonePromise;
190
+ };
191
+ var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
192
+ if (!messagesForBrowser) {
193
+ return "";
194
+ }
195
+ const consoleLines = [];
196
+ for (const message of messagesForBrowser) {
197
+ const funcString = message.level === "error" ? "console.error" : "console.warn";
198
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
199
+ consoleLines.push(` ${funcString}(${argString});`);
200
+ }
201
+ let groupStart = "";
202
+ let groupEnd = "";
203
+ if (groupLabel !== null) {
204
+ groupStart = `
205
+ console.group(${JSON.stringify(groupLabel)});`;
206
+ groupEnd = ` console.groupEnd()
207
+ `;
208
+ }
209
+ return `<script>${groupStart}
210
+ ${consoleLines.join("\n")}
211
+ ${groupEnd}</script>
212
+ `;
213
+ };
214
+ async function renderComponentOnServer(Component, props, pageUrl, environmentConfig) {
215
+ const componentDebugName = Component.displayName || Component.name;
216
+ return renderOnServer(
217
+ /* @__PURE__ */ jsx(Component, { ...props }),
218
+ pageUrl,
219
+ environmentConfig,
220
+ componentDebugName
221
+ );
222
+ }
223
+ async function renderOnServer(elements, pageUrl, environmentConfig, debugName) {
224
+ const renderContext = createServerRenderContext(pageUrl, environmentConfig);
225
+ let html = await renderStreamToPromise(
226
+ /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements })
227
+ );
228
+ if (renderContext.messagesForBrowser.length > 0) {
229
+ html = `${html}${scriptTagToLogServerMessages(
230
+ renderContext.messagesForBrowser,
231
+ `Server messages rendering: ${debugName}`
232
+ )}`;
233
+ }
234
+ return { html, renderContext };
235
+ }
236
+ var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
237
+ var ENTRY_POINTS_PATH = "components/partials/";
238
+ var MODULE_FOLDER_PATH = "components/modules/";
239
+ var VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
240
+ var VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
241
+ var getComponentExtension = (componentPath) => {
242
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
243
+ (ext) => componentPath.endsWith(ext)
244
+ );
245
+ if (filteredExtensions.length === 1) {
246
+ return filteredExtensions[0];
247
+ }
248
+ return void 0;
249
+ };
250
+ var hasComponentExtension = (componentPath) => {
251
+ return !!getComponentExtension(componentPath);
252
+ };
253
+ var isStorybookStory = (componentPath) => {
254
+ return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
255
+ };
256
+ var removeComponentExtension = (componentPath) => {
257
+ const ext = getComponentExtension(componentPath);
258
+ if (ext == null) {
259
+ return componentPath;
260
+ }
261
+ return componentPath.slice(0, -1 * ext.length);
262
+ };
263
+ var findAllComponentsIn = (webRoot, componentsFolder, includeSubdirIndexJS) => {
264
+ const fullComponentsFolderPath = joinPosix(webRoot, componentsFolder);
265
+ const componentsByName = {};
266
+ if (!existsSync(fullComponentsFolderPath)) {
267
+ return componentsByName;
268
+ }
269
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
270
+ const fullPath = joinPosix(fullComponentsFolderPath, fileOrFolderName);
271
+ const subdirPath = joinPosix(componentsFolder, fileOrFolderName);
272
+ const isDirectory = lstatSync(fullPath).isDirectory();
273
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
274
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
275
+ componentsByName[subdirPathNoExtension] = subdirPath;
276
+ } else if (isDirectory && includeSubdirIndexJS) {
277
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
278
+ const potentialIndexModule = joinPosix(
279
+ subdirPath,
280
+ `index${potentialExtension}`
281
+ );
282
+ const fullPotentialPath = joinPosix(
283
+ fullPath,
284
+ `index${potentialExtension}`
285
+ );
286
+ if (existsSync(fullPotentialPath)) {
287
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
288
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ });
294
+ return componentsByName;
295
+ };
296
+ var findAllComponentsIn_default = findAllComponentsIn;
297
+ function findAllModulesInRoot(webRoot) {
298
+ const allModuleComponents = findAllComponentsIn_default(
299
+ webRoot,
300
+ "./components/modules",
301
+ true
302
+ );
303
+ const moduleNames = Object.keys(allModuleComponents).map(
304
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
305
+ );
306
+ const moduleSubpaths = Object.keys(allModuleComponents);
307
+ return { moduleNames, moduleSubpaths };
308
+ }
309
+ function findAllPartialsInRoot(webRoot) {
310
+ const allPartialComponents = findAllComponentsIn_default(
311
+ webRoot,
312
+ "./components/partials",
313
+ false
314
+ );
315
+ const partialSubpaths = Object.keys(allPartialComponents);
316
+ const partialNames = partialSubpaths.map(
317
+ (partialSubpath) => basename(partialSubpath)
318
+ );
319
+ return { partialNames, partialSubpaths };
320
+ }
321
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl) {
322
+ const globals = [
323
+ `window.__hsEnvConfig = ${JSON.stringify(environmentConfig.toJSON())};`
324
+ ];
325
+ if (hsServerPageUrl) {
326
+ globals.push(`window.__hsServerPageUrl = '${hsServerPageUrl}';`);
327
+ }
328
+ return `
329
+ <script type="text/javascript">
330
+ ${globals.join("\n ")}
331
+ </script>
332
+ `;
333
+ }
334
+ function setIn(object, nestedKeysArray, value) {
335
+ let curr = object;
336
+ const finalKey = nestedKeysArray.pop();
337
+ for (let index = 0; index < nestedKeysArray.length; index++) {
338
+ const currentKey = nestedKeysArray[index];
339
+ const nextKey = nestedKeysArray[index + 1];
340
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
341
+ if (curr[currentKey] === void 0) {
342
+ curr[currentKey] = [];
343
+ }
344
+ }
345
+ if (curr[currentKey] === void 0) {
346
+ curr[currentKey] = {};
347
+ }
348
+ curr = curr[currentKey];
349
+ }
350
+ if (value !== void 0) {
351
+ curr[finalKey] = value;
352
+ }
353
+ }
354
+ function renderFieldsToJson(fields) {
355
+ let moduleJson;
356
+ const outputCallback = (callbackJson) => {
357
+ moduleJson = callbackJson;
358
+ };
359
+ renderToStaticMarkup(
360
+ cloneElement(fields, {
361
+ outputCallback
362
+ })
363
+ );
364
+ return moduleJson;
365
+ }
366
+ export {
367
+ COMPONENT_EXTENSIONS,
368
+ ENTRY_POINTS_PATH,
369
+ MODULE_FOLDER_PATH,
370
+ VIRTUAL_CONFIG_SETUP,
371
+ VIRTUAL_ISLAND_RUNTIME,
372
+ collectCssInDev,
373
+ collectCssModules,
374
+ createIslandsGlobalJsForClientInDev,
375
+ findAllComponentsIn_default as findAllComponentsIn,
376
+ findAllModulesInRoot,
377
+ findAllPartialsInRoot,
378
+ getComponentExtension,
379
+ getIslandUrls,
380
+ getServerGlobalsToInject,
381
+ hasComponentExtension,
382
+ isStorybookStory,
383
+ removeComponentExtension,
384
+ renderComponentOnServer,
385
+ renderFieldsToJson,
386
+ renderOnServer,
387
+ renderStreamToPromise,
388
+ resolveIslandPlugin,
389
+ setIn
390
+ };
package/dist/lib/cli.js CHANGED
@@ -15,11 +15,13 @@ export function getDevServerCommandLineOptions(argv) {
15
15
  hubspotCliAccountNameOption = args[accountOptionIndex + 1];
16
16
  args.splice(accountOptionIndex, 2);
17
17
  }
18
+ const sslEnabledOption = args.includes('--ssl') && !args.includes('--no-ssl');
18
19
  const storybook = args.findIndex(arg => arg === '--storybook') > 0;
19
20
  return {
20
- webRoot,
21
21
  hubspotCliConfigPathOption,
22
22
  hubspotCliAccountNameOption,
23
+ sslEnabledOption,
23
24
  storybook,
25
+ webRoot,
24
26
  };
25
27
  }
@@ -0,0 +1,22 @@
1
+ const MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.\nYou may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account\n`;
2
+ const OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
3
+ const NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
4
+ export class MissingScopeError extends Error {
5
+ constructor(error) {
6
+ let messageEnd = '';
7
+ if (error.error.message.match(OAUTH_ERROR_REGEX)) {
8
+ messageEnd = error.error.message;
9
+ }
10
+ super(`${MISSING_SCOPE_ERROR_PREFIX}\n${messageEnd}`);
11
+ // Set the prototype explicitly.
12
+ Object.setPrototypeOf(this, MissingScopeError.prototype);
13
+ }
14
+ }
15
+ export function logMissingScopeWarning(error) {
16
+ console.warn(error.message);
17
+ }
18
+ export function isMissingScopeError(error) {
19
+ return (error.statusCode === 403 &&
20
+ (error.error.message.match(OAUTH_ERROR_REGEX) ||
21
+ error.error.message.startsWith(NOT_PUBLIC_USE_ERROR)));
22
+ }
@@ -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
+ }
@@ -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';
@@ -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);
@@ -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, devServerHost, devServerPort, projectName, projectComponentPath, proxyPageUrl.href, proxyPageUrl.href);
38
+ await proxyPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, proxyPageUrl.href, proxyPageUrl.href);
39
39
  }
40
40
  catch (e) {
41
41
  next(e);
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);
@@ -1,3 +1,5 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
1
3
  import { Router } from 'express';
2
4
  import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
3
5
  import cors from 'cors';
@@ -16,6 +18,9 @@ function getShadowDevServerCheckHandler(devServerPort) {
16
18
  let localProxyUrl;
17
19
  try {
18
20
  accountId = getAccountId(portalId);
21
+ if (accountId === null) {
22
+ throw new Error();
23
+ }
19
24
  }
20
25
  catch (e) {
21
26
  response
@@ -1,14 +1,13 @@
1
1
  import net from 'net';
2
2
  import express from 'express';
3
3
  import createShadowDevServerRoutes from './createShadowDevServerRoutes.js';
4
- const SHADOW_PORT = 1442;
5
4
  const testNetServer = net.createServer();
6
- export default async function startShadowDevServer(devServerPort) {
5
+ export default async function startShadowDevServer(devServerPort, shadowPort) {
7
6
  const portIsTaken = await new Promise((res, rej) => {
8
- console.log(`Starting proxy link server on port ${SHADOW_PORT}`);
7
+ console.log(`Starting proxy link server on port ${shadowPort}`);
9
8
  testNetServer.once('error', err => {
10
9
  if (err['code'] === 'EADDRINUSE') {
11
- console.error(`Port ${SHADOW_PORT} is in use. HubSpot is unable to automatically create proxy links in the Sprocket Menu`);
10
+ console.error(`Port ${shadowPort} is in use. HubSpot is unable to automatically create proxy links in the Sprocket Menu`);
12
11
  res(true);
13
12
  }
14
13
  else {
@@ -21,12 +20,12 @@ export default async function startShadowDevServer(devServerPort) {
21
20
  testNetServer.once('close', () => {
22
21
  res(false);
23
22
  });
24
- testNetServer.listen(SHADOW_PORT);
23
+ testNetServer.listen(shadowPort);
25
24
  });
26
25
  if (portIsTaken) {
27
26
  return;
28
27
  }
29
28
  const shadowDevServer = express();
30
- shadowDevServer.listen(SHADOW_PORT);
29
+ shadowDevServer.listen(shadowPort);
31
30
  shadowDevServer.use('/', await createShadowDevServerRoutes(devServerPort));
32
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.4",
3
+ "version": "0.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -24,8 +24,8 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@hubspot/cli-lib": "^3.0.12",
27
- "@hubspot/cms-components": "^0.3.4",
28
- "@hubspot/cms-js-internal": "^0.3.4",
27
+ "@hubspot/cms-components": "^0.4.0",
28
+ "@hubspot/cms-js-internal": "^0.4.0",
29
29
  "@storybook/addon-actions": "^7.0.0-beta.19",
30
30
  "@storybook/addon-essentials": "^7.0.0-beta.19",
31
31
  "@storybook/addon-interactions": "^7.0.0-beta.19",
@@ -45,7 +45,8 @@
45
45
  "request": "^2.88.2",
46
46
  "typescript": "~4.7.0",
47
47
  "vite": "^4.0.0",
48
- "vite-plugin-inspect": "^0.4.3"
48
+ "vite-plugin-inspect": "^0.4.3",
49
+ "vite-plugin-mkcert": "^1.10.1"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@testing-library/dom": "^8.20.0",
@@ -91,5 +92,5 @@
91
92
  "publishConfig": {
92
93
  "access": "public"
93
94
  },
94
- "gitHead": "ca8cb386c6ffeea1474ef31811be525db2c69c97"
95
+ "gitHead": "9b7c19f05fd3befbddfa392c4d2029e883e701f2"
95
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;