@hubspot/cms-dev-server 0.15.3 → 0.15.8

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
@@ -35,6 +35,7 @@ Options:
35
35
  -a, --account The account name or id to use for the dev server.
36
36
  --ssl Enables SSL for the dev server, serving it over an https:// URL.
37
37
  --storybook Launches a Storybook dev server.
38
+ --generateFieldsTypes Generate types for fields.(jsx|json) files in module folders.
38
39
 
39
40
  For more information on HubSpot CMS JS Rendering, visit:
40
41
  ${wrapMessageInColor(
@@ -47,7 +48,7 @@ function getDevServerCommandLineOptions(argv) {
47
48
  const webRoot2 = args[2];
48
49
  let hubspotCliConfigPathOption2;
49
50
  let hubspotCliAccountNameOption2;
50
- if (args.length == 2 || args.includes("help") || args.includes("--help")) {
51
+ if (args.length === 2 || args.includes("help") || args.includes("--help")) {
51
52
  printHelpMessage();
52
53
  process.exit(0);
53
54
  }
@@ -67,17 +68,19 @@ function getDevServerCommandLineOptions(argv) {
67
68
  }
68
69
  const sslEnabledOption2 = args.includes("--ssl") && !args.includes("--no-ssl");
69
70
  const storybook2 = args.findIndex((arg) => arg === "--storybook") > 0;
71
+ const fieldGenEnabledOption2 = args.includes("--generateFieldsTypes");
70
72
  return {
71
73
  hubspotCliConfigPathOption: hubspotCliConfigPathOption2,
72
74
  hubspotCliAccountNameOption: hubspotCliAccountNameOption2,
73
75
  sslEnabledOption: sslEnabledOption2,
74
76
  storybook: storybook2,
77
+ fieldGenEnabledOption: fieldGenEnabledOption2,
75
78
  webRoot: webRoot2
76
79
  };
77
80
  }
78
81
 
79
82
  // src/createDevServer.ts
80
- import path8 from "path";
83
+ import path9 from "path";
81
84
  import url2 from "url";
82
85
  import express2 from "express";
83
86
  import http3 from "http";
@@ -409,6 +412,9 @@ import stream from "stream";
409
412
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
410
413
  import * as cmsComponents from "@hubspot/cms-components";
411
414
  import { ServerRenderContext } from "@hubspot/cms-components";
415
+ import { writeFileSync } from "fs";
416
+ import ts from "typescript";
417
+ import React, { isValidElement, cloneElement } from "react";
412
418
  var { setProperty, getProperty, hasProperty } = dotProp;
413
419
  var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
414
420
  const islandsArrayToSerialize = tweakedIslandsArray.map(
@@ -652,6 +658,265 @@ async function renderOnServer(elements, renderContext = bootStrapRenderContext()
652
658
  }
653
659
  return { html, renderContext };
654
660
  }
661
+ var fieldTypeNameByType = {
662
+ alignment: "AlignmentFieldType",
663
+ audioplayer: "AudioFieldType",
664
+ backgroundimage: "BackgroundImageFieldType",
665
+ blog: "BlogFieldType",
666
+ boolean: "BooleanFieldType",
667
+ border: "BorderFieldType",
668
+ choice: "ChoiceFieldType",
669
+ color: "ColorFieldType",
670
+ crmobject: "CrmObjectFieldType",
671
+ cta: "CtaFieldType",
672
+ date: "DateFieldType",
673
+ datetime: "DateTimeFieldType",
674
+ email: "EmailFieldType",
675
+ embed: "EmbedFieldType",
676
+ file: "FileFieldType",
677
+ followupemail: "FollowUpEmailFieldType",
678
+ font: "FontFieldType",
679
+ form: "FormFieldType",
680
+ gradient: "GradientFieldType",
681
+ group: "GroupFieldType",
682
+ html: "HtmlFieldType",
683
+ hubdbrow: "HubDbRowFieldType",
684
+ hubdbtable: "HubDbTableFieldType",
685
+ hubl: "HublFieldType",
686
+ icon: "IconFieldType",
687
+ image: "ImageFieldType",
688
+ link: "LinkFieldType",
689
+ logo: "LogoFieldType",
690
+ meeting: "MeetingFieldType",
691
+ menu: "MenuFieldType",
692
+ number: "NumberFieldType",
693
+ page: "PageFieldType",
694
+ payment: "PaymentFieldType",
695
+ podcast: "PodcastFieldType",
696
+ richtext: "RichTextFieldType",
697
+ salesforcecampaign: "SfdcCamapaignFieldType",
698
+ simplemenu: "SimpleMenuFieldType",
699
+ spacing: "SpacingFieldType",
700
+ survey: "SurveyFieldType",
701
+ tag: "TagFieldType",
702
+ textalignment: "TextAlignmentFieldType",
703
+ text: "TextFieldType",
704
+ url: "UrlFieldType",
705
+ video: "VideoFieldType",
706
+ workflow: "WorkflowFieldType"
707
+ };
708
+ var getChildrenAsArray = (element) => React.Children.toArray(element.props.children);
709
+ function getFieldEntries(fields) {
710
+ if (isValidElement(fields)) {
711
+ const fieldsJSX = getChildrenAsArray(fields);
712
+ return getReactFieldEntries(fieldsJSX);
713
+ } else if (Array.isArray(fields)) {
714
+ return getJSONFieldEntries(fields);
715
+ }
716
+ return void 0;
717
+ }
718
+ var getJSXFieldType = (fieldFunctionName) => {
719
+ switch (fieldFunctionName) {
720
+ case "RepeatedFieldGroup":
721
+ case "FieldGroup":
722
+ return "GroupFieldType";
723
+ default:
724
+ return `${fieldFunctionName}Type`;
725
+ }
726
+ };
727
+ var getElementName = (element) => typeof element.type === "string" ? element.type : element.type.name || null;
728
+ function getReactFieldEntries(fields) {
729
+ const validTypeNames = Object.values(fieldTypeNameByType);
730
+ if (!Array.isArray(fields)) {
731
+ return;
732
+ }
733
+ return fields.filter((field) => field.props && field.props.name).map((field) => {
734
+ const elName = getElementName(field);
735
+ const fieldType = getJSXFieldType(getElementName(field));
736
+ if (!validTypeNames.includes(fieldType)) {
737
+ return void 0;
738
+ }
739
+ const { name, default: hasDefault } = field.props;
740
+ const isRepeater = elName === "RepeatedFieldGroup";
741
+ const entry = {
742
+ type: fieldType,
743
+ name,
744
+ hasDefault: !!hasDefault,
745
+ isRepeater,
746
+ children: []
747
+ };
748
+ if (fieldType === "GroupFieldType") {
749
+ const childrenArray = getChildrenAsArray(field);
750
+ const children = getReactFieldEntries(childrenArray);
751
+ return {
752
+ ...entry,
753
+ children
754
+ };
755
+ }
756
+ return entry;
757
+ }).filter((entry) => entry !== void 0);
758
+ }
759
+ function getJSONFieldEntries(fields) {
760
+ if (!Array.isArray(fields)) {
761
+ return;
762
+ }
763
+ return fields.filter((field) => field.name && field.type).map((field) => {
764
+ const { name, type } = field;
765
+ const fieldType = fieldTypeNameByType[type];
766
+ if (!fieldType) {
767
+ return void 0;
768
+ }
769
+ const entry = {
770
+ type: fieldType,
771
+ name,
772
+ isRepeater: "occurrence" in field,
773
+ hasDefault: !!field.default,
774
+ children: []
775
+ };
776
+ if (fieldType === "GroupFieldType" && "children" in field) {
777
+ const children = getJSONFieldEntries(field.children);
778
+ return { ...entry, children };
779
+ }
780
+ return entry;
781
+ }).filter((entry) => entry !== void 0);
782
+ }
783
+ var OVERRIDE_TYPE = "Override";
784
+ var REQUIRED_TYPE = "Required";
785
+ var REPEATED_VAR = "_repeater";
786
+ var DEFAULT_VALUES_TYPE = "DefaultValues";
787
+ var CMS_COMPONENTS = "@hubspot/cms-components";
788
+ var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
789
+ var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
790
+ var createPropertySignature = (identifier, type) => ts.factory.createPropertySignature([], identifier, void 0, type);
791
+ var buildTypeFromField = (field, additionalNode) => {
792
+ const imports = [field.type];
793
+ const identifier = ts.factory.createIdentifier(field.name);
794
+ const baseType = ts.factory.createTypeReferenceNode(field.type);
795
+ const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
796
+ baseType
797
+ ]);
798
+ let finalType = field.hasDefault ? requiredType : baseType;
799
+ if (additionalNode) {
800
+ const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
801
+ const repeaterName = ts.factory.createLiteralTypeNode(
802
+ ts.factory.createStringLiteral(REPEATED_VAR)
803
+ );
804
+ if (!field.isRepeater) {
805
+ imports.push(OVERRIDE_TYPE);
806
+ }
807
+ finalType = field.isRepeater ? ts.factory.createTypeReferenceNode("Array", [
808
+ ts.factory.createTypeReferenceNode("Record", [
809
+ repeaterName,
810
+ typeLiteral
811
+ ])
812
+ ]) : ts.factory.createTypeReferenceNode(OVERRIDE_TYPE, [
813
+ finalType,
814
+ typeLiteral
815
+ ]);
816
+ }
817
+ return { type: createPropertySignature(identifier, finalType), imports };
818
+ };
819
+ function getImportDeclaration(imports, moduleSpecifier) {
820
+ const importSpecifiers = Array.from(imports).map(
821
+ (importName) => ts.factory.createImportSpecifier(
822
+ true,
823
+ void 0,
824
+ ts.factory.createIdentifier(importName)
825
+ )
826
+ );
827
+ const namedImports = ts.factory.createNamedImports(importSpecifiers);
828
+ return ts.factory.createImportDeclaration(
829
+ [],
830
+ [],
831
+ ts.factory.createImportClause(false, void 0, namedImports),
832
+ ts.factory.createStringLiteral(moduleSpecifier)
833
+ );
834
+ }
835
+ function getFieldTypes(fields) {
836
+ const imports = ["DefaultValues"];
837
+ const types = fields.map((field) => {
838
+ if (field.children) {
839
+ const childrenResult = getFieldTypes(field.children);
840
+ imports.push(...childrenResult.imports);
841
+ if (childrenResult.types.length) {
842
+ const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
843
+ const childrenPropertySignature = createPropertySignature(
844
+ "children",
845
+ subType
846
+ );
847
+ const { type: type2, imports: newImports2 } = buildTypeFromField(
848
+ field,
849
+ field.isRepeater ? subType : childrenPropertySignature
850
+ );
851
+ imports.push(...newImports2);
852
+ return type2;
853
+ }
854
+ }
855
+ const { type, imports: newImports } = buildTypeFromField(field);
856
+ imports.push(...newImports);
857
+ return type;
858
+ });
859
+ return { types, imports: Array.from(new Set(imports)) };
860
+ }
861
+ function constructFinalType(fields, typeName) {
862
+ const { types, imports } = getFieldTypes(fields);
863
+ const importDeclaration = getImportDeclaration(
864
+ imports,
865
+ CMS_COMPONENTS_FIELD_TYPES
866
+ );
867
+ const baseType = ts.factory.createTypeAliasDeclaration(
868
+ [],
869
+ [],
870
+ "",
871
+ void 0,
872
+ ts.factory.createTypeLiteralNode(types)
873
+ );
874
+ const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
875
+ baseType.type
876
+ ]);
877
+ const finalType = ts.factory.createTypeAliasDeclaration(
878
+ [],
879
+ [],
880
+ typeName,
881
+ void 0,
882
+ wrappedType
883
+ );
884
+ const defaultExport = ts.factory.createExportDefault(
885
+ ts.factory.createIdentifier(typeName)
886
+ );
887
+ return [importDeclaration, finalType, defaultExport];
888
+ }
889
+ function writeFieldsType(fields, fileName, typeName) {
890
+ const entries = getFieldEntries(fields);
891
+ if (!entries) {
892
+ return false;
893
+ }
894
+ try {
895
+ const file = ts.createSourceFile(
896
+ fileName,
897
+ "",
898
+ ts.ScriptTarget.ESNext,
899
+ false,
900
+ ts.ScriptKind.TS
901
+ );
902
+ const printer = ts.createPrinter();
903
+ const nodes = constructFinalType(entries, typeName);
904
+ const comments = [
905
+ AUTO_GEN_COMMENT,
906
+ "Removing the above comment will disable type generation for this module",
907
+ "This file was created by @hubspot/cms-dev-server, for more information see https://github.hubspot.com/cms-react/reference/js-modules.html#module-fields"
908
+ ].map((comment) => `// ${comment}`);
909
+ const typeResult = nodes.map(
910
+ (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)
911
+ );
912
+ const result = [...comments, ...typeResult].join("\n");
913
+ writeFileSync(fileName, result);
914
+ return true;
915
+ } catch (e) {
916
+ console.error(e);
917
+ return false;
918
+ }
919
+ }
655
920
  function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
