@hubspot/cms-dev-server 1.2.33 → 1.2.35

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/index.js CHANGED
@@ -3,7 +3,7 @@ import { createServer as createViteServer } from "vite";
3
3
  import { createRequire } from "module";
4
4
  import { default as react } from "@vitejs/plugin-react";
5
5
 
6
- // ../cms-js-internal/dist/types-BsFs0N9P.js
6
+ // ../cms-js-internal/dist/types-BEz622C8.js
7
7
  import path from "path";
8
8
  import { createHash } from "crypto";
9
9
  import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
@@ -118,7 +118,7 @@ function resolveIslandPlugin(islandsSet) {
118
118
  idWithNoParam,
119
119
  componentExtension
120
120
  );
121
- const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
121
+ const modulePath = path.relative(viteRoot, idWithNoParam);
122
122
  const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
123
123
  if (islandsSet) {
124
124
  islandsSet.add(moduleId);
@@ -237,10 +237,20 @@ function getCMSAssetConfig(webRoot) {
237
237
  );
238
238
  return parsedConfig;
239
239
  }
240
+ function getCMSAssetConfigIfExists(webRoot) {
241
+ try {
242
+ return getCMSAssetConfig(webRoot);
243
+ } catch (e) {
244
+ console.error(
245
+ `Error finding or parsing cms-assets.json in ${webRoot}, but ignoring for now`
246
+ );
247
+ return {};
248
+ }
249
+ }
240
250
  var ENABLED_FEATURES_GATE_MAP = {
241
251
  "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
242
- "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
243
- "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
252
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules",
253
+ "PortalsAccessIdentity:DesignManager:UrlSigning": "PortalsAccessIdentity:DesignManager:UrlSigning"
244
254
  };
245
255
  function isUngatedFor(gates, gate) {
246
256
  return gates.includes(gate);
@@ -663,8 +673,8 @@ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap)
663
673
  );
664
674
  return Object.fromEntries(relativeEntries);
665
675
  }
