@hubspot/cms-dev-server 0.16.7 → 0.16.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run.js CHANGED
@@ -80,13 +80,13 @@ function getDevServerCommandLineOptions(argv) {
80
80
  }
81
81
 
82
82
  // src/createDevServer.ts
83
- import path9 from "path";
83
+ import path10 from "path";
84
84
  import url2 from "url";
85
85
  import express2 from "express";
86
86
  import http3 from "http";
87
87
  import bodyParser from "body-parser";
88
88
  import { spawn } from "child_process";
89
- import { normalizePath as normalizePath6 } from "vite";
89
+ import { normalizePath as normalizePath7 } from "vite";
90
90
  import { Transform } from "stream";
91
91
 
92
92
  // src/routes/createDevServerRoutes.ts
@@ -94,8 +94,8 @@ import { Router } from "express";
94
94
  import { createProxyMiddleware } from "http-proxy-middleware";
95
95
 
96
96
  // src/routes/partial.ts
97
- import path3 from "path";
98
- import { normalizePath as normalizePath2 } from "vite";
97
+ import path5 from "path";
98
+ import { normalizePath as normalizePath4 } from "vite";
99
99
 
100
100
  // src/lib/fullOriginalUrlFromRequest.ts
101
101
  function fullOriginalUrlFromRequest(request2) {
@@ -300,7 +300,8 @@ function getCMSAssetConfig(webRoot2) {
300
300
  }
301
301
  var ENABLED_FEATURES_GATE_MAP = {
302
302
  "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
303
- "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin"
303
+ "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
304
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
304
305
  };
305
306
  function isUngatedFor(gates, gate) {
306
307
  return gates.includes(gate);
@@ -412,6 +413,9 @@ function setIn(object, nestedKeysArray, value) {
412
413
 
413
414
  // ../cms-js-internal/dist/index.js
414
415
  import * as dotProp from "dot-prop";
416
+ import * as parser from "@babel/parser";
417
+ import _traverse from "@babel/traverse";
418
+ import * as t from "@babel/types";
415
419
  import { jsx } from "react/jsx-runtime";
416
420
  import stream from "stream";
417
421
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
@@ -597,6 +601,180 @@ function noncePlaceholderPlugin() {
597
601
  }
598
602
  };
599
603
  }
604
+ var traverse = _traverse.default;
605
+ var CMS_MODULE_COMPONENT_NAME = "UnstableModule";
606
+ function findCmsModules(cmsModules = {}) {
607
+ let config;
608
+ return {
609
+ enforce: "pre",
610
+ name: "findCmsModules",
611
+ configResolved(resolvedConfig) {
612
+ config = resolvedConfig;
613
+ },
614
+ transform(code, id) {
615
+ const moduleInfo = this.getModuleInfo(id);
616
+ const isExternal = config.command === "serve" ? false : moduleInfo.isExternal;
617
+ if (isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME)) {
618
+ return null;
619
+ }
620
+ const localCmsModules = {};
621
+ const sourceAst = parser.parse(code, {
622
+ sourceType: "module",
623
+ plugins: ["jsx", "typescript"]
624
+ });
625
+ let unstableModuleLocalName = CMS_MODULE_COMPONENT_NAME;
626
+ const pluginError = this.error.bind(this);
627
+ traverse(sourceAst, {
628
+ ImportDeclaration(path11) {
629
+ if (!t.isStringLiteral(path11.node.source, {
630
+ value: "@hubspot/cms-components"
631
+ })) {
632
+ return null;
633
+ }
634
+ for (const specifier of path11.node.specifiers) {
635
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
636
+ name: CMS_MODULE_COMPONENT_NAME
637
+ })) {
638
+ unstableModuleLocalName = specifier.local.name;
639
+ }
640
+ }
641
+ },
642
+ JSXOpeningElement(path11) {
643
+ if (!t.isJSXIdentifier(path11.node.name, {
644
+ name: unstableModuleLocalName
645
+ }) || path11.node.attributes.length !== 2) {
646
+ return null;
647
+ }
648
+ let cmsModuleName;
649
+ let cmsModulePath;
650
+ for (const prop of path11.node.attributes) {
651
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
652
+ cmsModuleName = prop.value.value;
653
+ continue;
654
+ }
655
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
656
+ cmsModulePath = prop.value.value;
657
+ continue;
658
+ }
659
+ pluginError(
660
+ new Error(
661
+ `Error: ${id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
662
+ )
663
+ );
664
+ }
665
+ const cmsModuleProps = {
666
+ name: cmsModuleName,
667
+ path: cmsModulePath
668
+ };
669
+ if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {
670
+ pluginError(
671
+ new Error(
672
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
673
+ )
674
+ );
675
+ }
676
+ localCmsModules[cmsModuleProps.name] = cmsModuleProps;
677
+ }
678
+ });
679
+ return {
680
+ meta: {
681
+ findCmsModules: localCmsModules
682
+ }
683
+ };
684
+ },
685
+ buildEnd(error) {
686
+ if (error)
687
+ throw error;
688
+ const modulesWithCmsModuleUsage = Array.of(
689
+ ...this.getModuleIds()
690
+ ).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => this.getModuleInfo(moduleId)).filter(
691
+ (moduleInfo) => Object.hasOwn(moduleInfo.meta, "findCmsModules")
692
+ );
693
+ const moduleToEntryPoints = {};
694
+ for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
695
+ moduleToEntryPoints[moduleWithCmsModuleUsage.id] = findEntryPoints(
696
+ this,
697
+ moduleWithCmsModuleUsage
698
+ );
699
+ }
700
+ for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
701
+ const usageInModuleEntryPoint = moduleToEntryPoints[moduleWithCmsModuleUsage.id].find((entryPoint) => entryPoint.id.includes("/components/modules"));
702
+ if (usageInModuleEntryPoint) {
703
+ this.error(`
704
+ Error: <${CMS_MODULE_COMPONENT_NAME} /> can only be used in Partials.
705
+ Module: ${usageInModuleEntryPoint.id === moduleWithCmsModuleUsage.id ? usageInModuleEntryPoint.id.replace(config.root, "") : `imports: ${moduleWithCmsModuleUsage.id.replace(
706
+ config.root,
707
+ ""
708
+ )}, which`} contains a <${CMS_MODULE_COMPONENT_NAME} />
709
+ `);
710
+ }
711
+ }
712
+ const root = config.root;
713
+ for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
714
+ const islandsContainingCmsModuleUsage = checkModuleTreeForIslands(
715
+ this,
716
+ moduleWithCmsModuleUsage
717
+ );
718
+ if (islandsContainingCmsModuleUsage.length > 0) {
719
+ throw new Error(`
720
+ <${CMS_MODULE_COMPONENT_NAME} /> cannot be used within islands.
721
+ ${formatIslandImporter(
722
+ moduleWithCmsModuleUsage.id,
723
+ root
724
+ )} uses <${CMS_MODULE_COMPONENT_NAME} /> and is used by islands:
725
+ ${islandsContainingCmsModuleUsage.map(
726
+ (islandModuleInfo) => formatIslandImporter(islandModuleInfo.id, root)
727
+ ).join(", ")}
728
+ `);
729
+ }
730
+ }
731
+ for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
732
+ const entryPoints = moduleToEntryPoints[moduleWithCmsModuleUsage.id];
733
+ for (const entryPoint of entryPoints) {
734
+ const relativeEntryPoint = entryPoint.id.replace(root, "");
735
+ if (!Object.hasOwn(cmsModules, relativeEntryPoint)) {
736
+ cmsModules[relativeEntryPoint] = {};
737
+ }
738
+ for (const [cmsModuleName, cmsModuleValue] of Object.entries(
739
+ moduleWithCmsModuleUsage.meta.findCmsModules
740
+ )) {
741
+ if (Object.hasOwn(cmsModules[relativeEntryPoint], cmsModuleName)) {
742
+ this.error(`Error: duplicate module name: ${cmsModuleName}`);
743
+ }
744
+ cmsModules[relativeEntryPoint][cmsModuleName] = cmsModuleValue;
745
+ }
746
+ }
747
+ }
748
+ }
749
+ };
750
+ }
751
+ function findEntryPoints(ctx, moduleInfo) {
752
+ if (moduleInfo.isEntry) {
753
+ return [moduleInfo];
754
+ }
755
+ const result = [];
756
+ for (const importer of moduleInfo.importers) {
757
+ const importerModuleInfo = ctx.getModuleInfo(importer);
758
+ const entryPoints = findEntryPoints(ctx, importerModuleInfo);
759
+ result.push(...entryPoints);
760
+ }
761
+ return result;
762
+ }
763
+ function checkModuleTreeForIslands(ctx, module) {
764
+ if (module.id.endsWith("?client-entry")) {
765
+ return [module];
766
+ }
767
+ const importerResults = [];
768
+ for (const importer of module.importers) {
769
+ const importerInfo = ctx.getModuleInfo(importer);
770
+ const importerResult = checkModuleTreeForIslands(ctx, importerInfo);
771
+ importerResults.push(importerResult);
772
+ }
773
+ return importerResults.flat();
774
+ }
775
+ function formatIslandImporter(id, root) {
776
+ return id.replace(root, "").replace("?client-entry", "");
777
+ }
600
778
  var promiseForNewWritableStream = () => {
601
779
  const chunks = [];
602
780
  const writableStream = new stream.Writable();
@@ -1016,7 +1194,7 @@ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, perServerReque
1016
1194
  };
1017
1195
 
1018
1196
  // src/routes/partial.ts
1019
- import { buildStaticEnvConfig } from "@hubspot/cms-components";
1197
+ import { buildStaticEnvConfig as buildStaticEnvConfig3 } from "@hubspot/cms-components";
1020
1198
 
1021
1199
  // src/lib/trackUsage.ts
1022
1200
  import localDevHttpImport from "@hubspot/local-dev-lib/http";
@@ -1055,7 +1233,7 @@ function trackUsage(action) {
1055
1233
  eventName: EVENT_NAME,
1056
1234
  action,
1057
1235
  nodeVersion: getNodeVersionData(),
1058
- version: "0.16.7",
1236
+ version: "0.16.11",
1059
1237
  os: getPlatform()
1060
1238
  };
1061
1239
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1093,162 +1271,113 @@ function sendTrackingRequest(action) {
1093
1271
  });
1094
1272
  }
1095
1273
 
1096
- // src/routes/partial.ts
1097
- var partialRouteHandler = async (request2, response) => {
1098
- sendTrackingRequest("view-partial-route");
1099
- const {
1100
- authedPortalId,
1101
- authedEnv,
1102
- authedHublet,
1103
- webRoot: webRoot2,
1104
- viteServer,
1105
- jsRenderingGates,
1106
- projectName,
1107
- projectComponentPath
1108
- } = request2.app.locals;
1109
- const partialName = request2.params.partial;
1110
- const baseTemplatePath = packagePath(
1111
- import.meta.url,
1112
- "html/baseTemplate.html"
1113
- );
1114
- const partialPath = normalizePath2(
1115
- path3.resolve(webRoot2, "components/partials/", partialName)
1116
- );
1117
- const entrypointPath = normalizePath2(
1118
- [
1119
- "@projects",
1120
- projectName,
1121
- projectComponentPath,
1122
- "components/modules/",
1123
- partialName
1124
- ].join("/")
1125
- );
1126
- const basePath = getEntryPointBasePath(partialPath);
1127
- const environmentConfig = buildStaticEnvConfig(
1128
- authedPortalId,
1129
- authedHublet,
1130
- authedEnv,
1131
- false,
1132
- jsRenderingGates
1133
- );
1134
- try {
1135
- const {
1136
- html: renderedHtml,
1137
- cssNeeded,
1138
- renderContext,
1139
- inlineAssets
1140
- } = await renderPartial_default(
1141
- viteServer,
1142
- partialPath,
1143
- {},
1144
- fullOriginalUrlFromRequest(request2),
1145
- basePath,
1146
- environmentConfig,
1147
- {
1148
- identifierPrefix: getEntryPointHash(entrypointPath)
1274
+ // src/lib/renderModulePreview.ts
1275
+ import { buildStaticEnvConfig as buildStaticEnvConfig2 } from "@hubspot/cms-components";
1276
+ import path4 from "path";
1277
+ import { normalizePath as normalizePath3 } from "vite";
1278
+
1279
+ // src/lib/proxyHelpers.ts
1280
+ import fs2 from "fs";
1281
+ import { resolve as resolve2 } from "path";
1282
+ import { unescape } from "html-escaper";
1283
+ var localJsRenderStartString = '<!-- proxy local render of "';
1284
+ var localJsRenderEndString = "end proxy local render -->";
1285
+ function isRecord(value) {
1286
+ return typeof value === "object" && value !== null;
1287
+ }
1288
+ var findLocalRenderPlaceholders = (body) => {
1289
+ let offsetSoFar = 0;
1290
+ const result = [];
1291
+ while (offsetSoFar < body.length && offsetSoFar !== -1) {
1292
+ const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
1293
+ offsetSoFar = startOffset;
1294
+ if (startOffset >= 0) {
1295
+ const nextNewlineOffset = body.indexOf(
1296
+ "\n",
1297
+ startOffset + localJsRenderStartString.length
1298
+ );
1299
+ const pathEndOffset = body.indexOf(
1300
+ '"',
1301
+ startOffset + localJsRenderStartString.length
1302
+ );
1303
+ const nearestNewlineOrQuoteAfterBlockOpen = Math.min(
1304
+ nextNewlineOffset,
1305
+ pathEndOffset
1306
+ );
1307
+ offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1308
+ if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1309
+ const path11 = body.substring(
1310
+ startOffset + localJsRenderStartString.length,
1311
+ pathEndOffset
1312
+ );
1313
+ offsetSoFar = pathEndOffset + 1;
1314
+ if (startOffset >= 0 && path11) {
1315
+ const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1316
+ const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1317
+ offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
1318
+ if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
1319
+ const jsonString = body.substring(pathEndOffset + 1, endOffset).trim();
1320
+ try {
1321
+ let json;
1322
+ try {
1323
+ json = JSON.parse(unescape(jsonString));
1324
+ } catch (e) {
1325
+ json = JSON.parse(jsonString);
1326
+ }
1327
+ if (!isRecord(json.request)) {
1328
+ console.error(
1329
+ `Invalid JSON inside <!-- proxy local render .. --> string (missing request key)`
1330
+ );
1331
+ } else if (!isRecord(json.props)) {
1332
+ console.error(
1333
+ `Invalid JSON inside <!-- proxy local render .. --> string (missing props key)`
1334
+ );
1335
+ } else {
1336
+ result.push({
1337
+ startOffset,
1338
+ endOffset: endOffset + localJsRenderEndString.length,
1339
+ path: path11,
1340
+ json
1341
+ });
1342
+ }
1343
+ offsetSoFar = endOffset + localJsRenderEndString.length;
1344
+ } catch (e) {
1345
+ console.error(
1346
+ `Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`
1347
+ );
1348
+ offsetSoFar = endOffset;
1349
+ }
1350
+ }
1351
+ }
1149
1352
  }
1150
- );
1151
- const htmlShell = await createHtmlShellDependingOnRenderContext(
1152
- baseTemplatePath,
1153
- request2.originalUrl,
1154
- `Partial: ${partialPath}`,
1155
- renderContext,
1156
- viteServer,
1157
- jsRenderingGates
1158
- );
1159
- const html = htmlShell.replace(
1160
- "<!--headend-->",
1161
- [
1162
- cssNeeded,
1163
- ...inlineAssets.map((inlineAsset) => inlineAsset.html)
1164
- ].join("\n")
1165
- ).replace(`<!--ssr-outlet-->`, renderedHtml);
1166
- response.status(200).set({ "Content-Type": "text/html" }).end(html);
1353
+ }
1354
+ }
1355
+ return result;
1356
+ };
1357
+ var getHSProjectConfig = (hsProjectConfigPath) => {
1358
+ try {
1359
+ return JSON.parse(fs2.readFileSync(hsProjectConfigPath, "utf8"));
1167
1360
  } catch (e) {
1168
- console.error(e);
1169
- viteServer.ssrFixStacktrace(e);
1170
- response.status(500).end(`Error rendering partial (${partialName})
1171
-
1172
- ${e.stack}`);
1361
+ console.warn(
1362
+ `Missing hsproject.json file (${resolve2(hsProjectConfigPath)}): `,
1363
+ e.message
1364
+ );
1365
+ return null;
1173
1366
  }
1174
1367
  };
1175
- var partial_default = partialRouteHandler;
1176
-
1177
- // src/components/PartialsList.tsx
1178
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1179
- function EmptyPartialsList({ webRoot: webRoot2 }) {
1180
- return /* @__PURE__ */ jsxs("p", { children: [
1181
- "No partials in ",
1182
- /* @__PURE__ */ jsxs("code", { children: [
1183
- webRoot2,
1184
- "components/partials"
1185
- ] })
1186
- ] });
1187
- }
1188
- function PartialLinkInLI({ partialName }) {
1189
- return /* @__PURE__ */ jsx2("li", { children: /* @__PURE__ */ jsx2("a", { href: `/partial/${partialName}`, children: partialName }) });
1190
- }
1191
- function PartialsList({ webRoot: webRoot2, partialNames }) {
1192
- if (partialNames.length === 0) {
1193
- return /* @__PURE__ */ jsx2(EmptyPartialsList, { webRoot: webRoot2 });
1368
+ var getProjectNameFromHSConfig = (hsProjectConfigPath) => {
1369
+ const hsProjectConfig = getHSProjectConfig(hsProjectConfigPath);
1370
+ if (hsProjectConfig) {
1371
+ return hsProjectConfig.name;
1194
1372
  }
1195
- return /* @__PURE__ */ jsx2("ul", { children: partialNames.map((partialName) => /* @__PURE__ */ jsx2(PartialLinkInLI, { partialName }, partialName)) });
1196
- }
1197
-
1198
- // src/routes/linksToAllPartialsRouteHandler.tsx
1199
- import { jsx as jsx3 } from "react/jsx-runtime";
1200
- var linksToAllPartialRouteHandler = async (request2, response) => {
1201
- const { webRoot: webRoot2 } = request2.app.locals;
1202
- const { partialNames } = findAllPartialsInRoot(webRoot2);
1203
- const { html: responseHtml } = await renderOnServer(
1204
- /* @__PURE__ */ jsx3(PartialsList, { webRoot: webRoot2, partialNames })
1205
- );
1206
- response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
1373
+ throw new Error("hsproject.json file not found");
1207
1374
  };
1208
- var linksToAllPartialsRouteHandler_default = linksToAllPartialRouteHandler;
1209
1375
 
1210
- // src/components/ModulesList.tsx
1211
- import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
1212
- function EmptyModulesList({ webRoot: webRoot2 }) {
1213
- return /* @__PURE__ */ jsxs2("p", { children: [
1214
- "No modules in ",
1215
- /* @__PURE__ */ jsxs2("code", { children: [
1216
- webRoot2,
1217
- "components/modules"
1218
- ] })
1219
- ] });
1220
- }
1221
- function ModuleLinkInLI({ moduleName }) {
1222
- return /* @__PURE__ */ jsxs2("li", { children: [
1223
- /* @__PURE__ */ jsx4("a", { href: `/preview/module/${moduleName}`, children: moduleName }),
1224
- " / ",
1225
- /* @__PURE__ */ jsx4("a", { href: `/module/${moduleName}`, children: "Local Version" })
1226
- ] });
1227
- }
1228
- function ModulesList({ webRoot: webRoot2, moduleNames }) {
1229
- if (moduleNames.length === 0) {
1230
- return /* @__PURE__ */ jsx4(EmptyModulesList, { webRoot: webRoot2 });
1231
- }
1232
- return /* @__PURE__ */ jsx4("ul", { children: moduleNames.map((moduleName) => /* @__PURE__ */ jsx4(ModuleLinkInLI, { moduleName }, moduleName)) });
1233
- }
1234
- var ModulesList_default = ModulesList;
1235
-
1236
- // src/routes/linksToAllModulesRouteHandler.tsx
1237
- import { jsx as jsx5 } from "react/jsx-runtime";
1238
- var linksToAllModuleRouteHandler = async (request2, response) => {
1239
- const { webRoot: webRoot2 } = request2.app.locals;
1240
- const { moduleNames } = findAllModulesInRoot(webRoot2);
1241
- const { html: responseHtml } = await renderOnServer(
1242
- /* @__PURE__ */ jsx5(ModulesList_default, { webRoot: webRoot2, moduleNames })
1243
- );
1244
- response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
1245
- };
1246
- var linksToAllModulesRouteHandler_default = linksToAllModuleRouteHandler;
1247
-
1248
- // src/routes/module.ts
1249
- import { buildStaticEnvConfig as buildStaticEnvConfig2 } from "@hubspot/cms-components";
1250
- import path4 from "path";
1251
- import { normalizePath as normalizePath3 } from "vite";
1376
+ // src/proxyPage/proxyPage.ts
1377
+ import path3 from "path";
1378
+ import { normalizePath as normalizePath2 } from "vite";
1379
+ import { getAccountId, getEnv } from "@hubspot/local-dev-lib/config";
1380
+ import localDevHttpImport5 from "@hubspot/local-dev-lib/http";
1252
1381
 
1253
1382
  // src/lib/renderModule.ts
1254
1383
  import { join as joinPosix2 } from "path/posix";
@@ -1463,392 +1592,95 @@ function getFieldValuesForModule(fieldsJSON, fieldOverrides = {}) {
1463
1592
  }
1464
1593
  var renderModule_default = renderModule;
1465
1594
 
1466
- // src/routes/module.ts
1467
- var moduleRouteHandler = async (request2, response) => {
1468
- sendTrackingRequest("view-module-route");
1469
- const {
1470
- authedPortalId,
1471
- authedEnv,
1472
- authedHublet,
1473
- webRoot: webRoot2,
1474
- viteServer,
1475
- jsRenderingGates,
1476
- projectName,
1477
- projectComponentPath
1478
- } = request2.app.locals;
1479
- const moduleName = request2.params.moduleName;
1480
- const baseTemplatePath = packagePath(
1481
- import.meta.url,
1482
- "html/baseTemplate.html"
1483
- );
1484
- const modulePath = normalizePath3(
1485
- path4.resolve(webRoot2, "components/modules/", moduleName)
1486
- );
1487
- const entrypointPath = normalizePath3(
1488
- [
1489
- "@projects",
1490
- projectName,
1491
- projectComponentPath,
1492
- "components/modules/",
1493
- moduleName
1494
- ].join("/")
1495
- );
1496
- let fieldOverrides = null;
1497
- if (request2.query.fields) {
1498
- try {
1499
- if (typeof request2.query.fields === "string") {
1500
- fieldOverrides = JSON.parse(
1501
- decodeURIComponent(request2.query.fields.replace(/\+/g, "%20"))
1502
- );
1503
- }
1504
- } catch (e) {
1505
- console.error(
1506
- `Error parsing field param for module ${moduleName}: ${request2.query.fields}`
1507
- );
1595
+ // src/proxyPage/utils.ts
1596
+ import { createEmptyServerRenderContext } from "@hubspot/cms-components";
1597
+
1598
+ // src/proxyPage/constants.ts
1599
+ var VALID_PROXY_DOMAIN_SUFFIXES = ["localhost", "hslocal.net"];
1600
+
1601
+ // src/proxyPage/utils.ts
1602
+ var getSubDomainFromValidLocalDomain = (hostname) => {
1603
+ for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
1604
+ if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
1605
+ return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
1508
1606
  }
1509
1607
  }
1510
- const basePath = getEntryPointBasePath(modulePath);
1511
- const environmentConfig = buildStaticEnvConfig2(
1512
- authedPortalId,
1513
- authedHublet,
1514
- authedEnv,
1515
- false,
1516
- jsRenderingGates
1517
- );
1518
- try {
1519
- const {
1520
- html: renderedHtml,
1521
- cssNeeded,
1522
- renderContext,
1523
- inlineAssets
1524
- } = await renderModule_default(
1525
- viteServer,
1526
- modulePath,
1527
- {
1528
- fieldValues: fieldOverrides,
1529
- hublParameters: {},
1530
- moduleName: `local-${moduleName}`
1531
- },
1532
- fullOriginalUrlFromRequest(request2),
1533
- basePath,
1534
- environmentConfig,
1535
- {
1536
- identifierPrefix: getEntryPointHash(entrypointPath)
1608
+ return void 0;
1609
+ };
1610
+ var randomStringWithLotsOf = (char, maxLength) => {
1611
+ return new Array(Math.floor(Math.random() * maxLength)).fill(char).join("");
1612
+ };
1613
+ var fakeRenderJsComponent = (indexForThisRender) => {
1614
+ return new Promise((resolve3, reject) => {
1615
+ const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1e3;
1616
+ setTimeout(() => {
1617
+ try {
1618
+ const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf(
1619
+ "?",
1620
+ 100
1621
+ )}</div>
1622
+ `;
1623
+ resolve3({
1624
+ html: fakeJsRenderedOutput,
1625
+ cssNeeded: "",
1626
+ renderContext: createEmptyServerRenderContext(),
1627
+ inlineAssets: []
1628
+ });
1629
+ } catch (e) {
1630
+ console.log("Error with JS render...");
1631
+ console.error(e);
1632
+ reject();
1537
1633
  }
1538
- );
1539
- const htmlShell = await createHtmlShellDependingOnRenderContext(
1540
- baseTemplatePath,
1541
- request2.originalUrl,
1542
- `Module: ${modulePath}`,
1543
- renderContext,
1544
- viteServer,
1545
- jsRenderingGates
1546
- );
1547
- const html = htmlShell.replace(
1548
- "<!--headend-->",
1549
- [
1550
- cssNeeded,
1551
- ...inlineAssets.map((inlineAsset) => inlineAsset.html)
1552
- ].join("\n")
1553
- ).replace(`<!--ssr-outlet-->`, renderedHtml);
1554
- response.status(200).set({ "Content-Type": "text/html" }).end(html);
1555
- } catch (e) {
1556
- console.error(e);
1557
- viteServer.ssrFixStacktrace(e);
1558
- response.status(500).end(`Error rendering module (${moduleName})
1634
+ }, randomTimeout);
1635
+ });
1636
+ };
1637
+ var consoleWarn = (message) => {
1638
+ console.warn("\x1B[33m%s\x1B[0m", "WARNING:", message);
1639
+ };
1559
1640
 
1560
- ${e.stack}`);
1561
- }
1641
+ // src/proxyPage/renderLocalError.ts
1642
+ import AnsiToHtmlConverter from "ansi-to-html";
1643
+ var customColors = [
1644
+ // Normal colors
1645
+ "#000",
1646
+ // black
1647
+ "#ec392c",
1648
+ // red
1649
+ "#b3e439",
1650
+ // green
1651
+ "#fea525",
1652
+ // yellow
1653
+ "#76dff3",
1654
+ // blue
1655
+ "#fd4285",
1656
+ // magenta
1657
+ "#cfa3ff",
1658
+ // cyan
1659
+ "#f4f4f4",
1660
+ // White
1661
+ // Bright colors (mostly identical to ^)
1662
+ "#646464",
1663
+ "#ec392c",
1664
+ "#fea525",
1665
+ "#76dff3",
1666
+ "#fd4285",
1667
+ "#cfa3ff",
1668
+ "#f4f4f4"
1669
+ ];
1670
+ var Converter = new AnsiToHtmlConverter({ colors: customColors });
1671
+ var darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
1672
+ var renderLocalError_default = (path11, error) => {
1673
+ const stackWithColorClasses = Converter.toHtml(error.stack);
1674
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path11}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1562
1675
  };
