@hubspot/cms-dev-server 0.14.5 → 0.14.7

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
@@ -77,7 +77,7 @@ function getDevServerCommandLineOptions(argv) {
77
77
  }
78
78
 
79
79
  // src/createDevServer.ts
80
- import path9 from "path";
80
+ import path8 from "path";
81
81
  import url2 from "url";
82
82
  import express2 from "express";
83
83
  import http3 from "http";
@@ -126,16 +126,10 @@ function packagePath(metaUrl, projectPath) {
126
126
  );
127
127
  }
128
128
 
129
- // ../cms-js-internal/dist/index.js
130
- import * as dotProp from "dot-prop";
129
+ // ../cms-js-internal/dist/basicUtils.js
131
130
  import path2 from "path";
132
- import * as jsxRuntime from "react/jsx-runtime";
133
- import stream from "stream";
134
- import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
135
- import * as cmsComponents from "@hubspot/cms-components";
136
- import { ServerRenderContext } from "@hubspot/cms-components";
137
131
  import { createHash } from "crypto";
138
- import { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
132
+ import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
139
133
  import { join } from "path/posix";
140
134
  var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
141
135
  var ENTRY_POINTS_PATH = "components/partials/";
@@ -163,6 +157,258 @@ function jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent =
163
157
  ${indentString}`
164
158
  );
165
159
  }
160
+ var viteRoot;
161
+ var viteCommand;
162
+ function resolveIslandPlugin(islandsSet) {
163
+ return {
164
+ enforce: "pre",
165
+ name: "resolve-islands",
166
+ configResolved(config) {
167
+ viteRoot = config.root;
168
+ viteCommand = config.command;
169
+ },
170
+ load(id) {
171
+ if (id.endsWith("?island") || id.endsWith("?client")) {
172
+ const [idWithNoParam] = id.split("?");
173
+ const islandModuleImportPath = `${idWithNoParam}?client-entry`;
174
+ const componentExtension = path2.extname(idWithNoParam);
175
+ const componentFilenameWithNoExtension = path2.basename(
176
+ idWithNoParam,
177
+ componentExtension
178
+ );
179
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
180
+ const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
181
+ if (islandsSet) {
182
+ islandsSet.add(moduleId);
183
+ }
184
+ return `
185
+ const moduleId = '${moduleId}';
186
+
187
+ const lazyComponent = () => import('${islandModuleImportPath}');
188
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
189
+ lazyComponent.moduleId = moduleId;
190
+
191
+ export default lazyComponent;
192
+ `;
193
+ }
194
+ return null;
195
+ }
196
+ };
197
+ }
198
+ var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport * as cmsComponents from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nconst buildIslandIdentifierPrefix =\n cmsComponents.buildIslandIdentifierPrefix || (id => id);\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: React.ComponentType<any>\n) {\n const {\n island,\n rootElement,\n postHydration,\n pageUrl,\n islands,\n basePath,\n WrapperModule,\n } = renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: buildIslandIdentifierPrefix(renderableIsland.island.id),\n };\n\n let innerComponent = <Component islandId={island.id} {...island.props} />;\n if (WrapperModule) {\n innerComponent = <WrapperModule>{innerComponent}</WrapperModule>;\n }\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n basePath={basePath}\n >\n {innerComponent}\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
199
+ var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
200
+ function clientIslandEntryPlugin() {
201
+ return {
202
+ enforce: "pre",
203
+ name: "client-island-entry-plugin",
204
+ resolveId(id) {
205
+ if (id === virtualClientRenderIslandModuleId) {
206
+ return virtualClientRenderIslandModuleId;
207
+ }
208
+ return null;
209
+ },
210
+ load(id) {
211
+ if (id.endsWith("?client-entry")) {
212
+ const [idWithNoParam] = id.split("?");
213
+ return `
214
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
215
+ import Component from '${idWithNoParam}';
216
+
217
+ export function render(island) {
218
+ return clientRenderIsland(island, Component)
219
+ }
220
+
221
+ export default Component;
222
+ `;
223
+ }
224
+ if (id === virtualClientRenderIslandModuleId) {
225
+ return clientRenderIsland;
226
+ }
227
+ return null;
228
+ }
229
+ };
230
+ }
231
+ var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
232
+ if (!messagesForBrowser) {
233
+ return "";
234
+ }
235
+ const consoleLines = [];
236
+ for (const message of messagesForBrowser) {
237
+ let funcString = "console.log";
238
+ if (message.level === "error") {
239
+ funcString = "console.error";
240
+ }
241
+ if (message.level === "warn") {
242
+ funcString = "console.warn";
243
+ }
244
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
245
+ consoleLines.push(` ${funcString}(${argString});`);
246
+ }
247
+ let groupStart = "";
248
+ let groupEnd = "";
249
+ if (groupLabel !== void 0 && groupLabel !== null) {
250
+ groupStart = `
251
+ console.group(${JSON.stringify(groupLabel)});`;
252
+ groupEnd = ` console.groupEnd()
253
+ `;
254
+ }
255
+ return `<script>${groupStart}
256
+ ${consoleLines.join("\n")}
257
+ ${groupEnd}</script>
258
+ `;
259
+ };
260
+ var getComponentExtension = (componentPath) => {
261
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
262
+ (ext) => componentPath.endsWith(ext)
263
+ );
264
+ if (filteredExtensions.length === 1) {
265
+ return filteredExtensions[0];
266
+ }
267
+ return void 0;
268
+ };
269
+ var hasComponentExtension = (componentPath) => {
270
+ return !!getComponentExtension(componentPath);
271
+ };
272
+ var isStorybookStory = (componentPath) => {
273
+ return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
274
+ };
275
+ var removeComponentExtension = (componentPath) => {
276
+ const ext = getComponentExtension(componentPath);
277
+ if (ext == null) {
278
+ return componentPath;
279
+ }
280
+ return componentPath.slice(0, -1 * ext.length);
281
+ };
282
+ function getEntryPointHash(entryPoint) {
283
+ return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
284
+ }
285
+ function getEntryPointHashWithIndexSuffix(entryPoint, index) {
286
+ const renderIndexSuffix = index != null ? `i${index}` : "";
287
+ return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
288
+ }
289
+ function getCMSAssetConfig(webRoot2) {
290
+ const cmsAssetsPath = path2.join(webRoot2, "cms-assets.json");
291
+ return JSON.parse(fs.readFileSync(cmsAssetsPath).toString());
292
+ }
293
+ var ENABLED_FEATURES_GATE_MAP = {
294
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
295
+ "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin"
296
+ };
297
+ function isUngatedFor(gates, gate) {
298
+ return gates.includes(gate);
299
+ }
300
+ var findAllComponentsIn = (webRoot2, componentsFolder) => {
301
+ const fullComponentsFolderPath = join(webRoot2, componentsFolder);
302
+ const componentsByName = {};
303
+ if (!existsSync(fullComponentsFolderPath)) {
304
+ return componentsByName;
305
+ }
306
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
307
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
308
+ const subdirPath = join(componentsFolder, fileOrFolderName);
309
+ const isDirectory = lstatSync(fullPath).isDirectory();
310
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
311
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
312
+ componentsByName[subdirPathNoExtension] = subdirPath;
313
+ } else if (isDirectory) {
314
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
315
+ const potentialIndexModule = join(
316
+ subdirPath,
317
+ `index${potentialExtension}`
318
+ );
319
+ const fullPotentialPath = join(
320
+ fullPath,
321
+ `index${potentialExtension}`
322
+ );
323
+ if (existsSync(fullPotentialPath)) {
324
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
325
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
326
+ break;
327
+ }
328
+ }
329
+ }
330
+ });
331
+ return componentsByName;
332
+ };
333
+ function findAllModulesInRoot(webRoot2) {
334
+ const allModuleComponents = findAllComponentsIn(
335
+ webRoot2,
336
+ "./components/modules"
337
+ );
338
+ const moduleNames = Object.keys(allModuleComponents).map(
339
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
340
+ );
341
+ const moduleSubpaths = Object.keys(allModuleComponents);
342
+ return { moduleNames, moduleSubpaths };
343
+ }
344
+ function findAllPartialsInRoot(webRoot2) {
345
+ const allPartialComponents = findAllComponentsIn(
346
+ webRoot2,
347
+ "./components/partials"
348
+ );
349
+ const partialNames = Object.keys(allPartialComponents).map(
350
+ (partialSubpath) => partialSubpath.replace("components/partials/", "").replace("/index", "")
351
+ );
352
+ const partialSubpaths = Object.keys(allPartialComponents);
353
+ return { partialNames, partialSubpaths };
354
+ }
355
+ function namespaceModulePropsShape(props) {
356
+ const {
357
+ dataQueryResult,
358
+ hublParameters,
359
+ fieldValues: passedFieldValues,
360
+ hublData,
361
+ experimentalHublData,
362
+ moduleName,
363
+ supplementalFieldValues
364
+ } = props;
365
+ const oldPropsShape = { ...props };
366
+ if (oldPropsShape.dataQueryResult) {
367
+ delete oldPropsShape.dataQueryResult;
368
+ }
369
+ if (oldPropsShape.hublParameters) {
370
+ delete oldPropsShape.hublParameters;
371
+ }
372
+ const fieldValues = passedFieldValues || oldPropsShape;
373
+ return {
374
+ ...fieldValues,
375
+ dataQueryResult,
376
+ fieldValues,
377
+ hublParameters,
378
+ hublData,
379
+ experimentalHublData,
380
+ moduleName,
381
+ supplementalFieldValues
382
+ };
383
+ }
384
+ function setIn(object, nestedKeysArray, value) {
385
+ let curr = object;
386
+ const finalKey = nestedKeysArray.pop();
387
+ for (let index = 0; index < nestedKeysArray.length; index++) {
388
+ const currentKey = nestedKeysArray[index];
389
+ const nextKey = nestedKeysArray[index + 1];
390
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
391
+ if (curr[currentKey] === void 0) {
392
+ curr[currentKey] = [];
393
+ }
394
+ }
395
+ if (curr[currentKey] === void 0) {
396
+ curr[currentKey] = {};
397
+ }
398
+ curr = curr[currentKey];
399
+ }
400
+ if (value !== void 0) {
401
+ curr[finalKey] = value;
402
+ }
403
+ }
404
+
405
+ // ../cms-js-internal/dist/index.js
406
+ import * as dotProp from "dot-prop";
407
+ import * as jsxRuntime from "react/jsx-runtime";
408
+ import stream from "stream";
409
+ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
410
+ import * as cmsComponents from "@hubspot/cms-components";
411
+ import { ServerRenderContext } from "@hubspot/cms-components";
166
412
  var { setProperty, getProperty, hasProperty } = dotProp;
167
413
  var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
168
414
  const islandsArrayToSerialize = tweakedIslandsArray.map(
@@ -298,67 +544,29 @@ function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
298
544
  };
299
545
  perServerRequestDataWithUrls.set(id, reducerWithUrl);
300
546
  }
301
- });
302
- return perServerRequestDataWithUrls;
303
- }
304
- var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
305
- const islands = getIslandUrls(roots, viteDevServer);
306
- const perServerRequestDataWithUrls = getPerServerRequestUrls(
307
- perServerRequestData,
308
- viteDevServer
309
- );
310
- return `${" ".repeat(
311
- indent
312
- )}window.__islands = ${serializeIslandDataForInlineScript(
313
- islands,
314
- perServerRequestData,
315
- indent,
316
- prettyPrint
317
- )}${writeSharedStateToJsGlobal(
318
- islands,
319
- perServerRequestDataWithUrls,
320
- indent,
321
- prettyPrint
322
- )}`;
323
- };
324
- var viteRoot;
325
- var viteCommand;
326
- function resolveIslandPlugin(islandsSet) {
327
- return {
328
- enforce: "pre",
329
- name: "resolve-islands",
330
- configResolved(config) {
331
- viteRoot = config.root;
332
- viteCommand = config.command;
333
- },
334
- load(id) {
335
- if (id.endsWith("?island") || id.endsWith("?client")) {
336
- const [idWithNoParam] = id.split("?");
337
- const islandModuleImportPath = `${idWithNoParam}?client-entry`;
338
- const componentExtension = path2.extname(idWithNoParam);
339
- const componentFilenameWithNoExtension = path2.basename(
340
- idWithNoParam,
341
- componentExtension
342
- );
343
- const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
344
- const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
345
- if (islandsSet) {
346
- islandsSet.add(moduleId);
347
- }
348
- return `
349
- const moduleId = '${moduleId}';
350
-
351
- const lazyComponent = () => import('${islandModuleImportPath}');
352
- lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
353
- lazyComponent.moduleId = moduleId;
354
-
355
- export default lazyComponent;
356
- `;
357
- }
358
- return null;
359
- }
360
- };
547
+ });
548
+ return perServerRequestDataWithUrls;
361
549
  }
550
+ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
551
+ const islands = getIslandUrls(roots, viteDevServer);
552
+ const perServerRequestDataWithUrls = getPerServerRequestUrls(
553
+ perServerRequestData,
554
+ viteDevServer
555
+ );
556
+ return `${" ".repeat(
557
+ indent
558
+ )}window.__islands = ${serializeIslandDataForInlineScript(
559
+ islands,
560
+ perServerRequestData,
561
+ indent,
562
+ prettyPrint
563
+ )}${writeSharedStateToJsGlobal(
564
+ islands,
565
+ perServerRequestDataWithUrls,
566
+ indent,
567
+ prettyPrint
568
+ )}`;
569
+ };
362
570
  function noncePlaceholderPlugin() {
363
571
  const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
364
572
  return {
@@ -381,39 +589,6 @@ function noncePlaceholderPlugin() {
381
589
  }
382
590
  };
383
591
  }
384
- var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport * as cmsComponents from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nconst buildIslandIdentifierPrefix =\n cmsComponents.buildIslandIdentifierPrefix || (id => id);\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: React.ComponentType<any>\n) {\n const {\n island,\n rootElement,\n postHydration,\n pageUrl,\n islands,\n basePath,\n WrapperModule,\n } = renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: buildIslandIdentifierPrefix(renderableIsland.island.id),\n };\n\n let innerComponent = <Component islandId={island.id} {...island.props} />;\n if (WrapperModule) {\n innerComponent = <WrapperModule>{innerComponent}</WrapperModule>;\n }\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n basePath={basePath}\n >\n {innerComponent}\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
385
- var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
386
- function clientIslandEntryPlugin() {
387
- return {
388
- enforce: "pre",
389
- name: "client-island-entry-plugin",
390
- resolveId(id) {
391
- if (id === virtualClientRenderIslandModuleId) {
392
- return virtualClientRenderIslandModuleId;
393
- }
394
- return null;
395
- },
396
- load(id) {
397
- if (id.endsWith("?client-entry")) {
398
- const [idWithNoParam] = id.split("?");
399
- return `
400
- import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
401
- import Component from '${idWithNoParam}';
402
-
403
- export function render(island) {
404
- return clientRenderIsland(island, Component)
405
- }
406
-
407
- export default Component;
408
- `;
409
- }
410
- if (id === virtualClientRenderIslandModuleId) {
411
- return clientRenderIsland;
412
- }
413
- return null;
414
- }
415
- };
416
- }
417
592
  var jsx2 = jsxRuntime.jsx;
418
593
  var promiseForNewWritableStream = () => {
419
594
  const chunks = [];
@@ -451,35 +626,6 @@ var renderStreamToPromise = async (reactElements, options) => {
451
626
  });
452
627
  return streamDonePromise;
453
628
  };
454
- var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
455
- if (!messagesForBrowser) {
456
- return "";
457
- }
458
- const consoleLines = [];
459
- for (const message of messagesForBrowser) {
460
- let funcString = "console.log";
461
- if (message.level === "error") {
462
- funcString = "console.error";
463
- }
464
- if (message.level === "warn") {
465
- funcString = "console.warn";
466
- }
467
- const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
468
- consoleLines.push(` ${funcString}(${argString});`);
469
- }
470
- let groupStart = "";
471
- let groupEnd = "";
472
- if (groupLabel !== void 0 && groupLabel !== null) {
473
- groupStart = `
474
- console.group(${JSON.stringify(groupLabel)});`;
475
- groupEnd = ` console.groupEnd()
476
- `;
477
- }
478
- return `<script>${groupStart}
479
- ${consoleLines.join("\n")}
480
- ${groupEnd}</script>
481
- `;
482
- };
483
629
  async function renderOnServer(elements, pageUrl, environmentConfig, entryPointBasePath, contextOptions, debugName, renderOptions) {
484
630
  const supplementalFieldValues = contextOptions ? contextOptions.supplementalFieldValues : void 0;
485
631
  const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
@@ -499,97 +645,6 @@ async function renderOnServer(elements, pageUrl, environmentConfig, entryPointBa
499
645
  }
500
646
  return { html, renderContext };
501
647
  }
502
- var getComponentExtension = (componentPath) => {
503
- const filteredExtensions = COMPONENT_EXTENSIONS.filter(
504
- (ext) => componentPath.endsWith(ext)
505
- );
506
- if (filteredExtensions.length === 1) {
507
- return filteredExtensions[0];
508
- }
509
- return void 0;
510
- };
511
- var hasComponentExtension = (componentPath) => {
512
- return !!getComponentExtension(componentPath);
513
- };
514
- var isStorybookStory = (componentPath) => {
515
- return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
516
- };
517
- var removeComponentExtension = (componentPath) => {
518
- const ext = getComponentExtension(componentPath);
519
- if (ext == null) {
520
- return componentPath;
521
- }
522
- return componentPath.slice(0, -1 * ext.length);
523
- };
524
- function getEntryPointHash(entryPoint) {
525
- return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
526
- }
527
- function getEntryPointHashWithIndexSuffix(entryPoint, index) {
528
- const renderIndexSuffix = index != null ? `i${index}` : "";
529
- return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
530
- }
531
- var ENABLED_FEATURES_GATE_MAP = {
532
- "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
533
- "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin"
534
- };
535
- function isUngatedFor(gates, gate) {
536
- return gates.includes(gate);
537
- }
538
- var findAllComponentsIn = (webRoot2, componentsFolder) => {
539
- const fullComponentsFolderPath = join(webRoot2, componentsFolder);
540
- const componentsByName = {};
541
- if (!existsSync(fullComponentsFolderPath)) {
542
- return componentsByName;
543
- }
544
- readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
545
- const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
546
- const subdirPath = join(componentsFolder, fileOrFolderName);
547
- const isDirectory = lstatSync(fullPath).isDirectory();
548
- if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
549
- const subdirPathNoExtension = removeComponentExtension(subdirPath);
550
- componentsByName[subdirPathNoExtension] = subdirPath;
551
- } else if (isDirectory) {
552
- for (const potentialExtension of COMPONENT_EXTENSIONS) {
553
- const potentialIndexModule = join(
554
- subdirPath,
555
- `index${potentialExtension}`
556
- );
557
- const fullPotentialPath = join(
558
- fullPath,
559
- `index${potentialExtension}`
560
- );
561
- if (existsSync(fullPotentialPath)) {
562
- const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
563
- componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
564
- break;
565
- }
566
- }
567
- }
568
- });
569
- return componentsByName;
570
- };
571
- function findAllModulesInRoot(webRoot2) {
572
- const allModuleComponents = findAllComponentsIn(
573
- webRoot2,
574
- "./components/modules"
575
- );
576
- const moduleNames = Object.keys(allModuleComponents).map(
577
- (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
578
- );
579
- const moduleSubpaths = Object.keys(allModuleComponents);
580
- return { moduleNames, moduleSubpaths };
581
- }
582
- function findAllPartialsInRoot(webRoot2) {
583
- const allPartialComponents = findAllComponentsIn(
584
- webRoot2,
585
- "./components/partials"
586
- );
587
- const partialNames = Object.keys(allPartialComponents).map(
588
- (partialSubpath) => partialSubpath.replace("components/partials/", "").replace("/index", "")
589
- );
590
- const partialSubpaths = Object.keys(allPartialComponents);
591
- return { partialNames, partialSubpaths };
592
- }
593
648
  function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
594
649
  if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
595
650
  prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
@@ -632,55 +687,6 @@ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath
632
687
  </script>
633
688
  `;
634
689
  }