666
- function toRelativePath(config, path17) {
667
- return path17.replace(`${config.root}/`, "");
676
+ function toRelativePath(config, path18) {
677
+ return path18.replace(`${config.root}/`, "");
668
678
  }
669
679
  function shouldAnalyzeModule(config, moduleInfo, code) {
670
680
  const [fileId, __] = moduleInfo.id.split("?");
@@ -707,11 +717,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
707
717
  let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
708
718
  let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
709
719
  traverse(sourceAst, {
710
- ImportDeclaration(path17) {
711
- if (t.isStringLiteral(path17.node.source, {
720
+ ImportDeclaration(path18) {
721
+ if (t.isStringLiteral(path18.node.source, {
712
722
  value: "@hubspot/cms-components"
713
723
  })) {
714
- for (const specifier of path17.node.specifiers) {
724
+ for (const specifier of path18.node.specifiers) {
715
725
  if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
716
726
  name: CMS_MODULE_COMPONENT_NAME
717
727
  })) {
@@ -725,14 +735,14 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
725
735
  }
726
736
  }
727
737
  },
728
- JSXOpeningElement(path17) {
729
- if (t.isJSXIdentifier(path17.node.name, {
738
+ JSXOpeningElement(path18) {
739
+ if (t.isJSXIdentifier(path18.node.name, {
730
740
  name: moduleComponentLocalImportName
731
741
  })) {
732
742
  let cmsModuleName;
733
743
  let cmsModulePath;
734
744
  let cmsModuleLabel;
735
- for (const prop of path17.node.attributes) {
745
+ for (const prop of path18.node.attributes) {
736
746
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
737
747
  cmsModuleName = prop.value.value;
738
748
  continue;
@@ -767,11 +777,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
767
777
  }
768
778
  contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
769
779
  }
770
- if (t.isJSXIdentifier(path17.node.name, {
780
+ if (t.isJSXIdentifier(path18.node.name, {
771
781
  name: dndAreaComponentLocalImportName
772
782
  })) {
773
783
  let dndAreaName;
774
- for (const prop of path17.node.attributes) {
784
+ for (const prop of path18.node.attributes) {
775
785
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
776
786
  dndAreaName = prop.value.value;
777
787
  continue;
@@ -1173,7 +1183,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
1173
1183
  }),
1174
1184
  clientIslandEntryPlugin(),
1175
1185
  resolveIslandPlugin(),
1176
- jsRenderingGates.includes("CMS:JSRenderer:RemoveCjsPlugin") ? null : viteCommonjs(),
1186
+ viteCommonjs(),
1177
1187
  devSecretsPlugin(secretNames),
1178
1188
  noncePlaceholderPlugin()
1179
1189
  ] : [];
@@ -1210,8 +1220,8 @@ Custom origin: ${process.env.VITE_ORIGIN}
1210
1220
  var createViteDevServer_default = createViteDevServer;
1211
1221
 
1212
1222
  // src/createDevServer.ts
1213
- import path16 from "path";
1214
- import fs7 from "fs";
1223
+ import path17 from "path";
1224
+ import fs8 from "fs";
1215
1225
  import url2 from "url";
1216
1226
  import express2 from "express";
1217
1227
  import http3 from "http";
@@ -1226,6 +1236,7 @@ import {
1226
1236
  static as expressStatic
1227
1237
  } from "express";
1228
1238
  import { createProxyMiddleware as createProxyMiddleware2 } from "http-proxy-middleware";
1239
+ import cors from "cors";
1229
1240
 
1230
1241
  // src/routes/partial.ts
1231
1242
  import path7 from "path";
@@ -1631,7 +1642,7 @@ function trackUsage(action) {
1631
1642
  eventName: EVENT_NAME,
1632
1643
  action,
1633
1644
  nodeVersion: getNodeVersionData(),
1634
- version: "1.2.17",
1645
+ version: "1.2.35",
1635
1646
  os: getPlatform()
1636
1647
  };
1637
1648
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1704,12 +1715,12 @@ var findLocalRenderPlaceholders = (body) => {
1704
1715
  );
1705
1716
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1706
1717
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1707
- const path17 = body.substring(
1718
+ const path18 = body.substring(
1708
1719
  startOffset + localJsRenderStartString.length,
1709
1720
  pathEndOffset
1710
1721
  );
1711
1722
  offsetSoFar = pathEndOffset + 1;
1712
- if (startOffset >= 0 && path17) {
1723
+ if (startOffset >= 0 && path18) {
1713
1724
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1714
1725
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1715
1726
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1734,7 +1745,7 @@ var findLocalRenderPlaceholders = (body) => {
1734
1745
  result.push({
1735
1746
  startOffset,
1736
1747
  endOffset: endOffset + localJsRenderEndString.length,
1737
- path: path17,
1748
+ path: path18,
1738
1749
  json
1739
1750
  });
1740
1751
  }
@@ -2113,9 +2124,9 @@ var customColors = [
2113
2124
  ];
2114
2125
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
2115
2126
  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;`;
2116
- var renderLocalError_default = (path17, error) => {
2127
+ var renderLocalError_default = (path18, error) => {
2117
2128
  const stackWithColorClasses = Converter.toHtml(error.stack);
2118
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path17}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2129
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path18}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2119
2130
  };
2120
2131
 
2121
2132
  // src/proxyPage/fetchPreviewInfo.ts
@@ -2912,8 +2923,51 @@ import { http as hsCliHttp7 } from "@hubspot/local-dev-lib/http";
2912
2923
  import { getConfigAccountIfExists as getConfigAccountIfExists3 } from "@hubspot/local-dev-lib/config";
2913
2924
  import { accessTokenForPersonalAccessKey } from "@hubspot/local-dev-lib/personalAccessKey";
2914
2925
  import jsdom from "jsdom";
2926
+ var URL_SIGNING_GATE = "PortalsAccessIdentity:DesignManager:UrlSigning";
2927
+ async function signGetUrl(authedPortalId, unsignedUrl) {
2928
+ const urlWithPortalId = new URL(unsignedUrl);
2929
+ urlWithPortalId.searchParams.set("portalId", `${authedPortalId}`);
2930
+ const response = await hsCliHttp7.post(authedPortalId, {
2931
+ url: "/url-signer-rest/v1/signing",
2932
+ headers: {
2933
+ "Content-Type": "application/json",
2934
+ Accept: "application/json"
2935
+ },
2936
+ data: JSON.stringify({
2937
+ unsignedUrl: urlWithPortalId.toString(),
2938
+ httpMethod: "GET"
2939
+ })
2940
+ });
2941
+ return response.data.signedUrl;
2942
+ }
2943
+ async function signedGet(authedPortalId, unsignedUrl, headers, gates) {
2944
+ if (!isUngatedFor(gates, URL_SIGNING_GATE)) {
2945
+ const { data } = await hsCliHttp7.get(authedPortalId, {
2946
+ url: unsignedUrl,
2947
+ headers
2948
+ });
2949
+ return data;
2950
+ }
2951
+ const signedUrl = await signGetUrl(authedPortalId, unsignedUrl);
2952
+ const authHeaders = {};
2953
+ const accountConfig = getConfigAccountIfExists3(authedPortalId);
2954
+ if (accountConfig && accountConfig.authType === "personalaccesskey") {
2955
+ const accessToken = await accessTokenForPersonalAccessKey(authedPortalId);
2956
+ authHeaders["Authorization"] = `Bearer ${accessToken}`;
2957
+ }
2958
+ const response = await fetch(signedUrl, {
2959
+ method: "GET",
2960
+ headers: { ...headers, ...authHeaders }
2961
+ });
2962
+ if (!response.ok) {
2963
+ throw new Error(
2964
+ `Preview GET failed: ${response.status} ${response.statusText}`
2965
+ );
2966
+ }
2967
+ return await response.text();
2968
+ }
2915
2969
  var { JSDOM } = jsdom;
2916
- async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue) {
2970
+ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue, gates) {
2917
2971
  const moduleInfoQueryParams = new URLSearchParams({
2918
2972
  portalId: `${authedPortalId}`
2919
2973
  });
@@ -2928,8 +2982,6 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2928
2982
  "User-Agent": "HubSpot CMS Dev Server"
2929
2983
  }
2930
2984
  })).data;
2931
- const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2932
- process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2933
2985
  const queryParams = new URLSearchParams({
2934
2986
  portalId: `${authedPortalId}`,
2935
2987
  hsLocalProxy: `${true}`,
@@ -2937,20 +2989,34 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2937
2989
  hsLoginVerifyDisabled: `${true}`,
2938
2990
  module_id: moduleInfo.moduleId
2939
2991
  });
2940
- const modulePreviewHtml = (await hsCliHttp7.get(authedPortalId, {
2941
- url: `/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`,
2942
- headers: {
2943
- ["content-type"]: "application/x-www-form-urlencoded",
2944
- ["Accept"]: "text/html",
2945
- referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2946
- cookie: cookieValue,
2947
- "User-Agent": "HubSpot CMS Dev Server"
2992
+ const cosRenderingUrl = `https://api.hubspot${authedEnv === "qa" ? "qa" : ""}.com/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`;
2993
+ const previousHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2994
+ const needsDomainOverride = !isUngatedFor(gates, URL_SIGNING_GATE);
2995
+ if (needsDomainOverride) {
2996
+ process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2997
+ }
2998
+ let modulePreviewHtml;
2999
+ try {
3000
+ modulePreviewHtml = await signedGet(
3001
+ authedPortalId,
3002
+ cosRenderingUrl,
3003
+ {
3004
+ ["content-type"]: "application/x-www-form-urlencoded",
3005
+ ["Accept"]: "text/html",
3006
+ referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
3007
+ cookie: cookieValue,
3008
+ "User-Agent": "HubSpot CMS Dev Server"
3009
+ },
3010
+ gates
3011
+ );
3012
+ } finally {
3013
+ if (needsDomainOverride) {
3014
+ if (previousHubApiDomainOverride) {
3015
+ process.env.HUBAPI_DOMAIN_OVERRIDE = previousHubApiDomainOverride;
3016
+ } else {
3017
+ delete process.env.HUBAPI_DOMAIN_OVERRIDE;
3018
+ }
2948
3019
  }
2949
- })).data;
2950
- if (currentHubApiDomainOverride) {
2951
- process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2952
- } else {
2953
- delete process.env.HUBAPI_DOMAIN_OVERRIDE;
2954
3020
  }
2955
3021
  const dom = new JSDOM(modulePreviewHtml);
2956
3022
  const modulePreviewContent = dom.window.document.querySelector(
@@ -3193,7 +3259,8 @@ var partialRouteHandler = async (request, response) => {
3193
3259
  remoteModule.path,
3194
3260
  authedPortalId,
3195
3261
  authedEnv,
3196
- request.get("COOKIE")
3262
+ request.get("COOKIE"),
3263
+ jsRenderingGates
3197
3264
  ).then((result) => ({
3198
3265
  remoteModule,
3199
3266
  result
@@ -3727,18 +3794,18 @@ async function fetchPreviewTemplates(accountId, previewToken, limit = 250) {
3727
3794
  url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}&limit=${limit}`
3728
3795
  })).data;
3729
3796
  }
3730
- async function fetchModuleByPath(accountId, path17) {
3797
+ async function fetchModuleByPath(accountId, path18) {
3731
3798
  return (await hsCliHttp8.get(accountId, {
3732
- url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path17}?portalId=${accountId}`
3799
+ url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path18}?portalId=${accountId}`
3733
3800
  })).data;
3734
3801
  }
3735
- async function fetchTemplateByPath(accountId, path17) {
3802
+ async function fetchTemplateByPath(accountId, path18) {
3736
3803
  return (await hsCliHttp8.get(accountId, {
3737
- url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path17}?portalId=${accountId}`
3804
+ url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path18}?portalId=${accountId}`
3738
3805
  })).data;
3739
3806
  }
3740
- async function fetchModulePageDependencies(accountId, path17) {
3741
- const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path17}`;
3807
+ async function fetchModulePageDependencies(accountId, path18) {
3808
+ const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path18}`;
3742
3809
  return (await hsCliHttp8.get(accountId, { url: url3 })).data;
3743
3810
  }
3744
3811
 
@@ -4080,21 +4147,27 @@ ${e.stack}`);
4080
4147
  var modulePreviewRouteHandler_default = modulePreviewRouteHandler;
4081
4148
 
4082
4149
  // src/routes/hublModuleRouteHandler.ts
4083
- import { http as hsCliHttp9 } from "@hubspot/local-dev-lib/http";
4084
4150
  var hublModuleRouteHandler = async (request, response) => {
4085
4151
  sendTrackingRequest("view-hubl-module-route");
4086
- const { authedPortalId, localPreviewToken } = request.app.locals;
4152
+ const { authedPortalId, localPreviewToken, projectName, jsRenderingGates } = request.app.locals;
4087
4153
  const { modulePath } = request.params;
4088
4154
  if (!modulePath) {
4089
4155
  response.status(200).set({ "Content-Type": "text/html" }).end(buildModuleIndex());
4090
4156
  return;
4091
4157
  }
4092
- const calculatedPath = `@preview/${localPreviewToken}/@projects/${modulePath}.module`;
4158
+ const projectPrefix = projectName ? "@projects/" : "";
4159
+ const calculatedPath = `@preview/${localPreviewToken}/${projectPrefix}${modulePath}.module`;
4093
4160
  let customWidgetInfo;
4094
4161
  try {
4095
4162
  customWidgetInfo = await fetchModuleByPath(authedPortalId, calculatedPath);
4096
4163
  } catch (err) {
4097
- console.log(`Failed to fetch module data for ${calculatedPath}`);
4164
+ console.error(`Failed to fetch module data for ${calculatedPath}: ${err}`);
4165
+ response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex(err));
4166
+ return;
4167
+ }
4168
+ if (!customWidgetInfo || !("moduleId" in customWidgetInfo)) {
4169
+ response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex(null));
4170
+ return;
4098
4171
  }
4099
4172
  const params = {
4100
4173
  module_id: customWidgetInfo.moduleId,
@@ -4102,13 +4175,9 @@ var hublModuleRouteHandler = async (request, response) => {
4102
4175
  updated: Date.now(),
4103
4176
  ...request.query
4104
4177
  };
4105
- const previewUrl = new URL(getPreviewUrl(request, params));
4178
+ const previewUrl = getPreviewUrl(request, params);
4106
4179
  try {
4107
- const result = (await hsCliHttp9.get(authedPortalId, {
4108
- baseURL: previewUrl.origin,
4109
- url: previewUrl.pathname,
4110
- params
4111
- })).data;
4180
+ const result = await signedGet(authedPortalId, previewUrl, {}, jsRenderingGates);
4112
4181
  const html = addRefreshScript(result);
4113
4182
  response.status(200).set({ "Content-Type": "text/html" }).end(html);
4114
4183
  } catch (err) {
@@ -4130,7 +4199,6 @@ var buildModuleIndex = () => buildHTMLResponse(`
4130
4199
  `);
4131
4200
 
4132
4201
  // src/routes/hublTemplateRouteHandler.ts
4133
- import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
4134
4202
  import { buildStaticEnvConfig as buildStaticEnvConfig5 } from "@hubspot/cms-components";
4135
4203
  import { getConfigAccountEnvironment } from "@hubspot/local-dev-lib/config";
4136
4204
  var HUBSPOT_PREVIEW_BASE_TAG_REGEX = /<base\s+[^>]*href=["'][^"']*(?:hubspotpreview(?:qa)?)[^"']*["'][^>]*>/i;
@@ -4181,14 +4249,15 @@ var templateRouteHandler = async (request, response) => {
4181
4249
  hsCacheBuster: Date.now().toString(),
4182
4250
  ...request.query
4183
4251
  };
4184
- const previewUrl = new URL(getPreviewUrl(request, params));
4252
+ const previewUrl = getPreviewUrl(request, params);
4185
4253
  const fullOriginalUrl = `${request.protocol}://${request.get("host")}${request.originalUrl}`;
4186
4254
  try {
4187
- const result = (await hsCliHttp10.get(authedPortalId, {
4188
- baseURL: previewUrl.origin,
4189
- url: previewUrl.pathname,
4190
- params
4191
- })).data;
4255
+ const result = await signedGet(
4256
+ authedPortalId,
4257
+ previewUrl,
4258
+ {},
4259
+ jsRenderingGates
4260
+ );
4192
4261
  const pageHtml = addRefreshScript(result);
4193
4262
  const finalHtml = pageHtml.replace(
4194
4263
  HUBSPOT_PREVIEW_BASE_TAG_REGEX,
@@ -4207,6 +4276,7 @@ var templateRouteHandler = async (request, response) => {
4207
4276
  false
4208
4277
  );
4209
4278
  } catch (err) {
4279
+ console.error("Template route error:", err);
4210
4280
  response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex2());
4211
4281
  }
4212
4282
  };
@@ -4241,15 +4311,15 @@ function getOpenCommand() {
4241
4311
  }
4242
4312
  }
4243
4313
  async function handleGetModulePages(req, res, next) {
4244
- const { path: path17, portalId } = req.query;
4245
- if (!path17 || !portalId) {
4314
+ const { path: path18, portalId } = req.query;
4315
+ if (!path18 || !portalId) {
4246
4316
  return res.status(400).json({ error: "Missing required parameters" });
4247
4317
  }
4248
4318
  try {
4249
4319
  sendTrackingRequest("handle-module-dependencies");
4250
4320
  const data = await fetchModulePageDependencies(
4251
4321
  Number(portalId),
4252
- path17
4322
+ path18
4253
4323
  );
4254
4324
  res.json(data);
4255
4325
  } catch (err) {
@@ -4257,14 +4327,14 @@ async function handleGetModulePages(req, res, next) {
4257
4327
  }
4258
4328
  }
4259
4329
  function handleOpenFile(req, res, next) {
4260
- const { path: path17 } = req.query;
4261
- if (!path17) {
4330
+ const { path: path18 } = req.query;
4331
+ if (!path18) {
4262
4332
  return res.status(400).json({ error: "Missing required parameters" });
4263
4333
  }
4264
4334
  try {
4265
4335
  sendTrackingRequest("handle-open-file");
4266
4336
  const command = getOpenCommand();
4267
- spawn(command, [path17], { detached: true }).unref();
4337
+ spawn(command, [path18], { detached: true }).unref();
4268
4338
  res.sendStatus(200);
4269
4339
  } catch (err) {
4270
4340
  next(err);
@@ -4288,10 +4358,10 @@ import path11 from "path";
4288
4358
  import { normalizePath as normalizePath9 } from "vite";
4289
4359
 
4290
4360
  // src/api/project.ts
4291
- import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
4361
+ import { http as hsCliHttp9 } from "@hubspot/local-dev-lib/http";
4292
4362
  var DEVELOPER_PROJECTS_API_PATH = "/developer/projects/v1";
4293
4363
  async function fetchProjectByName(accountId, projectName) {
4294
- return (await hsCliHttp11.get(accountId, {
4364
+ return (await hsCliHttp9.get(accountId, {
4295
4365
  url: `${DEVELOPER_PROJECTS_API_PATH}/by-name/${projectName}`
4296
4366
  })).data;
4297
4367
  }
@@ -4497,6 +4567,7 @@ var createDevServerRoutes = async (viteServer, appLocals, storybookPort) => {
4497
4567
  debug(`${method}:${hostname}${url3}`);
4498
4568
  next();
4499
4569
  });
4570
+ devServerApp.use(cors());
4500
4571
  if (storybookPort) {
4501
4572
  devServerApp.use(
4502
4573
  createProxyMiddleware2(
@@ -4556,7 +4627,7 @@ import express from "express";
4556
4627
  // src/shadowDevServer/createShadowDevServerRoutes.ts
4557
4628
  import { Router as Router3 } from "express";
4558
4629
  import { getConfigAccountIfExists as getConfigAccountIfExists5 } from "@hubspot/local-dev-lib/config";
4559
- import cors from "cors";
4630
+ import cors2 from "cors";
4560
4631
  function getShadowDevServerCheckHandler(devServerPort, themePath) {
4561
4632
  return async function shadowDevServerCheckHandler(request, response) {
4562
4633
  const { query } = request;
@@ -4615,7 +4686,7 @@ async function createShadowDevServerRoutes(devServerPort, themePath) {
4615
4686
  const shadowDevServerRoutes = Router3();
4616
4687
  shadowDevServerRoutes.get(
4617
4688
  "/check-if-local-dev-server",
4618
- cors(),
4689
+ cors2(),
4619
4690
  getShadowDevServerCheckHandler(devServerPort, themePath)
4620
4691
  );
4621
4692
  return shadowDevServerRoutes;
@@ -4785,6 +4856,47 @@ async function getJsRenderingGates(portalId, env2, personalAccessKey) {
4785
4856
  return mergedGates;
4786
4857
  }
4787
4858
 
4859
+ // src/lib/hsmetaUtils.ts
4860
+ import path14 from "path";
4861
+ import fs5 from "fs";
4862
+ var HSMETA_FILENAMES = [
4863
+ "theme-hsmeta.json",
4864
+ "cms-assets-hsmeta.json"
4865
+ ];
4866
+ function getSubdirectories(dirPath) {
4867
+ try {
4868
+ return fs5.readdirSync(dirPath, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
4869
+ } catch {
4870
+ return [];
4871
+ }
4872
+ }
4873
+ function hsmetaCandidatePaths(srcPath) {
4874
+ const subdirs = getSubdirectories(srcPath);
4875
+ return subdirs.flatMap(
4876
+ (subdir) => HSMETA_FILENAMES.map((filename) => path14.join(srcPath, subdir, filename))
4877
+ );
4878
+ }
4879
+ function tryParseUid(hsmetaPath) {
4880
+ try {
4881
+ const hsmeta = JSON.parse(fs5.readFileSync(hsmetaPath, "utf8"));
4882
+ return hsmeta.uid ?? null;
4883
+ } catch (parseErr) {
4884
+ console.warn(`Could not parse ${hsmetaPath}:`, parseErr.message);
4885
+ return null;
4886
+ }
4887
+ }
4888
+ function findHsmetaUid(projectDir, srcDir) {
4889
+ const srcPath = path14.join(projectDir, srcDir);
4890
+ for (const candidatePath of hsmetaCandidatePaths(srcPath)) {
4891
+ if (!fs5.existsSync(candidatePath))
4892
+ continue;
4893
+ const uid = tryParseUid(candidatePath);
4894
+ if (uid)
4895
+ return uid;
4896
+ }
4897
+ return null;
4898
+ }
4899
+
4788
4900
  // src/lib/cliUtils.ts
4789
4901
  import process2 from "process";
4790
4902
  import os from "os";
@@ -4909,7 +5021,7 @@ import { fetchSecrets } from "@hubspot/local-dev-lib/api/secrets";
4909
5021
  import { PERSONAL_ACCESS_KEY_AUTH_METHOD } from "@hubspot/local-dev-lib/constants/auth";
4910
5022
 
4911
5023
  // src/proxyPage/fetchDomains.ts
4912
- import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
5024
+ import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
4913
5025
 
4914
5026
  // src/lib/errors.ts
4915
5027
  var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
@@ -4967,7 +5079,7 @@ function handleSecretsError(error) {
4967
5079
  // src/proxyPage/fetchDomains.ts
4968
5080
  async function fetchDomains(portalId) {
4969
5081
  try {
4970
- const result = (await hsCliHttp12.get(portalId, {
5082
+ const result = (await hsCliHttp10.get(portalId, {
4971
5083
  url: `/cms/v3/domains`,
4972
5084
  params: { portalId },
4973
5085
  responseType: "json"
@@ -4990,24 +5102,24 @@ async function fetchWebsiteDomainNames(portalId) {
4990
5102
  }
4991
5103
 
4992
5104
  // src/lib/validateHSPlatform.ts
4993
- import path14 from "path";
4994
- import fs5 from "fs";
5105
+ import path15 from "path";
5106
+ import fs6 from "fs";
4995
5107
  import select from "@inquirer/select";
4996
- import { http as hsCliHttp13 } from "@hubspot/local-dev-lib/http";
5108
+ import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
4997
5109
  var HSPROJECT_JSON = "hsproject.json";
4998
5110
  function checkFileExists(filePath) {
4999
- return fs5.existsSync(filePath) && fs5.statSync(filePath).isFile();
5111
+ return fs6.existsSync(filePath) && fs6.statSync(filePath).isFile();
5000
5112
  }
5001
5113
  function findHSProjectJson(startPath) {
5002
5114
  let currentDir = startPath;
5003
5115
  let dirLevel = 0;
5004
5116
  const maxDirLevel = 4;
5005
- while (path14.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
5006
- const filePath = path14.join(currentDir, HSPROJECT_JSON);
5117
+ while (path15.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
5118
+ const filePath = path15.join(currentDir, HSPROJECT_JSON);
5007
5119
  if (checkFileExists(filePath)) {
5008
5120
  return filePath;
5009
5121
  }
5010
- currentDir = path14.dirname(currentDir);
5122
+ currentDir = path15.dirname(currentDir);
5011
5123
  dirLevel++;
5012
5124
  }
5013
5125
  console.log(
@@ -5022,12 +5134,12 @@ async function validateHSPlatform(projectConfigPath, portalId) {
5022
5134
  );
5023
5135
  return false;
5024
5136
  }
5025
- const hsProjectJSONContents = fs5.readFileSync(projectConfigPath, "utf8");
5137
+ const hsProjectJSONContents = fs6.readFileSync(projectConfigPath, "utf8");
5026
5138
  const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
5027
5139
  const { platformVersion } = hsProjectJSONData;
5028
5140
  let platformVersionResult;
5029
5141
  try {
5030
- platformVersionResult = (await hsCliHttp13.get(portalId, {
5142
+ platformVersionResult = (await hsCliHttp11.get(portalId, {
5031
5143
  url: `developer/projects/v1/platformVersion`,
5032
5144
  responseType: "json"
5033
5145
  })).data;
@@ -5050,7 +5162,7 @@ async function validateHSPlatform(projectConfigPath, portalId) {
5050
5162
  });
5051
5163
  hsProjectJSONData.platformVersion = answer;
5052
5164
  try {
5053
- fs5.writeFileSync(
5165
+ fs6.writeFileSync(
5054
5166
  projectConfigPath,
5055
5167
  JSON.stringify(hsProjectJSONData, void 0, 2),
5056
5168
  "utf8"
@@ -5067,7 +5179,7 @@ async function validateHSPlatform(projectConfigPath, portalId) {
5067
5179
  }
5068
5180
 
5069
5181
  // src/createDevServer.ts
5070
- import { http as hsCliHttp14 } from "@hubspot/local-dev-lib/http";
5182
+ import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
5071
5183
 
5072
5184
  // ../cms-js-internal/dist/buildFieldsTypes.js
5073
5185
  import { writeFileSync } from "fs";
@@ -5312,8 +5424,8 @@ function writeFieldsType(fields, fileName, typeName) {
5312
5424
  }
5313
5425
 
5314
5426
  // src/lib/watchFieldsUpdates.ts
5315
- import fs6 from "fs";
5316
- import path15 from "path";
5427
+ import fs7 from "fs";
5428
+ import path16 from "path";
5317
5429
  import readline from "readline";
5318
5430
  var lastSerializedFieldsCache = {};
5319
5431
  var formatAsTypeName = (str) => {
@@ -5323,20 +5435,20 @@ var formatAsTypeName = (str) => {
5323
5435
  };
5324
5436
  var isInModulesFolder = (filePath, projectRoot) => {
5325
5437
  const getEntryPathFromId = (id) => {
5326
- return id.startsWith(projectRoot) ? id.replace(`${projectRoot}${path15.sep}`, "") : "";
5438
+ return id.startsWith(projectRoot) ? id.replace(`${projectRoot}${path16.sep}`, "") : "";
5327
5439
  };
5328
- const currentModuleId = path15.normalize(filePath);
5440
+ const currentModuleId = path16.normalize(filePath);
5329
5441
  const moduleEntryPath = getEntryPathFromId(currentModuleId);
5330
- const subFolderTokens = moduleEntryPath.split(path15.sep);
5442
+ const subFolderTokens = moduleEntryPath.split(path16.sep);
5331
5443
  return {
5332
5444
  inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
5333
5445
  isRootModuleFile: subFolderTokens.length === 3
5334
5446
  };
5335
5447
  };
5336
5448
  var fileContainsAutoGenComment = async (filePath) => {
5337
- if (!fs6.existsSync(filePath))
5449
+ if (!fs7.existsSync(filePath))
5338
5450
  return true;
5339
- const stream2 = fs6.createReadStream(filePath);
5451
+ const stream2 = fs7.createReadStream(filePath);
5340
5452
  const reader = readline.createInterface({ input: stream2 });
5341
5453
  const firstLine = await new Promise(
5342
5454
  (resolve2) => reader.once("line", (line) => resolve2(line.trim()))
@@ -5354,10 +5466,10 @@ var getIndexFile = (filePath, projectRoot) => {
5354
5466
  return void 0;
5355
5467
  if (isRootModuleFile)
5356
5468
  return { indexFilePath: filePath, isRootModuleFile };
5357
- const dir = path15.dirname(filePath);
5358
- const files = fs6.readdirSync(dir);
5469
+ const dir = path16.dirname(filePath);
5470
+ const files = fs7.readdirSync(dir);
5359
5471
  const indexFileName = files.find((file) => file.startsWith("index."));
5360
- return indexFileName ? { indexFilePath: path15.join(dir, indexFileName), isRootModuleFile } : void 0;
5472
+ return indexFileName ? { indexFilePath: path16.join(dir, indexFileName), isRootModuleFile } : void 0;
5361
5473
  };
5362
5474
  var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
5363
5475
  let indexFile;
@@ -5381,7 +5493,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5381
5493
  if (!indexInfo)
5382
5494
  return;
5383
5495
  const { indexFilePath, isRootModuleFile } = indexInfo;
5384
- const indexFileName = path15.parse(indexFilePath).name;
5496
+ const indexFileName = path16.parse(indexFilePath).name;
5385
5497
  const isTypeFile = filePath.endsWith(".types.ts");
5386
5498
  if (isTypeFile)
5387
5499
  return;
@@ -5392,7 +5504,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5392
5504
  );
5393
5505
  if (fields) {
5394
5506
  const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
5395
- const typeFilePath = path15.join(path15.dirname(filePath), typeFileName);
5507
+ const typeFilePath = path16.join(path16.dirname(filePath), typeFileName);
5396
5508
  const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
5397
5509
  const serializedFields = JSON.stringify(fields);
5398
5510
  if (lastSerializedFields === serializedFields)
@@ -5400,7 +5512,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5400
5512
  const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
5401
5513
  if (!hasAutoGenComment)
5402
5514
  return;
5403
- const moduleFolderName = path15.basename(path15.dirname(filePath));
5515
+ const moduleFolderName = path16.basename(path16.dirname(filePath));
5404
5516
  const outputTypeName = formatAsTypeName(moduleFolderName);
5405
5517
  const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
5406
5518
  if (didSucceed) {
@@ -5416,7 +5528,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5416
5528
  var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
5417
5529
  const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
5418
5530
  moduleSubpaths.forEach((modulePath) => {
5419
- const resolvedPath = path15.resolve(projectRoot, modulePath);
5531
+ const resolvedPath = path16.resolve(projectRoot, modulePath);
5420
5532
  maybeUpdateFields(resolvedPath, viteServer, projectRoot);
5421
5533
  });
5422
5534
  const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
@@ -5447,27 +5559,13 @@ function getWebRootProjectComponentFolder(absoluteWebRoot, projectConfigPath) {
5447
5559
  return themeFolderName;
5448
5560
  }
5449
5561
  try {
5450
- const projectDir = path16.dirname(projectConfigPath);
5451
- const configContent = fs7.readFileSync(projectConfigPath, "utf8");
5562
+ const projectDir = path17.dirname(projectConfigPath);
5563
+ const configContent = fs8.readFileSync(projectConfigPath, "utf8");
5452
5564
  const projectConfig = JSON.parse(configContent);
5453
- const isNewStructure = hasNewDirectoryStructure(
5454
- projectConfig.platformVersion
5455
- );
5456
- if (isNewStructure) {
5565
+ if (hasNewDirectoryStructure(projectConfig.platformVersion)) {
5457
5566
  const srcDir = projectConfig.srcDir || "src";
5458
- const hsmetaPath = path16.join(
5459
- projectDir,
5460
- srcDir,
5461
- "theme",
5462
- "theme-hsmeta.json"
5463
- );
5464
- if (fs7.existsSync(hsmetaPath)) {
5465
- const hsmetaContent = fs7.readFileSync(hsmetaPath, "utf8");
5466
- const hsmeta = JSON.parse(hsmetaContent);
5467
- if (hsmeta.uid) {
5468
- return hsmeta.uid;
5469
- }
5470
- }
5567
+ const uid = findHsmetaUid(projectDir, srcDir);
5568
+ return uid ?? projectConfig.name;
5471
5569
  }
5472
5570
  } catch (e) {
5473
5571
  console.warn(
@@ -5500,7 +5598,7 @@ async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, h
5500
5598
  `Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration.`
5501
5599
  );
5502
5600
  }
5503
- const cmsAssetConfig = getCMSAssetConfig(webRoot);
5601
+ const cmsAssetConfig = getCMSAssetConfigIfExists(webRoot);
5504
5602
  secretNamesFromConfig = getSecretNamesFromConfig(cmsAssetConfig);
5505
5603
  const { isValid } = validateConfig();
5506
5604
  if (isValid) {
@@ -5588,14 +5686,14 @@ Local proxy functionality and module preview routes will not work without settin
5588
5686
  }
5589
5687
  let authedHublet;
5590
5688
  try {
5591
- const accountInformation = (await hsCliHttp14.get(authedPortalId, {
5689
+ const accountInformation = (await hsCliHttp12.get(authedPortalId, {
5592
5690
  url: "/account-info/v3/details"
5593
5691
  })).data;
5594
5692
  authedHublet = accountInformation.dataHostingLocation;
5595
5693
  } catch (e) {
5596
5694
  authedHublet = "na1";
5597
5695
  }
5598
- const absoluteWebRoot = normalizePath10(path16.resolve(process.cwd(), webRoot));
5696
+ const absoluteWebRoot = normalizePath10(path17.resolve(process.cwd(), webRoot));
5599
5697
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
5600
5698
  const webRootProjectComponentFolder = getWebRootProjectComponentFolder(
5601
5699
  absoluteWebRoot,
@@ -5624,7 +5722,7 @@ Local proxy functionality and module preview routes will not work without settin
5624
5722
  secretNames
5625
5723
  );
5626
5724
  if (fieldGenEnabledOption) {
5627
- const normalizedAbsoluteWebRoot = path16.normalize(absoluteWebRoot);
5725
+ const normalizedAbsoluteWebRoot = path17.normalize(absoluteWebRoot);
5628
5726
  startFieldsTypeGenWatcher(viteServer, normalizedAbsoluteWebRoot);
5629
5727
  }
5630
5728
  const viteHTTPSConfig = viteServer.config.server.https;
@@ -5649,10 +5747,10 @@ Local proxy functionality and module preview routes will not work without settin
5649
5747
  expressServer.locals.localPreviewToken = _localPreviewToken;
5650
5748
  expressServer.locals.sslEnabled = sslEnabledOption;
5651
5749
  expressServer.use(bodyParser.json());
5652
- const __dirname = path16.dirname(url2.fileURLToPath(new URL(import.meta.url)));
5653
- let appWebRoot = normalizePath10(path16.resolve(__dirname, "../app"));
5750
+ const __dirname = path17.dirname(url2.fileURLToPath(new URL(import.meta.url)));
5751
+ let appWebRoot = normalizePath10(path17.resolve(__dirname, "../app"));
5654
5752
  if (true) {
5655
- appWebRoot = path16.join(__dirname, "app");
5753
+ appWebRoot = path17.join(__dirname, "app");
5656
5754
  }
5657
5755
  const appViteServer = await createAppServer_default(
5658
5756
  appWebRoot,
@@ -5722,17 +5820,17 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
5722
5820
  `;
5723
5821
  console.log(startMessage);
5724
5822
  if (storybook) {
5725
- const packageRoot = path16.dirname(url2.fileURLToPath(import.meta.url));
5726
- const configPath = path16.resolve(packageRoot, "./storybook-main");
5823
+ const packageRoot = path17.dirname(url2.fileURLToPath(import.meta.url));
5824
+ const configPath = path17.resolve(packageRoot, "./storybook-main");
5727
5825
  sendTrackingRequest("start-storybook");
5728
5826
  let storybookBin;
5729
5827
  try {
5730
5828
  const sbPackagePath = await import.meta.resolve("storybook/package.json");
5731
- const sbPackageDir = path16.dirname(url2.fileURLToPath(sbPackagePath));
5829
+ const sbPackageDir = path17.dirname(url2.fileURLToPath(sbPackagePath));
5732
5830
  const packageJson = JSON.parse(
5733
- fs7.readFileSync(path16.join(sbPackageDir, "package.json"), "utf-8")
5831
+ fs8.readFileSync(path17.join(sbPackageDir, "package.json"), "utf-8")
5734
5832
  );
5735
- storybookBin = path16.join(
5833
+ storybookBin = path17.join(
5736
5834
  sbPackageDir,
5737
5835
  packageJson.bin.storybook || packageJson.bin
5738
5836
  );
@@ -5769,7 +5867,7 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
5769
5867
  portalId: authedPortalId.toString(),
5770
5868
  hsEnv: authedEnv,
5771
5869
  hublet: authedHublet,
5772
- WEB_ROOT: path16.join(webRoot, "components")
5870
+ WEB_ROOT: path17.join(webRoot, "components")
5773
5871
  },
5774
5872
  stdio: "inherit"
5775
5873
  }