@hubspot/cms-dev-server 0.15.4 → 0.15.9

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.
Files changed (2) hide show
  1. package/dist/run.js +411 -53
  2. package/package.json +3 -3
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";
@@ -1044,7 +1047,7 @@ function trackUsage(action) {
1044
1047
  eventName: EVENT_NAME,
1045
1048
  action,
1046
1049
  nodeVersion: getNodeVersionData(),
1047
- version: "0.15.4",
1050
+ version: "0.15.9",
1048
1051
  os: getPlatform()
1049
1052
  };
1050
1053
  const uri = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1690,12 +1693,12 @@ var findLocalRenderPlaceholders = (body) => {
1690
1693
  );
1691
1694
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1692
1695
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1693
- const path9 = body.substring(
1696
+ const path10 = body.substring(
1694
1697
  startOffset + localJsRenderStartString.length,
1695
1698
  pathEndOffset
1696
1699
  );
1697
1700
  offsetSoFar = pathEndOffset + 1;
1698
- if (startOffset >= 0 && path9) {
1701
+ if (startOffset >= 0 && path10) {
1699
1702
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1700
1703
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1701
1704
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1720,7 +1723,7 @@ var findLocalRenderPlaceholders = (body) => {
1720
1723
  result.push({
1721
1724
  startOffset,
1722
1725
  endOffset: endOffset + localJsRenderEndString.length,
1723
- path: path9,
1726
+ path: path10,
1724
1727
  json
1725
1728
  });
1726
1729
  }
@@ -1834,9 +1837,9 @@ var customColors = [
1834
1837
  ];
1835
1838
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
1836
1839
  var darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
1837
- var renderLocalError_default = (path9, error) => {
1840
+ var renderLocalError_default = (path10, error) => {
1838
1841
  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>`;
1842
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path10}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1840
1843
  };
1841
1844
 
1842
1845
  // src/proxyPage/fetchPreviewInfo.ts
@@ -1887,34 +1890,6 @@ import {
1887
1890
  isDebugUrlString as isDebugUrlString3,
1888
1891
  mergeServerRequestData_internal
1889
1892
  } 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
1893
  var getEntryPointBasePathFromProxyRequest = (request2) => {
1919
1894
  if (!request2) {
1920
1895
  return "";
@@ -1939,7 +1914,6 @@ function resolvePlaceholderPath(placeholderPath, projectName, projectComponent)
1939
1914
  }
1940
1915
  var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, projectName, environmentConfig, __jsRenderingGates, cookieHeader) => {
1941
1916
  const url3 = new URL(urlToProxy);
1942
- const cleanedCookieHeader = cleanCookieHeaders(cookieHeader);
1943
1917
  const renderPreviewLocally = url3.searchParams.has("renderPreviewLocally");
1944
1918
  let proxiedQueryParams = {};
1945
1919
  let baseUrl = url3.origin;
@@ -1983,7 +1957,8 @@ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, pro
1983
1957
  json: false,
1984
1958
  useQuerystring: true,
1985
1959
  headers: {
1986
- COOKIE: cleanedCookieHeader
1960
+ COOKIE: cookieHeader,
1961
+ "User-Agent": "HubSpot CMS Dev Server"
1987
1962
  }
1988
1963
  });
1989
1964
  return result.catch((error) => {
@@ -2511,7 +2486,7 @@ function proxyPathPageResourceRedirect(req, res, next) {
2511
2486
  // src/routes/proxyServerlessHandler.ts
2512
2487
  import fetch2 from "node-fetch";
2513
2488
  var localDomains = ["localhost", "hslocal.net"];
2514
- function proxyPathPageResourceRedirect2(req, res, next) {
2489
+ function proxyServerlessRequest(req, res, next) {
2515
2490
  const { method, headers } = req;
2516
2491
  let refererUrl;
2517
2492
  let domainToProxy;
@@ -2664,7 +2639,8 @@ async function modulePreviewRouteHandler(request2, response) {
2664
2639
  ["content-type"]: "application/x-www-form-urlencoded",
2665
2640
  ["Accept"]: "text/html",
2666
2641
  referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
2667
- cookie: cleanCookieHeaders(request2.get("COOKIE"))
2642
+ cookie: request2.get("COOKIE"),
2643
+ "User-Agent": "HubSpot CMS Dev Server"
2668
2644
  },
2669
2645
  body: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2670
2646
  });
@@ -2766,8 +2742,8 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
2766
2742
  devServerApp.get("/modules/", linksToAllModulesRouteHandler_default);
2767
2743
  devServerApp.get("/module/:moduleName", module_default);
2768
2744
  devServerApp.get("/module/:moduleName/*", module_default);
2769
- devServerApp.all("/hs/serverless/*", proxyPathPageResourceRedirect2);
2770
- devServerApp.all("/_hcms/api/*", proxyPathPageResourceRedirect2);
2745
+ devServerApp.all("/hs/serverless/*", proxyServerlessRequest);
2746
+ devServerApp.all("/_hcms/api/*", proxyServerlessRequest);
2771
2747
  devServerApp.get("/", homeRouteHandler_default);
2772
2748
  devServerApp.get("/*", proxyPathPageResourceRedirect);
2773
2749
  devServerApp.get("/*", proxyPageResourceRedirect);
@@ -3213,11 +3189,385 @@ async function validateHSPlatform(projectConfigPath, portalId) {
3213
3189
 
3214
3190
  // src/createDevServer.ts
3215
3191
  import { get as hsGet6 } from "@hubspot/cli-lib/http.js";
3192
+
3193
+ // ../cms-js-internal/dist/buildFieldsTypes.js
3194
+ import { writeFileSync } from "fs";
3195
+ import ts from "typescript";
3196
+ import React, { isValidElement } from "react";
3197
+ var fieldTypeNameByType = {
3198
+ alignment: "AlignmentFieldType",
3199
+ audioplayer: "AudioFieldType",
3200
+ backgroundimage: "BackgroundImageFieldType",
3201
+ blog: "BlogFieldType",
3202
+ boolean: "BooleanFieldType",
3203
+ border: "BorderFieldType",
3204
+ choice: "ChoiceFieldType",
3205
+ color: "ColorFieldType",
3206
+ crmobject: "CrmObjectFieldType",
3207
+ cta: "CtaFieldType",
3208
+ date: "DateFieldType",
3209
+ datetime: "DateTimeFieldType",
3210
+ email: "EmailFieldType",
3211
+ embed: "EmbedFieldType",
3212
+ file: "FileFieldType",
3213
+ followupemail: "FollowUpEmailFieldType",
3214
+ font: "FontFieldType",
3215
+ form: "FormFieldType",
3216
+ gradient: "GradientFieldType",
3217
+ group: "GroupFieldType",
3218
+ html: "HtmlFieldType",
3219
+ hubdbrow: "HubDbRowFieldType",
3220
+ hubdbtable: "HubDbTableFieldType",
3221
+ hubl: "HublFieldType",
3222
+ icon: "IconFieldType",
3223
+ image: "ImageFieldType",
3224
+ link: "LinkFieldType",
3225
+ logo: "LogoFieldType",
3226
+ meeting: "MeetingFieldType",
3227
+ menu: "MenuFieldType",
3228
+ number: "NumberFieldType",
3229
+ page: "PageFieldType",
3230
+ payment: "PaymentFieldType",
3231
+ podcast: "PodcastFieldType",
3232
+ richtext: "RichTextFieldType",
3233
+ salesforcecampaign: "SfdcCamapaignFieldType",
3234
+ simplemenu: "SimpleMenuFieldType",
3235
+ spacing: "SpacingFieldType",
3236
+ survey: "SurveyFieldType",
3237
+ tag: "TagFieldType",
3238
+ textalignment: "TextAlignmentFieldType",
3239
+ text: "TextFieldType",
3240
+ url: "UrlFieldType",
3241
+ video: "VideoFieldType",
3242
+ workflow: "WorkflowFieldType"
3243
+ };
3244
+ var getChildrenAsArray = (element) => React.Children.toArray(element.props.children);
3245
+ function getFieldEntries(fields) {
3246
+ if (isValidElement(fields)) {
3247
+ const fieldsJSX = getChildrenAsArray(fields);
3248
+ return getReactFieldEntries(fieldsJSX);
3249
+ } else if (Array.isArray(fields)) {
3250
+ return getJSONFieldEntries(fields);
3251
+ }
3252
+ return void 0;
3253
+ }
3254
+ var getJSXFieldType = (fieldFunctionName) => {
3255
+ switch (fieldFunctionName) {
3256
+ case "RepeatedFieldGroup":
3257
+ case "FieldGroup":
3258
+ return "GroupFieldType";
3259
+ default:
3260
+ return `${fieldFunctionName}Type`;
3261
+ }
3262
+ };
3263
+ var getElementName = (element) => typeof element.type === "string" ? element.type : element.type.name || null;
3264
+ function getReactFieldEntries(fields) {
3265
+ const validTypeNames = Object.values(fieldTypeNameByType);
3266
+ if (!Array.isArray(fields)) {
3267
+ return;
3268
+ }
3269
+ return fields.filter((field) => field.props && field.props.name).map((field) => {
3270
+ const elName = getElementName(field);
3271
+ const fieldType = getJSXFieldType(getElementName(field));
3272
+ if (!validTypeNames.includes(fieldType)) {
3273
+ return void 0;
3274
+ }
3275
+ const { name, default: hasDefault } = field.props;
3276
+ const isRepeater = elName === "RepeatedFieldGroup";
3277
+ const entry = {
3278
+ type: fieldType,
3279
+ name,
3280
+ hasDefault: !!hasDefault,
3281
+ isRepeater,
3282
+ children: []
3283
+ };
3284
+ if (fieldType === "GroupFieldType") {
3285
+ const childrenArray = getChildrenAsArray(field);
3286
+ const children = getReactFieldEntries(childrenArray);
3287
+ return {
3288
+ ...entry,
3289
+ children
3290
+ };
3291
+ }
3292
+ return entry;
3293
+ }).filter((entry) => entry !== void 0);
3294
+ }
3295
+ function getJSONFieldEntries(fields) {
3296
+ if (!Array.isArray(fields)) {
3297
+ return;
3298
+ }
3299
+ return fields.filter((field) => field.name && field.type).map((field) => {
3300
+ const { name, type } = field;
3301
+ const fieldType = fieldTypeNameByType[type];
3302
+ if (!fieldType) {
3303
+ return void 0;
3304
+ }
3305
+ const entry = {
3306
+ type: fieldType,
3307
+ name,
3308
+ isRepeater: "occurrence" in field,
3309
+ hasDefault: !!field.default,
3310
+ children: []
3311
+ };
3312
+ if (fieldType === "GroupFieldType" && "children" in field) {
3313
+ const children = getJSONFieldEntries(field.children);
3314
+ return { ...entry, children };
3315
+ }
3316
+ return entry;
3317
+ }).filter((entry) => entry !== void 0);
3318
+ }
3319
+ var OVERRIDE_TYPE = "Override";
3320
+ var REQUIRED_TYPE = "Required";
3321
+ var REPEATED_VAR = "_repeater";
3322
+ var DEFAULT_VALUES_TYPE = "DefaultValues";
3323
+ var CMS_COMPONENTS = "@hubspot/cms-components";
3324
+ var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
3325
+ var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
3326
+ var createPropertySignature = (identifier, type) => ts.factory.createPropertySignature([], identifier, void 0, type);
3327
+ var buildTypeFromField = (field, additionalNode) => {
3328
+ const imports = [field.type];
3329
+ const identifier = ts.factory.createIdentifier(field.name);
3330
+ const baseType = ts.factory.createTypeReferenceNode(field.type);
3331
+ const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
3332
+ baseType
3333
+ ]);
3334
+ let finalType = field.hasDefault ? requiredType : baseType;
3335
+ if (additionalNode) {
3336
+ const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
3337
+ const repeaterName = ts.factory.createLiteralTypeNode(
3338
+ ts.factory.createStringLiteral(REPEATED_VAR)
3339
+ );
3340
+ if (!field.isRepeater) {
3341
+ imports.push(OVERRIDE_TYPE);
3342
+ }
3343
+ finalType = field.isRepeater ? ts.factory.createTypeReferenceNode("Array", [
3344
+ ts.factory.createTypeReferenceNode("Record", [
3345
+ repeaterName,
3346
+ typeLiteral
3347
+ ])
3348
+ ]) : ts.factory.createTypeReferenceNode(OVERRIDE_TYPE, [
3349
+ finalType,
3350
+ typeLiteral
3351
+ ]);
3352
+ }
3353
+ return { type: createPropertySignature(identifier, finalType), imports };
3354
+ };
3355
+ function getImportDeclaration(imports, moduleSpecifier) {
3356
+ const importSpecifiers = Array.from(imports).map(
3357
+ (importName) => ts.factory.createImportSpecifier(
3358
+ true,
3359
+ void 0,
3360
+ ts.factory.createIdentifier(importName)
3361
+ )
3362
+ );
3363
+ const namedImports = ts.factory.createNamedImports(importSpecifiers);
3364
+ return ts.factory.createImportDeclaration(
3365
+ [],
3366
+ [],
3367
+ ts.factory.createImportClause(false, void 0, namedImports),
3368
+ ts.factory.createStringLiteral(moduleSpecifier)
3369
+ );
3370
+ }
3371
+ function getFieldTypes(fields) {
3372
+ const imports = ["DefaultValues"];
3373
+ const types = fields.map((field) => {
3374
+ if (field.children) {
3375
+ const childrenResult = getFieldTypes(field.children);
3376
+ imports.push(...childrenResult.imports);
3377
+ if (childrenResult.types.length) {
3378
+ const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
3379
+ const childrenPropertySignature = createPropertySignature(
3380
+ "children",
3381
+ subType
3382
+ );
3383
+ const { type: type2, imports: newImports2 } = buildTypeFromField(
3384
+ field,
3385
+ field.isRepeater ? subType : childrenPropertySignature
3386
+ );
3387
+ imports.push(...newImports2);
3388
+ return type2;
3389
+ }
3390
+ }
3391
+ const { type, imports: newImports } = buildTypeFromField(field);
3392
+ imports.push(...newImports);
3393
+ return type;
3394
+ });
3395
+ return { types, imports: Array.from(new Set(imports)) };
3396
+ }
3397
+ function constructFinalType(fields, typeName) {
3398
+ const { types, imports } = getFieldTypes(fields);
3399
+ const importDeclaration = getImportDeclaration(
3400
+ imports,
3401
+ CMS_COMPONENTS_FIELD_TYPES
3402
+ );
3403
+ const baseType = ts.factory.createTypeAliasDeclaration(
3404
+ [],
3405
+ [],
3406
+ "",
3407
+ void 0,
3408
+ ts.factory.createTypeLiteralNode(types)
3409
+ );
3410
+ const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
3411
+ baseType.type
3412
+ ]);
3413
+ const finalType = ts.factory.createTypeAliasDeclaration(
3414
+ [],
3415
+ [],
3416
+ typeName,
3417
+ void 0,
3418
+ wrappedType
3419
+ );
3420
+ const defaultExport = ts.factory.createExportDefault(
3421
+ ts.factory.createIdentifier(typeName)
3422
+ );
3423
+ return [importDeclaration, finalType, defaultExport];
3424
+ }
3425
+ function writeFieldsType(fields, fileName, typeName) {
3426
+ const entries = getFieldEntries(fields);
3427
+ if (!entries) {
3428
+ return false;
3429
+ }
3430
+ try {
3431
+ const file = ts.createSourceFile(
3432
+ fileName,
3433
+ "",
3434
+ ts.ScriptTarget.ESNext,
3435
+ false,
3436
+ ts.ScriptKind.TS
3437
+ );
3438
+ const printer = ts.createPrinter();
3439
+ const nodes = constructFinalType(entries, typeName);
3440
+ const comments = [
3441
+ AUTO_GEN_COMMENT,
3442
+ "Removing the above comment will disable type generation for this module",
3443
+ "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"
3444
+ ].map((comment) => `// ${comment}`);
3445
+ const typeResult = nodes.map(
3446
+ (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)
3447
+ );
3448
+ const result = [...comments, ...typeResult].join("\n");
3449
+ writeFileSync(fileName, result);
3450
+ return true;
3451
+ } catch (e) {
3452
+ console.error(e);
3453
+ return false;
3454
+ }
3455
+ }
3456
+
3457
+ // src/lib/watchFieldsUpdates.ts
3458
+ import fs4 from "fs";
3459
+ import path8 from "path";
3460
+ import readline from "readline";
3461
+ var lastSerializedFieldsCache = {};
3462
+ var formatAsTypeName = (str) => {
3463
+ const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
3464
+ const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
3465
+ return validFirstChar ? typeName : `_${typeName}`;
3466
+ };
3467
+ var isInModulesFolder = (filePath, projectRoot) => {
3468
+ const getEntryPathFromId = (id) => {
3469
+ return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
3470
+ };
3471
+ const currentModuleId = path8.normalize(filePath);
3472
+ const moduleEntryPath = getEntryPathFromId(currentModuleId);
3473
+ const subFolderTokens = moduleEntryPath.split(path8.sep);
3474
+ return {
3475
+ inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
3476
+ isRootModuleFile: subFolderTokens.length === 3
3477
+ };
3478
+ };
3479
+ var fileContainsAutoGenComment = async (filePath) => {
3480
+ if (!fs4.existsSync(filePath))
3481
+ return true;
3482
+ const stream2 = fs4.createReadStream(filePath);
3483
+ const reader = readline.createInterface({ input: stream2 });
3484
+ const firstLine = await new Promise(
3485
+ (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
3486
+ );
3487
+ reader.close();
3488
+ stream2.close();
3489
+ return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
3490
+ };
3491
+ var getIndexFile = (filePath, projectRoot) => {
3492
+ const { inModuleFolder, isRootModuleFile } = isInModulesFolder(
3493
+ filePath,
3494
+ projectRoot
3495
+ );
3496
+ if (!inModuleFolder)
3497
+ return void 0;
3498
+ if (isRootModuleFile)
3499
+ return { indexFilePath: filePath, isRootModuleFile };
3500
+ const dir = path8.dirname(filePath);
3501
+ const files = fs4.readdirSync(dir);
3502
+ const indexFileName = files.find((file) => file.startsWith("index."));
3503
+ return indexFileName ? { indexFilePath: path8.join(dir, indexFileName), isRootModuleFile } : void 0;
3504
+ };
3505
+ var getIndexFileFields = async (indexFilePath, viteServer) => {
3506
+ let indexFile;
3507
+ try {
3508
+ indexFile = await viteServer.ssrLoadModule(indexFilePath);
3509
+ } catch (e) {
3510
+ return void 0;
3511
+ }
3512
+ if (!indexFile.fields)
3513
+ return void 0;
3514
+ const fields = indexFile.fields;
3515
+ const isJsonFields = Array.isArray(fields);
3516
+ const isReactFields = fields.type && fields.type.name === "ModuleFields";
3517
+ if (isJsonFields || isReactFields) {
3518
+ return fields;
3519
+ }
3520
+ return void 0;
3521
+ };
3522
+ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3523
+ const indexInfo = getIndexFile(filePath, projectRoot);
3524
+ if (!indexInfo)
3525
+ return;
3526
+ const { indexFilePath, isRootModuleFile } = indexInfo;
3527
+ const indexFileName = path8.parse(indexFilePath).name;
3528
+ const isTypeFile = filePath.endsWith(".types.ts");
3529
+ if (isTypeFile)
3530
+ return;
3531
+ const fields = await getIndexFileFields(indexFilePath, viteServer);
3532
+ if (fields) {
3533
+ const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
3534
+ const typeFilePath = path8.join(path8.dirname(filePath), typeFileName);
3535
+ const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
3536
+ const serializedFields = JSON.stringify(fields);
3537
+ if (lastSerializedFields === serializedFields)
3538
+ return;
3539
+ const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
3540
+ if (!hasAutoGenComment)
3541
+ return;
3542
+ const moduleFolderName = path8.basename(path8.dirname(filePath));
3543
+ const outputTypeName = formatAsTypeName(moduleFolderName);
3544
+ const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
3545
+ if (didSucceed) {
3546
+ lastSerializedFieldsCache[typeFilePath] = serializedFields;
3547
+ }
3548
+ const pathToLog = isRootModuleFile ? `${moduleFolderName}/${indexFileName}` : moduleFolderName;
3549
+ const successMsg = `Successfully generated types for ${pathToLog}`;
3550
+ const errorMsg = `Failed to generate types for ${pathToLog}`;
3551
+ const message = didSucceed ? successMsg : errorMsg;
3552
+ console.log(wrapMessageInColor(didSucceed ? "green" : "red", message));
3553
+ }
3554
+ };
3555
+ var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
3556
+ const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
3557
+ moduleSubpaths.forEach((modulePath) => {
3558
+ const resolvedPath = path8.resolve(projectRoot, modulePath);
3559
+ maybeUpdateFields(resolvedPath, viteServer, projectRoot);
3560
+ });
3561
+ const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
3562
+ viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
3563
+ };
3564
+
3565
+ // src/createDevServer.ts
3216
3566
  var BASE_PATH = "/";
3217
3567
  var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
3218
3568
  var SHADOW_PORT = 1442;
3219
3569
  var STORYBOOK_PORT = process.env.STORYBOOK_PORT ? parseInt(process.env.STORYBOOK_PORT, 10) : 3123;
3220
- async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2) {
3570
+ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2) {
3221
3571
  let authedPortalId = null;
3222
3572
  let authedEnv = null;
3223
3573
  let jsRenderingGates = [];
@@ -3300,7 +3650,7 @@ Local proxy functionality and module preview routes will not work without settin
3300
3650
  setTrackingInfo(authedPortalId, authedEnv);
3301
3651
  sendTrackingRequest("start-dev-server");
3302
3652
  let domainsToProxy = [];
3303
- if (sslEnabledOption2 && authedPortalId) {
3653
+ if (authedPortalId) {
3304
3654
  try {
3305
3655
  const portalDomains = await fetchWebsiteDomainNames(authedPortalId);
3306
3656
  domainsToProxy = (process.env.DOMAINS_TO_PROXY || "").split(",").filter((d) => !!d);
@@ -3309,9 +3659,12 @@ Local proxy functionality and module preview routes will not work without settin
3309
3659
  if (e instanceof MissingScopeError) {
3310
3660
  logMissingScopeWarning(e);
3311
3661
  } else {
3312
- console.warn(
3313
- `Failed to fetch domains for ${authedPortalId}, HTTPS proxying won't work with them.`
3314
- );
3662
+ const failedDomainFetchMessages = [
3663
+ "Failed to fetch the portal's domains, as a result:",
3664
+ "- HTTPS proxying won't work with them.",
3665
+ "- Proxying to serverless functions won't work."
3666
+ ].map((msg) => wrapMessageInColor("yellow", msg)).join("\n");
3667
+ console.warn(failedDomainFetchMessages);
3315
3668
  }
3316
3669
  }
3317
3670
  }
@@ -3324,7 +3677,7 @@ Local proxy functionality and module preview routes will not work without settin
3324
3677
  } catch (e) {
3325
3678
  authedHublet = "na1";
3326
3679
  }
3327
- const absoluteWebRoot = normalizePath6(path8.resolve(process.cwd(), webRoot2));
3680
+ const absoluteWebRoot = normalizePath6(path9.resolve(process.cwd(), webRoot2));
3328
3681
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
3329
3682
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
3330
3683
  if (authedPortalId) {
@@ -3338,6 +3691,9 @@ Local proxy functionality and module preview routes will not work without settin
3338
3691
  jsRenderingGates,
3339
3692
  secretNames
3340
3693
  );
3694
+ if (fieldGenEnabledOption2) {
3695
+ startFieldsTypeGenWatcher(viteServer, absoluteWebRoot);
3696
+ }
3341
3697
  const viteHTTPSConfig = viteServer.config.server.https;
3342
3698
  const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
3343
3699
  const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
@@ -3398,8 +3754,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3398
3754
  `
3399
3755
  );
3400
3756
  if (storybook2) {
3401
- const packageRoot = path8.dirname(url2.fileURLToPath(import.meta.url));
3402
- const configPath = path8.resolve(packageRoot, "./storybook-main");
3757
+ const packageRoot = path9.dirname(url2.fileURLToPath(import.meta.url));
3758
+ const configPath = path9.resolve(packageRoot, "./storybook-main");
3403
3759
  sendTrackingRequest("start-storybook");
3404
3760
  const storybookProcess = spawn(
3405
3761
  "sb",
@@ -3419,7 +3775,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
3419
3775
  portalId: authedPortalId.toString(),
3420
3776
  hsEnv: authedEnv,
3421
3777
  hublet: authedHublet,
3422
- WEB_ROOT: path8.join(webRoot2, "components")
3778
+ WEB_ROOT: path9.join(webRoot2, "components")
3423
3779
  }
3424
3780
  }
3425
3781
  );
@@ -3465,7 +3821,8 @@ var {
3465
3821
  hubspotCliConfigPathOption,
3466
3822
  hubspotCliAccountNameOption,
3467
3823
  sslEnabledOption,
3468
- storybook
3824
+ storybook,
3825
+ fieldGenEnabledOption
3469
3826
  } = getDevServerCommandLineOptions(process.argv);
3470
3827
  if (!webRoot) {
3471
3828
  throw new Error(`No web root path argument specified`);
@@ -3475,5 +3832,6 @@ createDevServer_default(
3475
3832
  storybook,
3476
3833
  hubspotCliConfigPathOption,
3477
3834
  hubspotCliAccountNameOption,
3478
- sslEnabledOption
3835
+ sslEnabledOption,
3836
+ fieldGenEnabledOption
3479
3837
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "0.15.4",
3
+ "version": "0.15.9",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@hubspot/cli-lib": "^3.0.12",
29
- "@hubspot/cms-components": "^0.15.4",
29
+ "@hubspot/cms-components": "^0.15.9",
30
30
  "@inquirer/select": "^2.0.0",
31
31
  "@originjs/vite-plugin-commonjs": "^1.0.3",
32
32
  "@storybook/addon-actions": "7.0.7",
@@ -108,5 +108,5 @@
108
108
  "publishConfig": {
109
109
  "access": "public"
110
110
  },
111
- "gitHead": "8ce65fb54ad49fb85981578c66878bcce383d39d"
111
+ "gitHead": "cfcc32d943ef0221d9c7a8f191a908538018c583"
112
112
  }