1563
- var module_default = moduleRouteHandler;
1564
1676
 
1565
- // src/proxyPage/fetchContentMetadata.ts
1566
- import http from "http";
1567
- import https from "https";
1568
- import { getAccountId } from "@hubspot/local-dev-lib/config";
1569
- async function requestPage(url3, redirects = 0, originalUrl) {
1570
- if (redirects > 5) {
1677
+ // src/proxyPage/fetchPreviewInfo.ts
1678
+ import localDevHttpImport4 from "@hubspot/local-dev-lib/http";
1679
+ var { default: hsCliHttp4 } = localDevHttpImport4;
1680
+ var fetchPreviewInfo_default = async (accountId, portalId, contentId) => {
1681
+ if (!contentId) {
1571
1682
  throw new Error(
1572
- `Hit too many redirects to HEAD requests for ${originalUrl}`
1573
- );
1574
- }
1575
- return new Promise((resolve3, reject) => {
1576
- const protocolAPI = url3.startsWith("https://") ? https : http;
1577
- protocolAPI.request(
1578
- url3,
1579
- {
1580
- method: "HEAD",
1581
- headers: {
1582
- // Keep this user agent, so we don't get 403s from the request
1583
- ["User-Agent"]: "cms-dev-server"
1584
- }
1585
- },
1586
- async (res) => {
1587
- let portalIdHeader;
1588
- let contentId;
1589
- const isContentMembershipRedirect = Boolean(
1590
- res.headers["x-hs-content-membership-redirect"]
1591
- );
1592
- if (isContentMembershipRedirect) {
1593
- debug("Content Membership Redirect", res.headers);
1594
- portalIdHeader = res.headers["x-hs-portal-id"];
1595
- contentId = res.headers["x-hs-content-id"];
1596
- if (portalIdHeader && contentId) {
1597
- return resolve3({
1598
- portalIdHeader,
1599
- contentId,
1600
- res
1601
- });
1602
- }
1603
- }
1604
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
1605
- console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
1606
- return resolve3(
1607
- requestPage(
1608
- res.headers.location,
1609
- redirects + 1,
1610
- originalUrl ?? url3
1611
- )
1612
- );
1613
- }
1614
- portalIdHeader = res.headers["x-hs-hub-id"];
1615
- contentId = res.headers["x-hs-content-id"];
1616
- return resolve3({
1617
- res,
1618
- portalIdHeader,
1619
- contentId
1620
- });
1621
- }
1622
- ).on("error", (err) => {
1623
- console.error(err);
1624
- reject(err);
1625
- }).end();
1626
- });
1627
- }
1628
- async function fetchContentMetadata(url3, portalId) {
1629
- const { portalIdHeader, contentId, res } = await requestPage(url3);
1630
- if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
1631
- throw new Error(
1632
- `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
1633
- );
1634
- } else {
1635
- const portalIdFromResponse = parseInt(portalIdHeader, 10);
1636
- const pageAccount = await getAccountId(portalIdFromResponse);
1637
- if (!pageAccount) {
1638
- throw new Error(
1639
- `No CLI auth for portal ${portalIdFromResponse} found, please run \`hs auth\``
1640
- );
1641
- }
1642
- if (res.statusCode !== 200 && !(portalIdFromResponse && pageAccount && contentId)) {
1643
- throw new Error(
1644
- `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url3}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
1645
- );
1646
- } else if (!portalId || !contentId) {
1647
- throw new Error(
1648
- `Missing hub ID or content ID headers on HEAD request to ${url3}`
1649
- );
1650
- } else if (isNaN(portalId)) {
1651
- throw new Error(
1652
- `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
1653
- );
1654
- }
1655
- const hublet = "na1";
1656
- return { portalId, contentId, hublet };
1657
- }
1658
- }
1659
-
1660
- // src/proxyPage/proxyPage.ts
1661
- import path5 from "path";
1662
- import { normalizePath as normalizePath4 } from "vite";
1663
- import { getAccountId as getAccountId2, getEnv } from "@hubspot/local-dev-lib/config";
1664
- import localDevHttpImport5 from "@hubspot/local-dev-lib/http";
1665
-
1666
- // src/lib/proxyHelpers.ts
1667
- import fs2 from "fs";
1668
- import { resolve as resolve2 } from "path";
1669
- import { unescape } from "html-escaper";
1670
- var localJsRenderStartString = '<!-- proxy local render of "';
1671
- var localJsRenderEndString = "end proxy local render -->";
1672
- function isRecord(value) {
1673
- return typeof value === "object" && value !== null;
1674
- }
1675
- var findLocalRenderPlaceholders = (body) => {
1676
- let offsetSoFar = 0;
1677
- const result = [];
1678
- while (offsetSoFar < body.length && offsetSoFar !== -1) {
1679
- const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
1680
- offsetSoFar = startOffset;
1681
- if (startOffset >= 0) {
1682
- const nextNewlineOffset = body.indexOf(
1683
- "\n",
1684
- startOffset + localJsRenderStartString.length
1685
- );
1686
- const pathEndOffset = body.indexOf(
1687
- '"',
1688
- startOffset + localJsRenderStartString.length
1689
- );
1690
- const nearestNewlineOrQuoteAfterBlockOpen = Math.min(
1691
- nextNewlineOffset,
1692
- pathEndOffset
1693
- );
1694
- offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1695
- if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1696
- const path10 = body.substring(
1697
- startOffset + localJsRenderStartString.length,
1698
- pathEndOffset
1699
- );
1700
- offsetSoFar = pathEndOffset + 1;
1701
- if (startOffset >= 0 && path10) {
1702
- const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1703
- const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1704
- offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
1705
- if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
1706
- const jsonString = body.substring(pathEndOffset + 1, endOffset).trim();
1707
- try {
1708
- let json;
1709
- try {
1710
- json = JSON.parse(unescape(jsonString));
1711
- } catch (e) {
1712
- json = JSON.parse(jsonString);
1713
- }
1714
- if (!isRecord(json.request)) {
1715
- console.error(
1716
- `Invalid JSON inside <!-- proxy local render .. --> string (missing request key)`
1717
- );
1718
- } else if (!isRecord(json.props)) {
1719
- console.error(
1720
- `Invalid JSON inside <!-- proxy local render .. --> string (missing props key)`
1721
- );
1722
- } else {
1723
- result.push({
1724
- startOffset,
1725
- endOffset: endOffset + localJsRenderEndString.length,
1726
- path: path10,
1727
- json
1728
- });
1729
- }
1730
- offsetSoFar = endOffset + localJsRenderEndString.length;
1731
- } catch (e) {
1732
- console.error(
1733
- `Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`
1734
- );
1735
- offsetSoFar = endOffset;
1736
- }
1737
- }
1738
- }
1739
- }
1740
- }
1741
- }
1742
- return result;
1743
- };
1744
- var getHSProjectConfig = (hsProjectConfigPath) => {
1745
- try {
1746
- return JSON.parse(fs2.readFileSync(hsProjectConfigPath, "utf8"));
1747
- } catch (e) {
1748
- console.warn(
1749
- `Missing hsproject.json file (${resolve2(hsProjectConfigPath)}): `,
1750
- e.message
1751
- );
1752
- return null;
1753
- }
1754
- };
1755
- var getProjectNameFromHSConfig = (hsProjectConfigPath) => {
1756
- const hsProjectConfig = getHSProjectConfig(hsProjectConfigPath);
1757
- if (hsProjectConfig) {
1758
- return hsProjectConfig.name;
1759
- }
1760
- throw new Error("hsproject.json file not found");
1761
- };
1762
-
1763
- // src/proxyPage/utils.ts
1764
- import { createEmptyServerRenderContext } from "@hubspot/cms-components";
1765
-
1766
- // src/proxyPage/constants.ts
1767
- var VALID_PROXY_DOMAIN_SUFFIXES = ["localhost", "hslocal.net"];
1768
-
1769
- // src/proxyPage/utils.ts
1770
- var getSubDomainFromValidLocalDomain = (hostname) => {
1771
- for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
1772
- if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
1773
- return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
1774
- }
1775
- }
1776
- return void 0;
1777
- };
1778
- var randomStringWithLotsOf = (char, maxLength) => {
1779
- return new Array(Math.floor(Math.random() * maxLength)).fill(char).join("");
1780
- };
1781
- var fakeRenderJsComponent = (indexForThisRender) => {
1782
- return new Promise((resolve3, reject) => {
1783
- const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1e3;
1784
- setTimeout(() => {
1785
- try {
1786
- const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf(
1787
- "?",
1788
- 100
1789
- )}</div>
1790
- `;
1791
- resolve3({
1792
- html: fakeJsRenderedOutput,
1793
- cssNeeded: "",
1794
- renderContext: createEmptyServerRenderContext(),
1795
- inlineAssets: []
1796
- });
1797
- } catch (e) {
1798
- console.log("Error with JS render...");
1799
- console.error(e);
1800
- reject();
1801
- }
1802
- }, randomTimeout);
1803
- });
1804
- };
1805
- var consoleWarn = (message) => {
1806
- console.warn("\x1B[33m%s\x1B[0m", "WARNING:", message);
1807
- };
1808
-
1809
- // src/proxyPage/renderLocalError.ts
1810
- import AnsiToHtmlConverter from "ansi-to-html";
1811
- var customColors = [
1812
- // Normal colors
1813
- "#000",
1814
- // black
1815
- "#ec392c",
1816
- // red
1817
- "#b3e439",
1818
- // green
1819
- "#fea525",
1820
- // yellow
1821
- "#76dff3",
1822
- // blue
1823
- "#fd4285",
1824
- // magenta
1825
- "#cfa3ff",
1826
- // cyan
1827
- "#f4f4f4",
1828
- // White
1829
- // Bright colors (mostly identical to ^)
1830
- "#646464",
1831
- "#ec392c",
1832
- "#fea525",
1833
- "#76dff3",
1834
- "#fd4285",
1835
- "#cfa3ff",
1836
- "#f4f4f4"
1837
- ];
1838
- var Converter = new AnsiToHtmlConverter({ colors: customColors });
1839
- var darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
1840
- var renderLocalError_default = (path10, error) => {
1841
- const stackWithColorClasses = Converter.toHtml(error.stack);
1842
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path10}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1843
- };
1844
-
1845
- // src/proxyPage/fetchPreviewInfo.ts
1846
- import localDevHttpImport4 from "@hubspot/local-dev-lib/http";
1847
- var { default: hsCliHttp4 } = localDevHttpImport4;
1848
- var fetchPreviewInfo_default = async (accountId, portalId, contentId) => {
1849
- if (!contentId) {
1850
- throw new Error(
1851
- `Invalid contentId when attempting to fetch preview info: ${contentId}`
1683
+ `Invalid contentId when attempting to fetch preview info: ${contentId}`
1852
1684
  );
1853
1685
  }
1854
1686
  try {
@@ -1887,7 +1719,7 @@ ${error.error.message}`);
1887
1719
 
1888
1720
  // src/proxyPage/proxyPage.ts
1889
1721
  import {
1890
- buildStaticEnvConfig as buildStaticEnvConfig3,
1722
+ buildStaticEnvConfig,
1891
1723
  isDebugUrlString as isDebugUrlString3,
1892
1724
  mergeServerRequestData_internal
1893
1725
  } from "@hubspot/cms-components";
@@ -2000,8 +1832,8 @@ var renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder,
2000
1832
  `The specified component folder "${projectComponentFolder}" does not match the webroot project component folder "${webRootProjectComponent}/${projectComponentFolder}" specified to the cms-dev-server. Components must be located within the webroot project folder. Check that the specified path is correct: ${placeholderPath}.`
2001
1833
  );
2002
1834
  }
2003
- const resolvedPath = normalizePath4(
2004
- path5.resolve(webRoot2, partialPath, componentFileName)
1835
+ const resolvedPath = normalizePath2(
1836
+ path3.resolve(webRoot2, partialPath, componentFileName)
2005
1837
  );
2006
1838
  const entryPointPath = [
2007
1839
  "@projects",
@@ -2084,7 +1916,7 @@ async function proxySpecificPage(request2, response, portalId, hublet, contentId
2084
1916
  let proxyEnv;
2085
1917
  const prettyPrint = isDebugUrlString3(urlToProxy);
2086
1918
  try {
2087
- accountId = getAccountId2(portalId);
1919
+ accountId = getAccountId(portalId);
2088
1920
  if (accountId === null) {
2089
1921
  throw new Error();
2090
1922
  }
@@ -2104,7 +1936,7 @@ async function proxySpecificPage(request2, response, portalId, hublet, contentId
2104
1936
  try {
2105
1937
  const previewInfo = await fetchPreviewInfo_default(accountId, portalId, contentId);
2106
1938
  const { previewKey } = previewInfo;
2107
- const environmentConfig = buildStaticEnvConfig3(
1939
+ const environmentConfig = buildStaticEnvConfig(
2108
1940
  portalId,
2109
1941
  hublet,
2110
1942
  proxyEnv,
@@ -2134,120 +1966,706 @@ async function proxySpecificPage(request2, response, portalId, hublet, contentId
2134
1966
  const renderPromisesByChunkIndex = new Array(
2135
1967
  numPlaceholders
2136
1968
  );
2137
- if (localRenderPlaceholders.length > 0) {
2138
- let offsetSoFar = 0;
2139
- const pageChunks = new Array(numPlaceholders + 1);
2140
- for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
2141
- const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
2142
- pageChunks[indexForThisRender] = pageHtml.slice(
2143
- offsetSoFar,
2144
- localRenderPlaceholder.startOffset
2145
- );
2146
- if (basePath === void 0) {
2147
- basePath = getEntryPointBasePathFromProxyRequest(
2148
- localRenderPlaceholder.json.request
2149
- );
1969
+ if (localRenderPlaceholders.length > 0) {
1970
+ let offsetSoFar = 0;
1971
+ const pageChunks = new Array(numPlaceholders + 1);
1972
+ for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
1973
+ const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
1974
+ pageChunks[indexForThisRender] = pageHtml.slice(
1975
+ offsetSoFar,
1976
+ localRenderPlaceholder.startOffset
1977
+ );
1978
+ if (basePath === void 0) {
1979
+ basePath = getEntryPointBasePathFromProxyRequest(
1980
+ localRenderPlaceholder.json.request
1981
+ );
1982
+ }
1983
+ const renderPromise = renderComponentForPlaceholder(
1984
+ indexForThisRender,
1985
+ localRenderPlaceholder,
1986
+ webRoot2,
1987
+ viteServer,
1988
+ fullOriginalUrl,
1989
+ basePath,
1990
+ environmentConfig,
1991
+ projectName,
1992
+ projectComponentPath
1993
+ );
1994
+ renderPromisesByChunkIndex[indexForThisRender] = renderPromise.then((promiseResult) => {
1995
+ var _a;
1996
+ let { html, cssNeeded, inlineAssets, renderContext } = promiseResult;
1997
+ console.log(
1998
+ `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`
1999
+ );
2000
+ if ((_a = renderContext.criticalDevErrors) == null ? void 0 : _a.length) {
2001
+ criticalDevErrors.push(...renderContext.criticalDevErrors);
2002
+ }
2003
+ if (renderContext.islands.length > 0) {
2004
+ islands = islands.concat(renderContext.islands);
2005
+ }
2006
+ mergedPerRequestState = mergeServerRequestData_internal(
2007
+ mergedPerRequestState,
2008
+ renderContext.perServerRequestData
2009
+ );
2010
+ let result = html;
2011
+ if (inlineAssets) {
2012
+ result = `${inlineAssets.map((inlineAsset) => inlineAsset.html).join("\n")}
2013
+ ${result}`;
2014
+ }
2015
+ if (cssNeeded) {
2016
+ result = `${cssNeeded}
2017
+ ${result}`;
2018
+ }
2019
+ return result;
2020
+ }).catch((e) => {
2021
+ numJsRenderFailures += 1;
2022
+ console.log(
2023
+ "Attempted to render",
2024
+ localRenderPlaceholder.path,
2025
+ "with props",
2026
+ localRenderPlaceholder.json
2027
+ );
2028
+ console.error(e);
2029
+ return renderLocalError_default(localRenderPlaceholder.path, e);
2030
+ });
2031
+ offsetSoFar = localRenderPlaceholder.endOffset;
2032
+ }
2033
+ pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
2034
+ response.writeHead(200);
2035
+ for (let i = 0; i < localRenderPlaceholders.length; i++) {
2036
+ const chunk = pageChunks[i];
2037
+ response.write(chunk);
2038
+ const foobar = await renderPromisesByChunkIndex[i];
2039
+ response.write(foobar);
2040
+ }
2041
+ response.write(
2042
+ getServerGlobalsToInject(
2043
+ environmentConfig,
2044
+ fullOriginalUrl,
2045
+ basePath,
2046
+ void 0,
2047
+ criticalDevErrors
2048
+ )
2049
+ );
2050
+ if (criticalDevErrors.length) {
2051
+ response.write(
2052
+ scriptTagToLogServerMessages(
2053
+ criticalDevErrorsToServerMessages_default(criticalDevErrors),
2054
+ "@hubspot/cms-dev-server messages"
2055
+ )
2056
+ );
2057
+ }
2058
+ if (islands.length > 0) {
2059
+ const sortedIslandRoots = sortIslandRootsByPriority(islands);
2060
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
2061
+ sortedIslandRoots,
2062
+ mergedPerRequestState,
2063
+ viteServer,
2064
+ jsRenderingGates,
2065
+ prettyPrint
2066
+ );
2067
+ response.write(islandRuntimeAndGlobalScriptHtml);
2068
+ }
2069
+ response.write(pageChunks[pageChunks.length - 1]);
2070
+ response.end();
2071
+ } else {
2072
+ response.writeHead(200);
2073
+ response.write(pageHtml);
2074
+ response.end();
2075
+ }
2076
+ } catch (error) {
2077
+ response.status(500).end(
2078
+ `Failed proxy render of page id = ${contentId} hub id = ${portalId}
2079
+
2080
+ ${error.stack}`
2081
+ );
2082
+ return;
2083
+ }
2084
+ }
2085
+
2086
+ // src/lib/renderModulePreview.ts
2087
+ import localDevHttpImport6 from "@hubspot/local-dev-lib/http";
2088
+ import jsdom from "jsdom";
2089
+ var { JSDOM } = jsdom;
2090
+ var { default: hsCliHttp6 } = localDevHttpImport6;
2091
+ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue) {
2092
+ const moduleInfoQueryParams = new URLSearchParams({
2093
+ portalId: `${authedPortalId}`
2094
+ });
2095
+ const moduleInfo = await hsCliHttp6.get(authedPortalId, {
2096
+ url: `/api/designmanager/v1/modules/by-path/${encodeURIComponent(
2097
+ modulePath
2098
+ )}?${moduleInfoQueryParams}`,
2099
+ headers: {
2100
+ ["Accept"]: "application/json",
2101
+ referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2102
+ cookie: cookieValue,
2103
+ "User-Agent": "HubSpot CMS Dev Server"
2104
+ }
2105
+ });
2106
+ const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2107
+ process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2108
+ const queryParams = new URLSearchParams({
2109
+ portalId: `${authedPortalId}`,
2110
+ hsLocalProxy: `${true}`,
2111
+ localProxySchemaVersion: "2",
2112
+ hsLoginVerifyDisabled: `${true}`,
2113
+ module_id: moduleInfo.moduleId
2114
+ });
2115
+ const modulePreviewHtml = await hsCliHttp6.get(authedPortalId, {
2116
+ url: `/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`,
2117
+ headers: {
2118
+ ["content-type"]: "application/x-www-form-urlencoded",
2119
+ ["Accept"]: "text/html",
2120
+ referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2121
+ cookie: cookieValue,
2122
+ "User-Agent": "HubSpot CMS Dev Server"
2123
+ }
2124
+ });
2125
+ if (currentHubApiDomainOverride) {
2126
+ process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2127
+ } else {
2128
+ delete process.env.HUBAPI_DOMAIN_OVERRIDE;
2129
+ }
2130
+ const dom = new JSDOM(modulePreviewHtml);
2131
+ const modulePreviewContent = dom.window.document.querySelector(
2132
+ 'div[data-hs-cos-type="module"]'
2133
+ ).outerHTML;
2134
+ const cssNeeded = Array.from(dom.window.document.querySelectorAll("style")).map((element) => element.outerHTML).join("");
2135
+ return { html: modulePreviewContent, cssNeeded };
2136
+ }
2137
+ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot2, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue) {
2138
+ const modulePath = normalizePath3(
2139
+ path4.resolve(webRoot2, "components/modules/", moduleName)
2140
+ );
2141
+ const basePath = `preview/${getEntryPointBasePath(modulePath)}`;
2142
+ const environmentConfig = buildStaticEnvConfig2(
2143
+ authedPortalId,
2144
+ authedHublet,
2145
+ authedEnv,
2146
+ false,
2147
+ jsRenderingGates
2148
+ );
2149
+ let componentModule;
2150
+ let foundPath;
2151
+ if (!hasComponentExtension(modulePath)) {
2152
+ [componentModule, foundPath] = await lookForModuleInFolder2(
2153
+ modulePath,
2154
+ viteServer
2155
+ );
2156
+ }
2157
+ if (!componentModule) {
2158
+ componentModule = await viteServer.ssrLoadModule(modulePath);
2159
+ foundPath = componentModule ? modulePath : void 0;
2160
+ }
2161
+ if (!componentModule) {
2162
+ throw new Error(`Couldn't find module: ${modulePath}`);
2163
+ }
2164
+ const Component = componentModule.Component;
2165
+ const fields = componentModule.fields;
2166
+ const meta = componentModule.meta;
2167
+ const hublDataTemplate = componentModule.hublDataTemplate;
2168
+ if (!Component) {
2169
+ throw new Error(
2170
+ `Module does not have a named Component export: ${foundPath}`
2171
+ );
2172
+ } else if (!fields) {
2173
+ throw new Error(`Module does not have a named fields export: ${foundPath}`);
2174
+ } else if (!meta) {
2175
+ throw new Error(`Module does not have a named meta export: ${foundPath}`);
2176
+ }
2177
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
2178
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
2179
+ const localFieldsJson = renderFieldsToJson(fields, modulePath);
2180
+ const localModule = {
2181
+ isJsModule: true,
2182
+ schemaVersion: 2,
2183
+ fields: localFieldsJson,
2184
+ id: 1,
2185
+ path: `@projects/${projectName}/${projectComponentPath}/components/modules/${moduleName}`,
2186
+ hublDataTemplate
2187
+ };
2188
+ const queryParams = new URLSearchParams({
2189
+ portalId: `${authedPortalId}`,
2190
+ hsLocalProxy: `${true}`,
2191
+ localProxySchemaVersion: "2",
2192
+ hsLoginVerifyDisabled: `${true}`
2193
+ });
2194
+ const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2195
+ process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2196
+ const templatePreview = await hsCliHttp6.post(authedPortalId, {
2197
+ url: `/api/cos-rendering/v1/public/_hcms/preview/template/multiform?${queryParams}`,
2198
+ headers: {
2199
+ ["content-type"]: "application/x-www-form-urlencoded",
2200
+ ["Accept"]: "text/html",
2201
+ referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2202
+ cookie: cookieValue,
2203
+ "User-Agent": "HubSpot CMS Dev Server"
2204
+ },
2205
+ data: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2206
+ });
2207
+ if (currentHubApiDomainOverride) {
2208
+ process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2209
+ } else {
2210
+ delete process.env.HUBAPI_DOMAIN_OVERRIDE;
2211
+ }
2212
+ const localRenderPlaceholders = findLocalRenderPlaceholders(templatePreview);
2213
+ if (localRenderPlaceholders.length !== 1) {
2214
+ throw new Error(
2215
+ `Error previewing module (${moduleName}), exception in module preview HTML
2216
+
2217
+ `
2218
+ );
2219
+ }
2220
+ return await renderComponentForPlaceholder(
2221
+ 0,
2222
+ localRenderPlaceholders[0],
2223
+ webRoot2,
2224
+ viteServer,
2225
+ fullOriginalUrl,
2226
+ basePath,
2227
+ environmentConfig,
2228
+ projectName,
2229
+ projectComponentPath
2230
+ );
2231
+ }
2232
+
2233
+ // src/routes/partial.ts
2234
+ import { join as joinPosix3 } from "path/posix";
2235
+ var partialRouteHandler = async (request2, response) => {
2236
+ sendTrackingRequest("view-partial-route");
2237
+ const {
2238
+ authedPortalId,
2239
+ authedEnv,
2240
+ authedHublet,
2241
+ webRoot: webRoot2,
2242
+ viteServer,
2243
+ jsRenderingGates,
2244
+ projectName,
2245
+ projectComponentPath
2246
+ } = request2.app.locals;
2247
+ const partialName = request2.params.partial;
2248
+ const baseTemplatePath = packagePath(
2249
+ import.meta.url,
2250
+ "html/baseTemplate.html"
2251
+ );
2252
+ const partialPath = normalizePath4(
2253
+ path5.resolve(webRoot2, "components/partials/", partialName)
2254
+ );
2255
+ const entrypointPath = normalizePath4(
2256
+ [
2257
+ "@projects",
2258
+ projectName,
2259
+ projectComponentPath,
2260
+ "components/modules/",
2261
+ partialName
2262
+ ].join("/")
2263
+ );
2264
+ const basePath = getEntryPointBasePath(partialPath);
2265
+ const environmentConfig = buildStaticEnvConfig3(
2266
+ authedPortalId,
2267
+ authedHublet,
2268
+ authedEnv,
2269
+ false,
2270
+ jsRenderingGates
2271
+ );
2272
+ try {
2273
+ const {
2274
+ html: renderedHtml,
2275
+ cssNeeded,
2276
+ renderContext,
2277
+ inlineAssets
2278
+ } = await renderPartial_default(
2279
+ viteServer,
2280
+ partialPath,
2281
+ {},
2282
+ fullOriginalUrlFromRequest(request2),
2283
+ basePath,
2284
+ environmentConfig,
2285
+ {
2286
+ identifierPrefix: getEntryPointHash(entrypointPath)
2287
+ }
2288
+ );
2289
+ let resolvedCss = cssNeeded;
2290
+ let resolvedInlineAssets = inlineAssets;
2291
+ let partialHtml = renderedHtml;
2292
+ if (jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules")) {
2293
+ const moduleNode = await viteServer.moduleGraph.getModuleByUrl(
2294
+ hasComponentExtension(partialPath) ? partialPath : joinPosix3(partialPath, "index")
2295
+ );
2296
+ if (!moduleNode) {
2297
+ throw new Error(`Error: could not find partial: ${partialPath}`);
2298
+ }
2299
+ const moduleInfo = viteServer.pluginContainer.getModuleInfo(
2300
+ moduleNode.id
2301
+ );
2302
+ const cmsModules = moduleInfo.meta.findCmsModules ?? {};
2303
+ const localProjectModules = Object.values(cmsModules).filter(
2304
+ (moduleDescriptor) => moduleDescriptor.path.startsWith(
2305
+ `@projects/${projectName}/${projectComponentPath}/components/modules/`
2306
+ )
2307
+ );
2308
+ const remoteModules = Object.values(cmsModules).filter(
2309
+ (moduleDescriptor) => !moduleDescriptor.path.startsWith(
2310
+ `@projects/${projectName}/${projectComponentPath}/components/modules/`
2311
+ )
2312
+ );
2313
+ const remoteModulePreviewPromises = [];
2314
+ const localProjectModulePreviewPromises = [];
2315
+ for (const remoteModule of remoteModules) {
2316
+ const modulePlaceholder = createModulePlaceholder(remoteModule.name);
2317
+ if (!renderedHtml.includes(modulePlaceholder))
2318
+ continue;
2319
+ remoteModulePreviewPromises.push(
2320
+ renderRemoteModulePreview(
2321
+ remoteModule.path,
2322
+ authedPortalId,
2323
+ authedEnv,
2324
+ request2.get("COOKIE")
2325
+ ).then((result) => ({
2326
+ remoteModule,
2327
+ result
2328
+ }))
2329
+ );
2330
+ }
2331
+ for (const localProjectModule of localProjectModules) {
2332
+ const modulePlaceholder = createModulePlaceholder(
2333
+ localProjectModule.name
2334
+ );
2335
+ if (!renderedHtml.includes(modulePlaceholder))
2336
+ continue;
2337
+ localProjectModulePreviewPromises.push(
2338
+ renderLocalProjectModulePreview(
2339
+ path5.basename(localProjectModule.path),
2340
+ authedPortalId,
2341
+ authedEnv,
2342
+ authedHublet,
2343
+ webRoot2,
2344
+ viteServer,
2345
+ jsRenderingGates,
2346
+ projectName,
2347
+ projectComponentPath,
2348
+ fullOriginalUrlFromRequest(request2),
2349
+ request2.get("COOKIE")
2350
+ ).then((result) => ({
2351
+ localProjectModule,
2352
+ result
2353
+ }))
2354
+ );
2355
+ }
2356
+ const [remoteModuleResults, localProjectModuleResults] = await Promise.all([
2357
+ Promise.all(remoteModulePreviewPromises),
2358
+ Promise.all(localProjectModulePreviewPromises)
2359
+ ]);
2360
+ for (const { remoteModule, result } of remoteModuleResults) {
2361
+ const modulePlaceholder = createModulePlaceholder(remoteModule.name);
2362
+ partialHtml = partialHtml.replace(modulePlaceholder, result.html);
2363
+ resolvedCss = resolvedCss.concat(result.cssNeeded);
2364
+ }
2365
+ for (const { localProjectModule, result } of localProjectModuleResults) {
2366
+ const modulePlaceholder = createModulePlaceholder(
2367
+ localProjectModule.name
2368
+ );
2369
+ renderContext.islands.push(...result.renderContext.islands);
2370
+ resolvedCss = resolvedCss.concat(result.cssNeeded);
2371
+ resolvedInlineAssets = resolvedInlineAssets.concat(result.inlineAssets);
2372
+ partialHtml = partialHtml.replace(modulePlaceholder, result.html);
2373
+ }
2374
+ }
2375
+ const htmlShell = await createHtmlShellDependingOnRenderContext(
2376
+ baseTemplatePath,
2377
+ request2.originalUrl,
2378
+ `Partial: ${partialPath}`,
2379
+ renderContext,
2380
+ viteServer,
2381
+ jsRenderingGates
2382
+ );
2383
+ const html = htmlShell.replace(
2384
+ "<!--headend-->",
2385
+ [
2386
+ resolvedCss,
2387
+ ...resolvedInlineAssets.map((inlineAsset) => inlineAsset.html)
2388
+ ].join("\n")
2389
+ ).replace(`<!--ssr-outlet-->`, partialHtml);
2390
+ response.status(200).set({ "Content-Type": "text/html" }).end(html);
2391
+ } catch (e) {
2392
+ console.error(e);
2393
+ viteServer.ssrFixStacktrace(e);
2394
+ response.status(500).end(`Error rendering partial (${partialName})
2395
+
2396
+ ${e.stack}`);
2397
+ }
2398
+ };
2399
+ function createModulePlaceholder(moduleName) {
2400
+ return `<!-- hs-module-placeholder-${moduleName} -->`;
2401
+ }
2402
+ var partial_default = partialRouteHandler;
2403
+
2404
+ // src/components/PartialsList.tsx
2405
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
2406
+ function EmptyPartialsList({ webRoot: webRoot2 }) {
2407
+ return /* @__PURE__ */ jsxs("p", { children: [
2408
+ "No partials in ",
2409
+ /* @__PURE__ */ jsxs("code", { children: [
2410
+ webRoot2,
2411
+ "components/partials"
2412
+ ] })
2413
+ ] });
2414
+ }
2415
+ function PartialLinkInLI({ partialName }) {
2416
+ return /* @__PURE__ */ jsx2("li", { children: /* @__PURE__ */ jsx2("a", { href: `/partial/${partialName}`, children: partialName }) });
2417
+ }
2418
+ function PartialsList({ webRoot: webRoot2, partialNames }) {
2419
+ if (partialNames.length === 0) {
2420
+ return /* @__PURE__ */ jsx2(EmptyPartialsList, { webRoot: webRoot2 });
2421
+ }
2422
+ return /* @__PURE__ */ jsx2("ul", { children: partialNames.map((partialName) => /* @__PURE__ */ jsx2(PartialLinkInLI, { partialName }, partialName)) });
2423
+ }
2424
+
2425
+ // src/routes/linksToAllPartialsRouteHandler.tsx
2426
+ import { jsx as jsx3 } from "react/jsx-runtime";
2427
+ var linksToAllPartialRouteHandler = async (request2, response) => {
2428
+ const { webRoot: webRoot2 } = request2.app.locals;
2429
+ const { partialNames } = findAllPartialsInRoot(webRoot2);
2430
+ const { html: responseHtml } = await renderOnServer(
2431
+ /* @__PURE__ */ jsx3(PartialsList, { webRoot: webRoot2, partialNames })
2432
+ );
2433
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
2434
+ };
2435
+ var linksToAllPartialsRouteHandler_default = linksToAllPartialRouteHandler;
2436
+
2437
+ // src/components/ModulesList.tsx
2438
+ import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
2439
+ function EmptyModulesList({ webRoot: webRoot2 }) {
2440
+ return /* @__PURE__ */ jsxs2("p", { children: [
2441
+ "No modules in ",
2442
+ /* @__PURE__ */ jsxs2("code", { children: [
2443
+ webRoot2,
2444
+ "components/modules"
2445
+ ] })
2446
+ ] });
2447
+ }
2448
+ function ModuleLinkInLI({ moduleName }) {
2449
+ return /* @__PURE__ */ jsxs2("li", { children: [
2450
+ /* @__PURE__ */ jsx4("a", { href: `/preview/module/${moduleName}`, children: moduleName }),
2451
+ " / ",
2452
+ /* @__PURE__ */ jsx4("a", { href: `/module/${moduleName}`, children: "Local Version" })
2453
+ ] });
2454
+ }
2455
+ function ModulesList({ webRoot: webRoot2, moduleNames }) {
2456
+ if (moduleNames.length === 0) {
2457
+ return /* @__PURE__ */ jsx4(EmptyModulesList, { webRoot: webRoot2 });
2458
+ }
2459
+ return /* @__PURE__ */ jsx4("ul", { children: moduleNames.map((moduleName) => /* @__PURE__ */ jsx4(ModuleLinkInLI, { moduleName }, moduleName)) });
2460
+ }
2461
+ var ModulesList_default = ModulesList;
2462
+
2463
+ // src/routes/linksToAllModulesRouteHandler.tsx
2464
+ import { jsx as jsx5 } from "react/jsx-runtime";
2465
+ var linksToAllModuleRouteHandler = async (request2, response) => {
2466
+ const { webRoot: webRoot2 } = request2.app.locals;
2467
+ const { moduleNames } = findAllModulesInRoot(webRoot2);
2468
+ const { html: responseHtml } = await renderOnServer(
2469
+ /* @__PURE__ */ jsx5(ModulesList_default, { webRoot: webRoot2, moduleNames })
2470
+ );
2471
+ response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
2472
+ };
2473
+ var linksToAllModulesRouteHandler_default = linksToAllModuleRouteHandler;
2474
+
2475
+ // src/routes/module.ts
2476
+ import { buildStaticEnvConfig as buildStaticEnvConfig4 } from "@hubspot/cms-components";
2477
+ import path6 from "path";
2478
+ import { normalizePath as normalizePath5 } from "vite";
2479
+ var moduleRouteHandler = async (request2, response) => {
2480
+ sendTrackingRequest("view-module-route");
2481
+ const {
2482
+ authedPortalId,
2483
+ authedEnv,
2484
+ authedHublet,
2485
+ webRoot: webRoot2,
2486
+ viteServer,
2487
+ jsRenderingGates,
2488
+ projectName,
2489
+ projectComponentPath
2490
+ } = request2.app.locals;
2491
+ const moduleName = request2.params.moduleName;
2492
+ const baseTemplatePath = packagePath(
2493
+ import.meta.url,
2494
+ "html/baseTemplate.html"
2495
+ );
2496
+ const modulePath = normalizePath5(
2497
+ path6.resolve(webRoot2, "components/modules/", moduleName)
2498
+ );
2499
+ const entrypointPath = normalizePath5(
2500
+ [
2501
+ "@projects",
2502
+ projectName,
2503
+ projectComponentPath,
2504
+ "components/modules/",
2505
+ moduleName
2506
+ ].join("/")
2507
+ );
2508
+ let fieldOverrides = null;
2509
+ if (request2.query.fields) {
2510
+ try {
2511
+ if (typeof request2.query.fields === "string") {
2512
+ fieldOverrides = JSON.parse(
2513
+ decodeURIComponent(request2.query.fields.replace(/\+/g, "%20"))
2514
+ );
2515
+ }
2516
+ } catch (e) {
2517
+ console.error(
2518
+ `Error parsing field param for module ${moduleName}: ${request2.query.fields}`
2519
+ );
2520
+ }
2521
+ }
2522
+ const basePath = getEntryPointBasePath(modulePath);
2523
+ const environmentConfig = buildStaticEnvConfig4(
2524
+ authedPortalId,
2525
+ authedHublet,
2526
+ authedEnv,
2527
+ false,
2528
+ jsRenderingGates
2529
+ );
2530
+ try {
2531
+ const {
2532
+ html: renderedHtml,
2533
+ cssNeeded,
2534
+ renderContext,
2535
+ inlineAssets
2536
+ } = await renderModule_default(
2537
+ viteServer,
2538
+ modulePath,
2539
+ {
2540
+ fieldValues: fieldOverrides,
2541
+ hublParameters: {},
2542
+ moduleName: `local-${moduleName}`
2543
+ },
2544
+ fullOriginalUrlFromRequest(request2),
2545
+ basePath,
2546
+ environmentConfig,
2547
+ {
2548
+ identifierPrefix: getEntryPointHash(entrypointPath)
2549
+ }
2550
+ );
2551
+ const htmlShell = await createHtmlShellDependingOnRenderContext(
2552
+ baseTemplatePath,
2553
+ request2.originalUrl,
2554
+ `Module: ${modulePath}`,
2555
+ renderContext,
2556
+ viteServer,
2557
+ jsRenderingGates
2558
+ );
2559
+ const html = htmlShell.replace(
2560
+ "<!--headend-->",
2561
+ [
2562
+ cssNeeded,
2563
+ ...inlineAssets.map((inlineAsset) => inlineAsset.html)
2564
+ ].join("\n")
2565
+ ).replace(`<!--ssr-outlet-->`, renderedHtml);
2566
+ response.status(200).set({ "Content-Type": "text/html" }).end(html);
2567
+ } catch (e) {
2568
+ console.error(e);
2569
+ viteServer.ssrFixStacktrace(e);
2570
+ response.status(500).end(`Error rendering module (${moduleName})
2571
+
2572
+ ${e.stack}`);
2573
+ }
2574
+ };
2575
+ var module_default = moduleRouteHandler;
2576
+
2577
+ // src/proxyPage/fetchContentMetadata.ts
2578
+ import http from "http";
2579
+ import https from "https";
2580
+ import { getAccountId as getAccountId2 } from "@hubspot/local-dev-lib/config";
2581
+ async function requestPage(url3, redirects = 0, originalUrl) {
2582
+ if (redirects > 5) {
2583
+ throw new Error(
2584
+ `Hit too many redirects to HEAD requests for ${originalUrl}`
2585
+ );
2586
+ }
2587
+ return new Promise((resolve3, reject) => {
2588
+ const protocolAPI = url3.startsWith("https://") ? https : http;
2589
+ protocolAPI.request(
2590
+ url3,
2591
+ {
2592
+ method: "HEAD",
2593
+ headers: {
2594
+ // Keep this user agent, so we don't get 403s from the request
2595
+ ["User-Agent"]: "cms-dev-server"
2150
2596
  }
2151
- const renderPromise = renderComponentForPlaceholder(
2152
- indexForThisRender,
2153
- localRenderPlaceholder,
2154
- webRoot2,
2155
- viteServer,
2156
- fullOriginalUrl,
2157
- basePath,
2158
- environmentConfig,
2159
- projectName,
2160
- projectComponentPath
2597
+ },
2598
+ async (res) => {
2599
+ let portalIdHeader;
2600
+ let contentId;
2601
+ const isContentMembershipRedirect = Boolean(
2602
+ res.headers["x-hs-content-membership-redirect"]
2161
2603
  );
2162
- renderPromisesByChunkIndex[indexForThisRender] = renderPromise.then((promiseResult) => {
2163
- var _a;
2164
- let { html, cssNeeded, inlineAssets, renderContext } = promiseResult;
2165
- console.log(
2166
- `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`
2167
- );
2168
- if ((_a = renderContext.criticalDevErrors) == null ? void 0 : _a.length) {
2169
- criticalDevErrors.push(...renderContext.criticalDevErrors);
2170
- }
2171
- if (renderContext.islands.length > 0) {
2172
- islands = islands.concat(renderContext.islands);
2173
- }
2174
- mergedPerRequestState = mergeServerRequestData_internal(
2175
- mergedPerRequestState,
2176
- renderContext.perServerRequestData
2177
- );
2178
- let result = html;
2179
- if (inlineAssets) {
2180
- result = `${inlineAssets.map((inlineAsset) => inlineAsset.html).join("\n")}
2181
- ${result}`;
2182
- }
2183
- if (cssNeeded) {
2184
- result = `${cssNeeded}
2185
- ${result}`;
2604
+ if (isContentMembershipRedirect) {
2605
+ debug("Content Membership Redirect", res.headers);
2606
+ portalIdHeader = res.headers["x-hs-portal-id"];
2607
+ contentId = res.headers["x-hs-content-id"];
2608
+ if (portalIdHeader && contentId) {
2609
+ return resolve3({
2610
+ portalIdHeader,
2611
+ contentId,
2612
+ res
2613
+ });
2186
2614
  }
2187
- return result;
2188
- }).catch((e) => {
2189
- numJsRenderFailures += 1;
2190
- console.log(
2191
- "Attempted to render",
2192
- localRenderPlaceholder.path,
2193
- "with props",
2194
- localRenderPlaceholder.json
2615
+ }
2616
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
2617
+ console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
2618
+ return resolve3(
2619
+ requestPage(
2620
+ res.headers.location,
2621
+ redirects + 1,
2622
+ originalUrl ?? url3
2623
+ )
2195
2624
  );
2196
- console.error(e);
2197
- return renderLocalError_default(localRenderPlaceholder.path, e);
2625
+ }
2626
+ portalIdHeader = res.headers["x-hs-hub-id"];
2627
+ contentId = res.headers["x-hs-content-id"];
2628
+ return resolve3({
2629
+ res,
2630
+ portalIdHeader,
2631
+ contentId
2198
2632
  });
2199
- offsetSoFar = localRenderPlaceholder.endOffset;
2200
- }
2201
- pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
2202
- response.writeHead(200);
2203
- for (let i = 0; i < localRenderPlaceholders.length; i++) {
2204
- const chunk = pageChunks[i];
2205
- response.write(chunk);
2206
- const foobar = await renderPromisesByChunkIndex[i];
2207
- response.write(foobar);
2208
2633
  }
2209
- response.write(
2210
- getServerGlobalsToInject(
2211
- environmentConfig,
2212
- fullOriginalUrl,
2213
- basePath,
2214
- void 0,
2215
- criticalDevErrors
2216
- )
2634
+ ).on("error", (err) => {
2635
+ console.error(err);
2636
+ reject(err);
2637
+ }).end();
2638
+ });
2639
+ }
2640
+ async function fetchContentMetadata(url3, portalId) {
2641
+ const { portalIdHeader, contentId, res } = await requestPage(url3);
2642
+ if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
2643
+ throw new Error(
2644
+ `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
2645
+ );
2646
+ } else {
2647
+ const portalIdFromResponse = parseInt(portalIdHeader, 10);
2648
+ const pageAccount = await getAccountId2(portalIdFromResponse);
2649
+ if (!pageAccount) {
2650
+ throw new Error(
2651
+ `No CLI auth for portal ${portalIdFromResponse} found, please run \`hs auth\``
2217
2652
  );
2218
- if (criticalDevErrors.length) {
2219
- response.write(
2220
- scriptTagToLogServerMessages(
2221
- criticalDevErrorsToServerMessages_default(criticalDevErrors),
2222
- "@hubspot/cms-dev-server messages"
2223
- )
2224
- );
2225
- }
2226
- if (islands.length > 0) {
2227
- const sortedIslandRoots = sortIslandRootsByPriority(islands);
2228
- const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
2229
- sortedIslandRoots,
2230
- mergedPerRequestState,
2231
- viteServer,
2232
- jsRenderingGates,
2233
- prettyPrint
2234
- );
2235
- response.write(islandRuntimeAndGlobalScriptHtml);
2236
- }
2237
- response.write(pageChunks[pageChunks.length - 1]);
2238
- response.end();
2239
- } else {
2240
- response.writeHead(200);
2241
- response.write(pageHtml);
2242
- response.end();
2243
2653
  }
2244
- } catch (error) {
2245
- response.status(500).end(
2246
- `Failed proxy render of page id = ${contentId} hub id = ${portalId}
2247
-
2248
- ${error.stack}`
2249
- );
2250
- return;
2654
+ if (res.statusCode !== 200 && !(portalIdFromResponse && pageAccount && contentId)) {
2655
+ throw new Error(
2656
+ `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url3}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
2657
+ );
2658
+ } else if (!portalId || !contentId) {
2659
+ throw new Error(
2660
+ `Missing hub ID or content ID headers on HEAD request to ${url3}`
2661
+ );
2662
+ } else if (isNaN(portalId)) {
2663
+ throw new Error(
2664
+ `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
2665
+ );
2666
+ }
2667
+ const hublet = "na1";
2668
+ return { portalId, contentId, hublet };
2251
2669
  }
2252
2670
  }
2253
2671
 
@@ -2551,11 +2969,8 @@ function proxyServerlessRequest(req, res, next) {
2551
2969
  }
2552
2970
 
2553
2971
  // src/routes/modulePreviewRouteHandler.ts
2554
- import { buildStaticEnvConfig as buildStaticEnvConfig4 } from "@hubspot/cms-components";
2555
- import path6 from "path";
2556
- import { normalizePath as normalizePath5 } from "vite";
2557
- import localDevHttpImport6 from "@hubspot/local-dev-lib/http";
2558
- var { default: hsCliHttp6 } = localDevHttpImport6;
2972
+ import path7 from "path";
2973
+ import { normalizePath as normalizePath6 } from "vite";
2559
2974
  async function modulePreviewRouteHandler(request2, response) {
2560
2975
  sendTrackingRequest("view-module-preview-route");
2561
2976
  const {
@@ -2569,116 +2984,27 @@ async function modulePreviewRouteHandler(request2, response) {
2569
2984
  projectComponentPath
2570
2985
  } = request2.app.locals;
2571
2986
  const moduleName = request2.params.moduleName;
2572
- const modulePath = normalizePath5(
2573
- path6.resolve(webRoot2, "components/modules/", moduleName)
2574
- );
2575
- const basePath = `preview/${getEntryPointBasePath(modulePath)}`;
2576
- const environmentConfig = buildStaticEnvConfig4(
2577
- authedPortalId,
2578
- authedHublet,
2579
- authedEnv,
2580
- false,
2581
- jsRenderingGates
2987
+ const modulePath = normalizePath6(
2988
+ path7.resolve(webRoot2, "components/modules/", moduleName)
2582
2989
  );
2583
- let templatePreview;
2584
- try {
2585
- let componentModule;
2586
- let foundPath;
2587
- if (!hasComponentExtension(modulePath)) {
2588
- [componentModule, foundPath] = await lookForModuleInFolder2(
2589
- modulePath,
2590
- viteServer
2591
- );
2592
- }
2593
- if (!componentModule) {
2594
- componentModule = await viteServer.ssrLoadModule(modulePath);
2595
- foundPath = componentModule ? modulePath : void 0;
2596
- }
2597
- if (!componentModule) {
2598
- throw new Error(`Couldn't find module: ${modulePath}`);
2599
- }
2600
- const Component = componentModule.Component;
2601
- const fields = componentModule.fields;
2602
- const meta = componentModule.meta;
2603
- const hublDataTemplate = componentModule.hublDataTemplate;
2604
- if (!Component) {
2605
- throw new Error(
2606
- `Module does not have a named Component export: ${foundPath}`
2607
- );
2608
- } else if (!fields) {
2609
- throw new Error(
2610
- `Module does not have a named fields export: ${foundPath}`
2611
- );
2612
- } else if (!meta) {
2613
- throw new Error(`Module does not have a named meta export: ${foundPath}`);
2614
- }
2615
- const internalSsrPath = packagePath(import.meta.url, "internalSsr");
2616
- const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
2617
- const localFieldsJson = renderFieldsToJson(fields, modulePath);
2618
- const localModule = {
2619
- isJsModule: true,
2620
- schemaVersion: 2,
2621
- fields: localFieldsJson,
2622
- id: 1,
2623
- path: `@projects/${projectName}/${projectComponentPath}/components/modules/${moduleName}`,
2624
- hublDataTemplate
2625
- };
2626
- const queryParams = new URLSearchParams({
2627
- portalId: `${authedPortalId}`,
2628
- hsLocalProxy: `${true}`,
2629
- localProxySchemaVersion: "2",
2630
- hsLoginVerifyDisabled: `${true}`
2631
- });
2632
- const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2633
- process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2634
- const templatePreviewPromise = hsCliHttp6.post(authedPortalId, {
2635
- url: `/api/cos-rendering/v1/public/_hcms/preview/template/multiform?${queryParams}`,
2636
- headers: {
2637
- ["content-type"]: "application/x-www-form-urlencoded",
2638
- ["Accept"]: "text/html",
2639
- referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2640
- cookie: request2.get("COOKIE"),
2641
- "User-Agent": "HubSpot CMS Dev Server"
2642
- },
2643
- data: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2644
- });
2645
- if (currentHubApiDomainOverride) {
2646
- process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2647
- } else {
2648
- delete process.env.HUBAPI_DOMAIN_OVERRIDE;
2649
- }
2650
- templatePreview = await templatePreviewPromise;
2651
- } catch (e) {
2652
- return response.status(500).end(`Error fetching module preview for (${moduleName}).
2653
-
2654
- ${e}.
2655
-
2656
- `);
2657
- }
2658
2990
  try {
2659
- const localRenderPlaceholders = findLocalRenderPlaceholders(templatePreview);
2660
- if (localRenderPlaceholders.length !== 1) {
2661
- return response.status(500).end(
2662
- `Error previewing module (${moduleName}), exception in module preview HTML
2663
-
2664
- `
2665
- );
2666
- }
2667
2991
  const {
2668
2992
  html: renderedHtml,
2669
2993
  cssNeeded,
2670
2994
  renderContext,
2671
2995
  inlineAssets
2672
- } = await renderComponentForPlaceholder(
2673
- 0,
2674
- localRenderPlaceholders[0],
2996
+ } = await renderLocalProjectModulePreview(
2997
+ moduleName,
2998
+ authedPortalId,
2999
+ authedEnv,
3000
+ authedHublet,
2675
3001
  webRoot2,
2676
3002
  viteServer,
2677
- fullOriginalUrlFromRequest(request2),
2678
- basePath,
2679
- environmentConfig,
3003
+ jsRenderingGates,
2680
3004
  projectName,
2681
- projectComponentPath
3005
+ projectComponentPath,
3006
+ fullOriginalUrlFromRequest(request2),
3007
+ request2.get("COOKIE")
2682
3008
  );
2683
3009
  const baseTemplatePath = packagePath(
2684
3010
  import.meta.url,
@@ -2955,6 +3281,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
2955
3281
  include: ["react", "react-dom", "react-dom/client"]
2956
3282
  },
2957
3283
  plugins: [
3284
+ jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
2958
3285
  sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
2959
3286
  react({
2960
3287
  babel: {
@@ -3143,7 +3470,7 @@ async function fetchWebsiteDomainNames(portalId) {
3143
3470
  }
3144
3471
 
3145
3472
  // src/lib/validateHSPlatform.ts
3146
- import path7 from "path";
3473
+ import path8 from "path";
3147
3474
  import fs3 from "fs";
3148
3475
  import select from "@inquirer/select";
3149
3476
  import localDevHttpImport8 from "@hubspot/local-dev-lib/http";
@@ -3156,12 +3483,12 @@ function findHSProjectJson(startPath) {
3156
3483
  let currentDir = startPath;
3157
3484
  let dirLevel = 0;
3158
3485
  const maxDirLevel = 4;
3159
- while (path7.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
3160
- const filePath = path7.join(currentDir, HSPROJECT_JSON);
3486
+ while (path8.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
3487
+ const filePath = path8.join(currentDir, HSPROJECT_JSON);
3161
3488
  if (checkFileExists(filePath)) {
3162
3489
  return filePath;
3163
3490
  }
3164
- currentDir = path7.dirname(currentDir);
3491
+ currentDir = path8.dirname(currentDir);
3165
3492
  dirLevel++;
3166
3493
  }
3167
3494
  console.log(
@@ -3467,7 +3794,7 @@ function writeFieldsType(fields, fileName, typeName) {
3467
3794
 
3468
3795
  // src/lib/watchFieldsUpdates.ts
3469
3796
  import fs4 from "fs";
3470
- import path8 from "path";
3797
+ import path9 from "path";
3471
3798
  import readline from "readline";
3472
3799
  var lastSerializedFieldsCache = {};
3473
3800
  var formatAsTypeName = (str) => {
@@ -3479,9 +3806,9 @@ var isInModulesFolder = (filePath, projectRoot) => {
3479
3806
  const getEntryPathFromId = (id) => {
3480
3807
  return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
3481
3808
  };
3482
- const currentModuleId = path8.normalize(filePath);
3809
+ const currentModuleId = path9.normalize(filePath);
3483
3810
  const moduleEntryPath = getEntryPathFromId(currentModuleId);
3484
- const subFolderTokens = moduleEntryPath.split(path8.sep);
3811
+ const subFolderTokens = moduleEntryPath.split(path9.sep);
3485
3812
  return {
3486
3813
  inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
3487
3814
  isRootModuleFile: subFolderTokens.length === 3
@@ -3508,10 +3835,10 @@ var getIndexFile = (filePath, projectRoot) => {
3508
3835
  return void 0;
3509
3836
  if (isRootModuleFile)
3510
3837
  return { indexFilePath: filePath, isRootModuleFile };
3511
- const dir = path8.dirname(filePath);
3838
+ const dir = path9.dirname(filePath);
3512
3839
  const files = fs4.readdirSync(dir);
3513
3840
  const indexFileName = files.find((file) => file.startsWith("index."));
3514
- return indexFileName ? { indexFilePath: path8.join(dir, indexFileName), isRootModuleFile } : void 0;
3841
+ return indexFileName ? { indexFilePath: path9.join(dir, indexFileName), isRootModuleFile } : void 0;
3515
3842
  };
3516
3843
  var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
3517
3844
  let indexFile;
@@ -3535,7 +3862,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3535
3862
  if (!indexInfo)
3536
3863
  return;
3537
3864
  const { indexFilePath, isRootModuleFile } = indexInfo;
3538
- const indexFileName = path8.parse(indexFilePath).name;
3865
+ const indexFileName = path9.parse(indexFilePath).name;
3539
3866
  const isTypeFile = filePath.endsWith(".types.ts");
3540
3867
  if (isTypeFile)
3541
3868
  return;
@@ -3546,7 +3873,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3546
3873
  );
3547
3874
  if (fields) {
3548
3875
  const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
3549
- const typeFilePath = path8.join(path8.dirname(filePath), typeFileName);
3876
+ const typeFilePath = path9.join(path9.dirname(filePath), typeFileName);
3550
3877
  const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
3551
3878
  const serializedFields = JSON.stringify(fields);
3552
3879
  if (lastSerializedFields === serializedFields)
@@ -3554,7 +3881,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3554
3881
  const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
3555
3882
  if (!hasAutoGenComment)
3556
3883
  return;
3557
- const moduleFolderName = path8.basename(path8.dirname(filePath));
3884
+ const moduleFolderName = path9.basename(path9.dirname(filePath));
3558
3885
  const outputTypeName = formatAsTypeName(moduleFolderName);
3559
3886
  const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
3560
3887
  if (didSucceed) {
@@ -3570,7 +3897,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3570
3897
  var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
3571
3898
  const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
3572
3899
  moduleSubpaths.forEach((modulePath) => {
3573
- const resolvedPath = path8.resolve(projectRoot, modulePath);
3900
+ const resolvedPath = path9.resolve(projectRoot, modulePath);
3574
3901
  maybeUpdateFields(resolvedPath, viteServer, projectRoot);
3575
3902
  });
3576
3903
  const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
@@ -3703,7 +4030,7 @@ Local proxy functionality and module preview routes will not work without settin
3703
4030
  } catch (e) {
3704
4031
  authedHublet = "na1";
3705
4032
  }
3706
- const absoluteWebRoot = normalizePath6(path9.resolve(process.cwd(), webRoot2));
4033
+ const absoluteWebRoot = normalizePath7(path10.resolve(process.cwd(), webRoot2));
3707
4034
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
3708
4035
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
3709
4036
  if (authedPortalId) {
@@ -3780,8 +4107,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3780
4107
  `
3781
4108
  );
3782
4109
  if (storybook2) {
3783
- const packageRoot = path9.dirname(url2.fileURLToPath(import.meta.url));
3784
- const configPath = path9.resolve(packageRoot, "./storybook-main");
4110
+ const packageRoot = path10.dirname(url2.fileURLToPath(import.meta.url));
4111
+ const configPath = path10.resolve(packageRoot, "./storybook-main");
3785
4112
  sendTrackingRequest("start-storybook");
3786
4113
  const storybookProcess = spawn(
3787
4114
  "sb",
@@ -3801,7 +4128,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3801
4128
  portalId: authedPortalId.toString(),
3802
4129
  hsEnv: authedEnv,
3803
4130
  hublet: authedHublet,
3804
- WEB_ROOT: path9.join(webRoot2, "components")
4131
+ WEB_ROOT: path10.join(webRoot2, "components")
3805
4132
  }
3806
4133
  }
3807
4134
  );