635
- function namespaceModulePropsShape(props) {
636
- const {
637
- dataQueryResult,
638
- hublParameters,
639
- fieldValues: passedFieldValues,
640
- hublData,
641
- experimentalHublData,
642
- moduleName,
643
- supplementalFieldValues
644
- } = props;
645
- const oldPropsShape = { ...props };
646
- if (oldPropsShape.dataQueryResult) {
647
- delete oldPropsShape.dataQueryResult;
648
- }
649
- if (oldPropsShape.hublParameters) {
650
- delete oldPropsShape.hublParameters;
651
- }
652
- const fieldValues = passedFieldValues || oldPropsShape;
653
- return {
654
- ...fieldValues,
655
- dataQueryResult,
656
- fieldValues,
657
- hublParameters,
658
- hublData,
659
- experimentalHublData,
660
- moduleName,
661
- supplementalFieldValues
662
- };
663
- }
664
- function setIn(object, nestedKeysArray, value) {
665
- let curr = object;
666
- const finalKey = nestedKeysArray.pop();
667
- for (let index = 0; index < nestedKeysArray.length; index++) {
668
- const currentKey = nestedKeysArray[index];
669
- const nextKey = nestedKeysArray[index + 1];
670
- if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
671
- if (curr[currentKey] === void 0) {
672
- curr[currentKey] = [];
673
- }
674
- }
675
- if (curr[currentKey] === void 0) {
676
- curr[currentKey] = {};
677
- }
678
- curr = curr[currentKey];
679
- }
680
- if (value !== void 0) {
681
- curr[finalKey] = value;
682
- }
683
- }
684
690
 