656
921
  if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
657
922
  prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
@@ -1044,7 +1309,7 @@ function trackUsage(action) {
1044
1309
  eventName: EVENT_NAME,
1045
1310
  action,
1046
1311
  nodeVersion: getNodeVersionData(),
1047
- version: "0.15.3",
1312
+ version: "0.15.8",
1048
1313
  os: getPlatform()
1049
1314
  };
1050
1315
  const uri = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1690,12 +1955,12 @@ var findLocalRenderPlaceholders = (body) => {
1690
1955
  );
1691
1956
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1692
1957
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1693
- const path9 = body.substring(
1958
+ const path10 = body.substring(
1694
1959
  startOffset + localJsRenderStartString.length,
1695
1960
  pathEndOffset
1696
1961
  );
1697
1962
  offsetSoFar = pathEndOffset + 1;
1698
- if (startOffset >= 0 && path9) {
1963
+ if (startOffset >= 0 && path10) {
1699
1964
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1700
1965
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1701
1966
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1720,7 +1985,7 @@ var findLocalRenderPlaceholders = (body) => {
1720
1985
  result.push({
1721
1986
  startOffset,
1722
1987
  endOffset: endOffset + localJsRenderEndString.length,
1723
- path: path9,
1988
+ path: path10,
1724
1989
  json
1725
1990
  });
1726
1991
  }
@@ -1834,9 +2099,9 @@ var customColors = [
1834
2099
  ];
1835
2100
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
1836
2101
  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;`;
1837
- var renderLocalError_default = (path9, error) => {
2102
+ var renderLocalError_default = (path10, error) => {
1838
2103
  const stackWithColorClasses = Converter.toHtml(error.stack);
1839
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path9}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2104
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path10}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1840
2105
  };
1841
2106
 
1842
2107
  // src/proxyPage/fetchPreviewInfo.ts
@@ -1887,34 +2152,6 @@ import {
1887
2152
  isDebugUrlString as isDebugUrlString3,
1888
2153
  mergeServerRequestData_internal
1889
2154
  } from "@hubspot/cms-components";
1890
-
1891
- // src/lib/cleanCookieHeaders.ts
1892
- var CookieBlockList = [
1893
- "__cflb",
1894
- "__cf_bm",
1895
- "__cfseq",
1896
- "__cfwaitingroom",
1897
- "__cfruid",
1898
- "_cfuvid",
1899
- "cf_ob_info",
1900
- "cf_use_ob",
1901
- "cf_clearance",
1902
- "cf_chl_XXXX",
1903
- "cf_chl_rc_i",
1904
- "cf_chl_rc_ni",
1905
- "cf_chl_rc_m"
1906
- ];
1907
- function cleanCookieHeaders(cookieHeader) {
1908
- if (cookieHeader === void 0)
1909
- return "";
1910
- const cookies = cookieHeader.split(";");
1911
- const cookieRegex = new RegExp(CookieBlockList.join("|"));
1912
- return cookies.filter((cookie) => {
1913
- return !cookie.match(cookieRegex);
1914
- }).join(";");
1915
- }
1916
-
1917
- // src/proxyPage/proxyPage.ts
1918
2155
  var getEntryPointBasePathFromProxyRequest = (request2) => {
1919
2156
  if (!request2) {
1920
2157
  return "";
@@ -1939,7 +2176,6 @@ function resolvePlaceholderPath(placeholderPath, projectName, projectComponent)
1939
2176
  }
1940
2177
  var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, projectName, environmentConfig, __jsRenderingGates, cookieHeader) => {
1941
2178
  const url3 = new URL(urlToProxy);
1942
- const cleanedCookieHeader = cleanCookieHeaders(cookieHeader);
1943
2179
  const renderPreviewLocally = url3.searchParams.has("renderPreviewLocally");
1944
2180
  let proxiedQueryParams = {};
1945
2181
  let baseUrl = url3.origin;
@@ -1961,7 +2197,8 @@ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, pro
1961
2197
  ...proxiedQueryParams,
1962
2198
  hs_preview: `${previewKey}-${contentId}`,
1963
2199
  hsLocalProxyProject: localProxyProject,
1964
- localProxySchemaVersion: "2"
2200
+ localProxySchemaVersion: "2",
2201
+ hsLoginVerifyDisabled: `${true}`
1965
2202
  };
1966
2203
  if (renderPreviewLocally) {
1967
2204
  proxiedQueryParams.hsDebugOverridePublicHost = url3.host;
@@ -1982,7 +2219,8 @@ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, pro
1982
2219
  json: false,
1983
2220
  useQuerystring: true,
1984
2221
  headers: {
1985
- COOKIE: cleanedCookieHeader
2222
+ COOKIE: cookieHeader,
2223
+ "User-Agent": "HubSpot CMS Dev Server"
1986
2224
  }
1987
2225
  });
1988
2226
  return result.catch((error) => {
@@ -2652,7 +2890,8 @@ async function modulePreviewRouteHandler(request2, response) {
2652
2890
  const queryParams = new URLSearchParams({
2653
2891
  portalId: `${authedPortalId}`,
2654
2892
  hsLocalProxy: `${true}`,
2655
- localProxySchemaVersion: "2"
2893
+ localProxySchemaVersion: "2",
2894
+ hsLoginVerifyDisabled: `${true}`
2656
2895
  });
2657
2896
  const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2658
2897
  process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot${authedEnv === "qa" ? "qa" : ""}`;
@@ -2662,7 +2901,8 @@ async function modulePreviewRouteHandler(request2, response) {
2662
2901
  ["content-type"]: "application/x-www-form-urlencoded",
2663
2902
  ["Accept"]: "text/html",
2664
2903
  referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2665
- cookie: cleanCookieHeaders(request2.get("COOKIE"))
2904
+ cookie: request2.get("COOKIE"),
2905
+ "User-Agent": "HubSpot CMS Dev Server"
2666
2906
  },
2667
2907
  body: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2668
2908
  });
@@ -3211,11 +3451,121 @@ async function validateHSPlatform(projectConfigPath, portalId) {
3211
3451
 
3212
3452
  // src/createDevServer.ts
3213
3453
  import { get as hsGet6 } from "@hubspot/cli-lib/http.js";
3454
+
3455
+ // src/lib/watchFieldsUpdates.ts
3456
+ import fs4 from "fs";
3457
+ import path8 from "path";
3458
+ import readline from "readline";
3459
+ var lastSerializedFieldsCache = {};
3460
+ var formatAsTypeName = (str) => {
3461
+ const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
3462
+ const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
3463
+ return validFirstChar ? typeName : `_${typeName}`;
3464
+ };
3465
+ var isInModulesFolder = (filePath, projectRoot) => {
3466
+ const getEntryPathFromId = (id) => {
3467
+ return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
3468
+ };
3469
+ const currentModuleId = path8.normalize(filePath);
3470
+ const moduleEntryPath = getEntryPathFromId(currentModuleId);
3471
+ const subFolderTokens = moduleEntryPath.split(path8.sep);
3472
+ return {
3473
+ inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
3474
+ isRootModuleFile: subFolderTokens.length === 3
3475
+ };
3476
+ };
3477
+ var fileContainsAutoGenComment = async (filePath) => {
3478
+ if (!fs4.existsSync(filePath))
3479
+ return true;
3480
+ const stream2 = fs4.createReadStream(filePath);
3481
+ const reader = readline.createInterface({ input: stream2 });
3482
+ const firstLine = await new Promise(
3483
+ (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
3484
+ );
3485
+ reader.close();
3486
+ stream2.close();
3487
+ return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
3488
+ };
3489
+ var getIndexFile = (filePath, projectRoot) => {
3490
+ const { inModuleFolder, isRootModuleFile } = isInModulesFolder(
3491
+ filePath,
3492
+ projectRoot
3493
+ );
3494
+ if (!inModuleFolder)
3495
+ return void 0;
3496
+ if (isRootModuleFile)
3497
+ return { indexFilePath: filePath, isRootModuleFile };
3498
+ const dir = path8.dirname(filePath);
3499
+ const files = fs4.readdirSync(dir);
3500
+ const indexFileName = files.find((file) => file.startsWith("index."));
3501
+ return indexFileName ? { indexFilePath: path8.join(dir, indexFileName), isRootModuleFile } : void 0;
3502
+ };
3503
+ var getIndexFileFields = async (indexFilePath, viteServer) => {
3504
+ let indexFile;
3505
+ try {
3506
+ indexFile = await viteServer.ssrLoadModule(indexFilePath);
3507
+ } catch (e) {
3508
+ return void 0;
3509
+ }
3510
+ if (!indexFile.fields)
3511
+ return void 0;
3512
+ const fields = indexFile.fields;
3513
+ const isJsonFields = Array.isArray(fields);
3514
+ const isReactFields = fields.type && fields.type.name === "ModuleFields";
3515
+ if (isJsonFields || isReactFields) {
3516
+ return fields;
3517
+ }
3518
+ return void 0;
3519
+ };
3520
+ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3521
+ const indexInfo = getIndexFile(filePath, projectRoot);
3522
+ if (!indexInfo)
3523
+ return;
3524
+ const { indexFilePath, isRootModuleFile } = indexInfo;
3525
+ const indexFileName = path8.parse(indexFilePath).name;
3526
+ const isTypeFile = filePath.endsWith(".types.ts");
3527
+ if (isTypeFile)
3528
+ return;
3529
+ const fields = await getIndexFileFields(indexFilePath, viteServer);
3530
+ if (fields) {
3531
+ const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
3532
+ const typeFilePath = path8.join(path8.dirname(filePath), typeFileName);
3533
+ const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
3534
+ const serializedFields = JSON.stringify(fields);
3535
+ if (lastSerializedFields === serializedFields)
3536
+ return;
3537
+ const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
3538
+ if (!hasAutoGenComment)
3539
+ return;
3540
+ const moduleFolderName = path8.basename(path8.dirname(filePath));
3541
+ const outputTypeName = formatAsTypeName(moduleFolderName);
3542
+ const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
3543
+ if (didSucceed) {
3544
+ lastSerializedFieldsCache[typeFilePath] = serializedFields;
3545
+ }
3546
+ const pathToLog = isRootModuleFile ? `${moduleFolderName}/${indexFileName}` : moduleFolderName;
3547
+ const successMsg = `Successfully generated types for ${pathToLog}`;
3548
+ const errorMsg = `Failed to generate types for ${pathToLog}`;
3549
+ const message = didSucceed ? successMsg : errorMsg;
3550
+ console.log(wrapMessageInColor(didSucceed ? "green" : "red", message));
3551
+ }
3552
+ };
3553
+ var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
3554
+ const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
3555
+ moduleSubpaths.forEach((modulePath) => {
3556
+ const resolvedPath = path8.resolve(projectRoot, modulePath);
3557
+ maybeUpdateFields(resolvedPath, viteServer, projectRoot);
3558
+ });
3559
+ const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
3560
+ viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
3561
+ };
3562
+
3563
+ // src/createDevServer.ts
3214
3564
  var BASE_PATH = "/";
3215
3565
  var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
3216
3566
  var SHADOW_PORT = 1442;
3217
3567
  var STORYBOOK_PORT = process.env.STORYBOOK_PORT ? parseInt(process.env.STORYBOOK_PORT, 10) : 3123;
3218
- async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2) {
3568
+ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2) {
3219
3569
  let authedPortalId = null;
3220
3570
  let authedEnv = null;
3221
3571
  let jsRenderingGates = [];
@@ -3322,7 +3672,7 @@ Local proxy functionality and module preview routes will not work without settin
3322
3672
  } catch (e) {
3323
3673
  authedHublet = "na1";
3324
3674
  }
