@hubspot/cms-dev-server 0.3.4 → 0.4.1

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,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);