685
691
  // src/lib/moduleGraph.ts
686
692
  var findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
@@ -728,7 +734,7 @@ var getEntryPointBasePath = (componentPath) => {
728
734
  // src/lib/renderComponentWithCSS.ts
729
735
  async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl, entryPointBasePath, contextOptions, environmentConfig, renderOptions) {
730
736
  const internalSsrPath = packagePath(import.meta.url, "internalSsr");
731
- const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule(internalSsrPath);
737
+ const { renderComponentOnServer, collectCssInDev: collectCssInDev2 } = await viteServer.ssrLoadModule(internalSsrPath);
732
738
  const [, componentPathWithExtension] = getComponentPaths(
733
739
  viteServer,
734
740
  componentPath
@@ -745,7 +751,7 @@ async function renderComponentWithCSS(viteServer, componentPath, Component, prop
745
751
  contextOptions,
746
752
  renderOptions
747
753
  );
748
- const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
754
+ const cssNeeded = collectCssInDev2(componentPathWithExtension, viteServer);
749
755
  let inlineAssets = [];
750
756
  if (renderContext.inlineAssets && Array.isArray(renderContext.inlineAssets)) {
751
757
  inlineAssets = renderContext.inlineAssets.map(
@@ -1023,7 +1029,7 @@ function trackUsage(action) {
1023
1029
  eventName: EVENT_NAME,
1024
1030
  action,
1025
1031
  nodeVersion: getNodeVersionData(),
1026
- version: "0.14.5",
1032
+ version: "0.14.7",
1027
1033
  os: getPlatform()
1028
1034
  };
1029
1035
  const uri = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1619,7 +1625,7 @@ import { getAccountId as getAccountId2, getEnv } from "@hubspot/cli-lib/lib/conf
1619
1625
  import { get as hsGet3 } from "@hubspot/cli-lib/http.js";
1620
1626
 
1621
1627
  // src/lib/proxyHelpers.ts
1622
- import fs from "fs";
1628
+ import fs2 from "fs";
1623
1629
  import { resolve as resolve2 } from "path";
1624
1630
  var localJsRenderStartString = '<!-- proxy local render of "';
1625
1631
  var localJsRenderEndString = "end proxy local render -->";
@@ -1647,12 +1653,12 @@ var findLocalRenderPlaceholders = (body) => {
1647
1653
  );
1648
1654
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1649
1655
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1650
- const path10 = body.substring(
1656
+ const path9 = body.substring(
1651
1657
  startOffset + localJsRenderStartString.length,
1652
1658
  pathEndOffset
1653
1659
  );
1654
1660
  offsetSoFar = pathEndOffset + 1;
1655
- if (startOffset >= 0 && path10) {
1661
+ if (startOffset >= 0 && path9) {
1656
1662
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1657
1663
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1658
1664
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1672,7 +1678,7 @@ var findLocalRenderPlaceholders = (body) => {
1672
1678
  result.push({
1673
1679
  startOffset,
1674
1680
  endOffset: endOffset + localJsRenderEndString.length,
1675
- path: path10,
1681
+ path: path9,
1676
1682
  json
1677
1683
  });
1678
1684
  }
@@ -1692,7 +1698,7 @@ var findLocalRenderPlaceholders = (body) => {
1692
1698
  };
1693
1699
  var getHSProjectConfig = (hsProjectConfigPath) => {
1694
1700
  try {
1695
- return JSON.parse(fs.readFileSync(hsProjectConfigPath, "utf8"));
1701
+ return JSON.parse(fs2.readFileSync(hsProjectConfigPath, "utf8"));
1696
1702
  } catch (e) {
1697
1703
  console.warn(
1698
1704
  `Missing hsproject.json file (${resolve2(hsProjectConfigPath)}): `,
@@ -1781,9 +1787,9 @@ var customColors = [
1781
1787
  ];
1782
1788
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
1783
1789
  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;`;
1784
- var renderLocalError_default = (path10, error) => {
1790
+ var renderLocalError_default = (path9, error) => {
1785
1791
  const stackWithColorClasses = Converter.toHtml(error.stack);
1786
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path10}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1792
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path9}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1787
1793
  };
1788
1794
 
1789
1795
  // src/proxyPage/fetchPreviewInfo.ts
@@ -2391,7 +2397,7 @@ async function proxyPathPageRouteHandler(request2, response, next) {
2391
2397
  }
2392
2398
 
2393
2399
  // src/routes/proxyPathPageResourceRedirect.ts
2394
- import fetch2 from "node-fetch";
2400
+ import fetch from "node-fetch";
2395
2401
  var HCMS_PATH2 = "/_hcms/";
2396
2402
  var HS_FS_PATH2 = "/hs-fs/";
2397
2403
  var HUB_FS_PATH2 = "/hubfs/";
@@ -2421,15 +2427,14 @@ function proxyPathPageResourceRedirect(req, res, next) {
2421
2427
  return;
2422
2428
  }
2423
2429
  const urlToProxy = `https://${proxyPageUrl.host}${req.url}`;
2424
- fetch2(urlToProxy).then((response) => response.body.pipe(res)).catch((err) => console.log(err));
2430
+ fetch(urlToProxy).then((response) => response.body.pipe(res)).catch((err) => console.log(err));
2425
2431
  }
2426
2432
 
2427
2433
  // src/routes/modulePreviewRouteHandler.ts
2428
2434
  import { buildStaticEnvConfig as buildStaticEnvConfig4 } from "@hubspot/cms-components";
2429
2435
  import path6 from "path";
2430
2436
  import { normalizePath as normalizePath5 } from "vite";
2431
- import { getAccountId as getAccountId3 } from "@hubspot/cli-lib/lib/config.js";
2432
- import { get as hsGet4 } from "@hubspot/cli-lib/http.js";
2437
+ import fetch2 from "node-fetch";
2433
2438
  async function modulePreviewRouteHandler(request2, response) {
2434
2439
  sendTrackingRequest("view-module-preview-route");
2435
2440
  const {
@@ -2455,26 +2460,57 @@ async function modulePreviewRouteHandler(request2, response) {
2455
2460
  jsRenderingGates
2456
2461
  );
2457
2462
  const baseUrl = `https://api.hubspot${authedEnv === "qa" ? "qa" : ""}${authedHublet === "eu1" ? "-eu1" : ""}.com/api`;
2458
- const accountId = await getAccountId3(authedPortalId);
2459
2463
  let templatePreview;
2460
2464
  try {
2461
- const moduleFetchResult = await hsGet4(accountId, {
2462
- baseUrl,
2463
- uri: `/designmanager/v1/modules/by-path/@projects/${projectName}/${projectComponentPath}/components/modules/${moduleName}`,
2464
- query: {
2465
- portalId: authedPortalId
2466
- },
2467
- json: true,
2468
- useQuerystring: true
2469
- });
2465
+ let componentModule;
2466
+ let foundPath;
2467
+ if (!hasComponentExtension(modulePath)) {
2468
+ [componentModule, foundPath] = await lookForModuleInFolder2(
2469
+ modulePath,
2470
+ viteServer
2471
+ );
2472
+ }
2473
+ if (!componentModule) {
2474
+ componentModule = await viteServer.ssrLoadModule(modulePath);
2475
+ foundPath = componentModule ? modulePath : void 0;
2476
+ }
2477
+ if (!componentModule) {
2478
+ throw new Error(`Couldn't find module: ${modulePath}`);
2479
+ }
2480
+ const Component = componentModule.Component;
2481
+ const fields = componentModule.fields;
2482
+ const meta = componentModule.meta;
2483
+ const hublDataTemplate = componentModule.hublDataTemplate;
2484
+ if (!Component) {
2485
+ throw new Error(
2486
+ `Module does not have a named Component export: ${foundPath}`
2487
+ );
2488
+ } else if (!fields) {
2489
+ throw new Error(
2490
+ `Module does not have a named fields export: ${foundPath}`
2491
+ );
2492
+ } else if (!meta) {
2493
+ throw new Error(`Module does not have a named meta export: ${foundPath}`);
2494
+ }
2495
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
2496
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(
2497
+ internalSsrPath
2498
+ );
2499
+ const localFieldsJson = renderFieldsToJson(fields, modulePath);
2500
+ const localModule = {
2501
+ isJsModule: true,
2502
+ schemaVersion: 2,
2503
+ fields: localFieldsJson,
2504
+ id: 1,
2505
+ path: `@projects/${projectName}/${projectComponentPath}/components/modules/${moduleName}`,
2506
+ hublDataTemplate
2507
+ };
2470
2508
  const queryParams = new URLSearchParams({
2471
2509
  portalId: `${authedPortalId}`,
2472
- module_id: `${moduleFetchResult.moduleId}`,
2473
2510
  hsLocalProxy: `${true}`,
2474
- hs_preview_key: `${moduleFetchResult.previewKey}`,
2475
2511
  localProxySchemaVersion: "1"
2476
2512
  });
2477
- const templatePreviewResponse = await fetch(
2513
+ const templatePreviewResponse = await fetch2(
2478
2514
  `${baseUrl}/cos-rendering/v1/public/_hcms/preview/template/multiform?${queryParams}`,
2479
2515
  {
2480
2516
  method: "POST",
@@ -2482,16 +2518,17 @@ async function modulePreviewRouteHandler(request2, response) {
2482
2518
  ["content-type"]: "application/x-www-form-urlencoded",
2483
2519
  ["Accept"]: "text/html",
2484
2520
  referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`
2485
- }
2521
+ },
2522
+ body: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2486
2523
  }
2487
2524
  );
2488
2525
  templatePreview = await templatePreviewResponse.text();
2489
2526
  } catch (e) {
2490
- return response.status(500).end(
2491
- `Error previewing module (${moduleName}). Ensure this module has been included in a successful project build.
2527
+ return response.status(500).end(`Error fetching module preview for (${moduleName}).
2492
2528
 
2493
- `
2494
- );
2529
+ ${e}.
2530
+
2531
+ `);
2495
2532
  }
2496
2533
  try {
2497
2534
  const localRenderPlaceholders = findLocalRenderPlaceholders(templatePreview);
@@ -2597,7 +2634,7 @@ import express from "express";
2597
2634
 
2598
2635
  // src/shadowDevServer/createShadowDevServerRoutes.ts
2599
2636
  import { Router as Router2 } from "express";
2600
- import { getAccountId as getAccountId4, getEnv as getEnv2 } from "@hubspot/cli-lib/lib/config.js";
2637
+ import { getAccountId as getAccountId3, getEnv as getEnv2 } from "@hubspot/cli-lib/lib/config.js";
2601
2638
  import cors from "cors";
2602
2639
  import { buildStaticEnvConfig as buildStaticEnvConfig5 } from "@hubspot/cms-components";
2603
2640
  function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
@@ -2618,7 +2655,7 @@ function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
2618
2655
  let hasJSBuildingBlocks = false;
2619
2656
  let localProxyUrl;
2620
2657
  try {
2621
- accountId = getAccountId4(portalId);
2658
+ accountId = getAccountId3(portalId);
2622
2659
  if (accountId === null) {
2623
2660
  throw new Error();
2624
2661
  }
@@ -2885,7 +2922,7 @@ async function getJsRenderingGates(portalId, env, personalAccessKey) {
2885
2922
  // src/createDevServer.ts
2886
2923
  import {
2887
2924
  getEnv as getEnv3,
2888
- getAccountId as getAccountId5,
2925
+ getAccountId as getAccountId4,
2889
2926
  getAccountConfig as getAccountConfig2,
2890
2927
  loadConfig,
2891
2928
  validateConfig
@@ -2893,7 +2930,7 @@ import {
2893
2930
  import { fetchSecrets } from "@hubspot/cli-lib/api/secrets.js";
2894
2931
 
2895
2932
  // src/proxyPage/fetchDomains.ts
2896
- import { get as hsGet5 } from "@hubspot/cli-lib/http.js";
2933
+ import { get as hsGet4 } from "@hubspot/cli-lib/http.js";
2897
2934
 
2898
2935
  // src/lib/errors.ts
2899
2936
  var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
@@ -2922,7 +2959,7 @@ function isMissingScopeError(error) {
2922
2959
  // src/proxyPage/fetchDomains.ts
2923
2960
  async function fetchDomains(portalId) {
2924
2961
  try {
2925
- const result = await hsGet5(portalId, {
2962
+ const result = await hsGet4(portalId, {
2926
2963
  uri: `/cms/v3/domains`,
2927
2964
  query: { portalId },
2928
2965
  json: true
@@ -2944,19 +2981,11 @@ async function fetchWebsiteDomainNames(portalId) {
2944
2981
  return domainNames;
2945
2982
  }
2946
2983
 
2947
- // src/lib/getCMSAssetConfig.ts
2948
- import fs2 from "fs";
2949
- import path7 from "path";
2950
- function getCMSAssetConfig(webRoot2) {
2951
- const cmsAssetsPath = path7.join(webRoot2, "cms-assets.json");
2952
- return JSON.parse(fs2.readFileSync(cmsAssetsPath).toString());
2953
- }
2954
-
2955
2984
  // src/lib/validateHSPlatform.ts
2956
- import path8 from "path";
2985
+ import path7 from "path";
2957
2986
  import fs3 from "fs";
2958
2987
  import select from "@inquirer/select";
2959
- import { get as hsGet6 } from "@hubspot/cli-lib/http.js";
2988
+ import { get as hsGet5 } from "@hubspot/cli-lib/http.js";
2960
2989
  var HSPROJECT_JSON = "hsproject.json";
2961
2990
  function checkFileExists(filePath) {
2962
2991
  return fs3.existsSync(filePath) && fs3.statSync(filePath).isFile();
@@ -2965,12 +2994,12 @@ function findHSProjectJson(startPath) {
2965
2994
  let currentDir = startPath;
2966
2995
  let dirLevel = 0;
2967
2996
  const maxDirLevel = 4;
2968
- while (path8.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
2969
- const filePath = path8.join(currentDir, HSPROJECT_JSON);
2997
+ while (path7.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
2998
+ const filePath = path7.join(currentDir, HSPROJECT_JSON);
2970
2999
  if (checkFileExists(filePath)) {
2971
3000
  return filePath;
2972
3001
  }
2973
- currentDir = path8.dirname(currentDir);
3002
+ currentDir = path7.dirname(currentDir);
2974
3003
  dirLevel++;
2975
3004
  }
2976
3005
  console.log(
@@ -2991,7 +3020,7 @@ async function validateHSPlatform(webroot, portalId) {
2991
3020
  const { platformVersion } = hsProjectJSONData;
2992
3021
  let platformVersionResult;
2993
3022
  try {
2994
- platformVersionResult = await hsGet6(portalId, {
3023
+ platformVersionResult = await hsGet5(portalId, {
2995
3024
  uri: `developer/projects/v1/platformVersion`,
2996
3025
  json: true
2997
3026
  });
@@ -3065,7 +3094,7 @@ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2
3065
3094
  process.exit(1);
3066
3095
  }
3067
3096
  if (validateConfig()) {
3068
- authedPortalId = getAccountId5(hubspotCliAccountNameOption2);
3097
+ authedPortalId = getAccountId4(hubspotCliAccountNameOption2);
3069
3098
  authedEnv = getEnv3(hubspotCliAccountNameOption2);
3070
3099
  personalAccessKey = getAccountConfig2(authedPortalId) && getAccountConfig2(authedPortalId).personalAccessKey;
3071
3100
  if (!authedPortalId && hubspotCliAccountNameOption2) {
@@ -3134,7 +3163,7 @@ Local proxy functionality will not work without setting up authentication.`
3134
3163
  }
3135
3164
  }
3136
3165
  const authedHublet = "na1";
3137
- const absoluteWebRoot = normalizePath6(path9.resolve(process.cwd(), webRoot2));
3166
+ const absoluteWebRoot = normalizePath6(path8.resolve(process.cwd(), webRoot2));
3138
3167
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
3139
3168
  if (authedPortalId) {
3140
3169
  await validateHSPlatform(absoluteWebRoot, authedPortalId);
@@ -3151,7 +3180,7 @@ Local proxy functionality will not work without setting up authentication.`
3151
3180
  const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
3152
3181
  const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
3153
3182
  const projectName = getProjectNameFromHSConfig(
3154
- path9.join(webRoot2, "../hsproject.json")
3183
+ path8.join(webRoot2, "../hsproject.json")
3155
3184
  );
3156
3185
  const httpServers = [];
3157
3186
  const expressServer = express2();
@@ -3208,8 +3237,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3208
3237
  `
3209
3238
  );
3210
3239
  if (storybook2) {
3211
- const packageRoot = path9.dirname(url2.fileURLToPath(import.meta.url));
3212
- const configPath = path9.resolve(packageRoot, "./storybook-main");
3240
+ const packageRoot = path8.dirname(url2.fileURLToPath(import.meta.url));
3241
+ const configPath = path8.resolve(packageRoot, "./storybook-main");
3213
3242
  sendTrackingRequest("start-storybook");
3214
3243
  const storybookProcess = spawn(
3215
3244
  "sb",
@@ -3229,7 +3258,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3229
3258
  portalId: authedPortalId.toString(),
3230
3259
  hsEnv: authedEnv,
3231
3260
  hublet: authedHublet,
3232
- WEB_ROOT: path9.join(webRoot2, "components")
3261
+ WEB_ROOT: path8.join(webRoot2, "components")
3233
3262
  }
3234
3263
  }
3235
3264
  );