3325
- const absoluteWebRoot = normalizePath6(path8.resolve(process.cwd(), webRoot2));
3675
+ const absoluteWebRoot = normalizePath6(path9.resolve(process.cwd(), webRoot2));
3326
3676
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
3327
3677
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
3328
3678
  if (authedPortalId) {
@@ -3336,6 +3686,9 @@ Local proxy functionality and module preview routes will not work without settin
3336
3686
  jsRenderingGates,
3337
3687
  secretNames
3338
3688
  );
3689
+ if (fieldGenEnabledOption2) {
3690
+ startFieldsTypeGenWatcher(viteServer, absoluteWebRoot);
3691
+ }
3339
3692
  const viteHTTPSConfig = viteServer.config.server.https;
3340
3693
  const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
3341
3694
  const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
@@ -3396,8 +3749,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3396
3749
  `
3397
3750
  );
3398
3751
  if (storybook2) {
3399
- const packageRoot = path8.dirname(url2.fileURLToPath(import.meta.url));
3400
- const configPath = path8.resolve(packageRoot, "./storybook-main");
3752
+ const packageRoot = path9.dirname(url2.fileURLToPath(import.meta.url));
3753
+ const configPath = path9.resolve(packageRoot, "./storybook-main");
3401
3754
  sendTrackingRequest("start-storybook");
3402
3755
  const storybookProcess = spawn(
3403
3756
  "sb",
@@ -3417,7 +3770,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3417
3770
  portalId: authedPortalId.toString(),
3418
3771
  hsEnv: authedEnv,
3419
3772
  hublet: authedHublet,
3420
- WEB_ROOT: path8.join(webRoot2, "components")
3773
+ WEB_ROOT: path9.join(webRoot2, "components")
3421
3774
  }
3422
3775
  }
3423
3776
  );
@@ -3463,7 +3816,8 @@ var {
3463
3816
  hubspotCliConfigPathOption,
3464
3817
  hubspotCliAccountNameOption,
3465
3818
  sslEnabledOption,
3466
- storybook
3819
+ storybook,
3820
+ fieldGenEnabledOption
3467
3821
  } = getDevServerCommandLineOptions(process.argv);
3468
3822
  if (!webRoot) {
3469
3823
  throw new Error(`No web root path argument specified`);
@@ -3473,5 +3827,6 @@ createDevServer_default(
3473
3827
  storybook,
3474
3828
  hubspotCliConfigPathOption,
3475
3829
  hubspotCliAccountNameOption,
3476
- sslEnabledOption
3830
+ sslEnabledOption,
3831
+ fieldGenEnabledOption
3477
3832
  );
@@ -36,13 +36,15 @@ function namespaceModulePropsShape(props) {
36
36
  import * as dotProp from "dot-prop";
37
37
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
38
38
  import * as cmsComponents from "@hubspot/cms-components";
39
- import { isValidElement, cloneElement } from "react";
39
+ import React, { isValidElement, cloneElement } from "react";
40
40
  var { setProperty, getProperty, hasProperty } = dotProp;
41
41
  var {
42
42
  createServerRenderContextV2: createServerRenderContextV22,
43
43
  createServerRenderContext: createServerRenderContext2,
44
44
  renderServerSidePropsWithAsyncLocalStoreContext
45
45
  } = cmsComponents;
46
+ var CMS_COMPONENTS = "@hubspot/cms-components";
47
+ var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
46
48
  function renderFieldsJSX(fieldsJSX) {
47
49
  let moduleJson;
48
50
  const outputCallback = (callbackJson) => {