@hubspot/cms-dev-server 1.1.0-prerelease.8 → 1.2.0

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 (125) hide show
  1. package/dist/app/assets/LexendDeca-Bold-B8uERmr8.woff2 +0 -0
  2. package/dist/app/assets/LexendDeca-Light-BtcvwT5C.woff2 +0 -0
  3. package/dist/app/assets/LexendDeca-Medium-CxVPR2j6.woff2 +0 -0
  4. package/dist/app/assets/LexendDeca-SemiBold-BhzS3XUP.woff2 +0 -0
  5. package/dist/app/assets/index-PcyCbkys.css +1 -0
  6. package/dist/app/assets/index-tvg7JxpD.js +164 -0
  7. package/dist/app/index.html +15 -0
  8. package/dist/app/server/assets/RenderTreeSeparately-T6CL43QJ-D50VfKo0.js +111 -0
  9. package/dist/app/server/serverEntry.js +3641 -0
  10. package/dist/generateJsonFromJsx.js +744 -0
  11. package/dist/html/baseTemplate.html +1 -0
  12. package/dist/index.js +5800 -0
  13. package/dist/internalSsr.js +1312 -0
  14. package/dist/island-runtime.js +267 -0
  15. package/dist/run.js +6495 -4
  16. package/dist/storybook/index.js +241 -0
  17. package/dist/storybook-main/main.js +1457 -0
  18. package/dist/storybook-main/preview.js +21 -0
  19. package/package.json +93 -24
  20. package/types/api/designmanager.d.ts +44 -0
  21. package/types/api/project.d.ts +5 -0
  22. package/types/api/session.d.ts +2 -0
  23. package/types/components/HubLModulesList.d.ts +4 -0
  24. package/types/components/HubLTemplatesList.d.ts +5 -0
  25. package/types/components/ModulesList.d.ts +5 -0
  26. package/types/components/PartialsList.d.ts +4 -0
  27. package/types/createAppServer.d.ts +3 -0
  28. package/types/createDevServer.d.ts +5 -0
  29. package/types/createViteDevServer.d.ts +6 -0
  30. package/types/fileManager.d.ts +4 -0
  31. package/types/index.d.ts +2 -0
  32. package/types/lib/cliUtils.d.ts +15 -0
  33. package/types/lib/configHelpers.d.ts +2 -0
  34. package/types/lib/criticalDevErrorsToServerMessages.d.ts +4 -0
  35. package/types/lib/debug.d.ts +1 -0
  36. package/types/lib/errors.d.ts +6 -0
  37. package/types/lib/fetchModuleGraphQLData.d.ts +24 -0
  38. package/types/lib/fullOriginalUrlFromRequest.d.ts +2 -0
  39. package/types/lib/gates.d.ts +2 -0
  40. package/types/lib/getDevServerUIData.d.ts +60 -0
  41. package/types/lib/getFieldValuesForModule.d.ts +2 -0
  42. package/types/lib/getJSRenderingGates.d.ts +8 -0
  43. package/types/lib/httpsRedirectingServer.d.ts +11 -0
  44. package/types/lib/logColors.d.ts +6 -0
  45. package/types/lib/moduleGraph.d.ts +1 -0
  46. package/types/lib/packagePath.d.ts +1 -0
  47. package/types/lib/pathHelpers.d.ts +3 -0
  48. package/types/lib/previewUtils.d.ts +22 -0
  49. package/types/lib/proxyHelpers.d.ts +29 -0
  50. package/types/lib/renderComponentWithCSS.d.ts +14 -0
  51. package/types/lib/renderHelpers.d.ts +1 -0
  52. package/types/lib/renderModule.d.ts +11 -0
  53. package/types/lib/renderModuleFieldsJson.d.ts +4 -0
  54. package/types/lib/renderModulePreview.d.ts +6 -0
  55. package/types/lib/renderPartial.d.ts +5 -0
  56. package/types/lib/templates.d.ts +4 -0
  57. package/types/lib/trackUsage.d.ts +3 -0
  58. package/types/lib/validateHSPlatform.d.ts +3 -0
  59. package/types/lib/watchFieldsUpdates.d.ts +22 -0
  60. package/types/plugins/cmsComponentsShimPlugin.d.ts +11 -0
  61. package/types/plugins/devSecretsPlugin.d.ts +2 -0
  62. package/types/plugins/hsStaticAssetPlugin.d.ts +2 -0
  63. package/types/proxyPage/constants.d.ts +1 -0
  64. package/types/proxyPage/fetchContentMetadata.d.ts +7 -0
  65. package/types/proxyPage/fetchDomains.d.ts +9 -0
  66. package/types/proxyPage/fetchPreviewInfo.d.ts +7 -0
  67. package/types/proxyPage/proxyPage.d.ts +11 -0
  68. package/types/proxyPage/renderLocalError.d.ts +2 -0
  69. package/types/proxyPage/utils.d.ts +4 -0
  70. package/types/routes/appServerRouteHandler.d.ts +3 -0
  71. package/types/routes/createAppServerAPIRoutes.d.ts +5 -0
  72. package/types/routes/createDevServerRoutes.d.ts +4 -0
  73. package/types/routes/hublModuleRouteHandler.d.ts +2 -0
  74. package/types/routes/hublTemplateRouteHandler.d.ts +2 -0
  75. package/types/routes/legacyRouteHandler.d.ts +3 -0
  76. package/types/routes/linksToAllModulesRouteHandler.d.ts +2 -0
  77. package/types/routes/linksToAllPartialsRouteHandler.d.ts +2 -0
  78. package/types/routes/module.d.ts +3 -0
  79. package/types/routes/moduleFieldsJson.d.ts +3 -0
  80. package/types/routes/modulePreviewRouteHandler.d.ts +3 -0
  81. package/types/routes/partial.d.ts +2 -0
  82. package/types/routes/proxyPageResourceRedirect.d.ts +2 -0
  83. package/types/routes/proxyPageRouteHandler.d.ts +2 -0
  84. package/types/routes/proxyPathPageResourceRedirect.d.ts +2 -0
  85. package/types/routes/proxyPathPageRouteHandler.d.ts +2 -0
  86. package/types/routes/proxyServerlessHandler.d.ts +2 -0
  87. package/types/routes/remoteFsDirtyHandler.d.ts +2 -0
  88. package/types/shadowDevServer/createShadowDevServerRoutes.d.ts +1 -0
  89. package/types/shadowDevServer/startShadowDevServer.d.ts +1 -0
  90. package/types/storybook/getFieldsArgTypes.d.ts +3 -0
  91. package/types/storybook/getNestedFieldObjectForArgs.d.ts +6 -0
  92. package/types/storybook/index.d.ts +1 -0
  93. package/types/storybook/moduleStory.d.ts +5 -0
  94. package/types/storybook/types.d.ts +15 -0
  95. package/dist/components/ModulesList.js +0 -14
  96. package/dist/components/PartialsList.js +0 -13
  97. package/dist/createDevServer.js +0 -26
  98. package/dist/createViteDevServer.js +0 -26
  99. package/dist/lib/argHelpers.js +0 -6
  100. package/dist/lib/cli.js +0 -23
  101. package/dist/lib/fullOriginalUrlFromRequest.js +0 -3
  102. package/dist/lib/htmlHelpers.js +0 -10
  103. package/dist/lib/moduleGraph.js +0 -11
  104. package/dist/lib/proxyHelpers.js +0 -69
  105. package/dist/lib/proxyHelpers.test.js +0 -136
  106. package/dist/lib/renderComponentWithCSS.js +0 -26
  107. package/dist/lib/renderHelpers.js +0 -45
  108. package/dist/lib/renderModule.js +0 -88
  109. package/dist/lib/renderPartial.js +0 -12
  110. package/dist/lib/templates.js +0 -48
  111. package/dist/plugins/devMockClientEntryPlugin.js +0 -52
  112. package/dist/proxyPage/constants.js +0 -4
  113. package/dist/proxyPage/fetchContentMetadata.js +0 -51
  114. package/dist/proxyPage/fetchPreviewInfo.js +0 -37
  115. package/dist/proxyPage/proxyPage.js +0 -167
  116. package/dist/proxyPage/renderLocalError.js +0 -27
  117. package/dist/proxyPage/utils.js +0 -38
  118. package/dist/routes/createDevServerRoutes.js +0 -21
  119. package/dist/routes/homeRouteHandler.js +0 -12
  120. package/dist/routes/linksToAllModulesRouteHandler.js +0 -10
  121. package/dist/routes/linksToAllPartialsRouteHandler.js +0 -10
  122. package/dist/routes/module.js +0 -27
  123. package/dist/routes/partial.js +0 -27
  124. package/dist/routes/proxyPageResourceRedirect.js +0 -12
  125. package/dist/routes/proxyPageRouteHandler.js +0 -40
@@ -0,0 +1,1457 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../cms-js-internal/dist/types-ohevhxjF.js
12
+ import path from "path";
13
+ import { createHash } from "crypto";
14
+ import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
15
+ import { join } from "path/posix";
16
+ function createPreloadLink(assetPath, basePath = "") {
17
+ if (assetPath && assetPath[0] !== "/") {
18
+ assetPath = `/${assetPath}`;
19
+ }
20
+ if (assetPath.endsWith(".js")) {
21
+ return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
22
+ } else if (CSS_LANGS_RE.test(assetPath)) {
23
+ return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
24
+ } else if (assetPath.endsWith(".woff")) {
25
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
26
+ } else if (assetPath.endsWith(".woff2")) {
27
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
28
+ } else if (assetPath.endsWith(".gif")) {
29
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
30
+ } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
31
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
32
+ } else if (assetPath.endsWith(".png")) {
33
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
34
+ } else {
35
+ throw new Error(`Unknown preload type for ${assetPath}`);
36
+ }
37
+ }
38
+ function sortKeys(input, options = {}) {
39
+ const { deep, compare } = options;
40
+ const cache = /* @__PURE__ */ new WeakMap();
41
+ function deepSortArray(array) {
42
+ const resultFromCache = cache.get(array);
43
+ if (resultFromCache !== void 0) {
44
+ return resultFromCache;
45
+ }
46
+ const result = [];
47
+ cache.set(array, result);
48
+ result.push(
49
+ ...array.map((item) => {
50
+ if (Array.isArray(item)) {
51
+ return deepSortArray(item);
52
+ }
53
+ if (isPlainObject(item)) {
54
+ return _sortKeys(item);
55
+ }
56
+ return item;
57
+ })
58
+ );
59
+ return result;
60
+ }
61
+ function _sortKeys(object) {
62
+ const resultFromCache = cache.get(object);
63
+ if (resultFromCache !== void 0) {
64
+ return resultFromCache;
65
+ }
66
+ const result = {};
67
+ const keys = Object.keys(object).sort(compare);
68
+ cache.set(object, result);
69
+ for (const key of keys) {
70
+ const value = object[key];
71
+ let newValue;
72
+ if (deep && Array.isArray(value)) {
73
+ newValue = deepSortArray(value);
74
+ } else {
75
+ newValue = deep && isPlainObject(value) ? _sortKeys(value) : value;
76
+ }
77
+ Object.defineProperty(result, key, {
78
+ ...Object.getOwnPropertyDescriptor(object, key),
79
+ value: newValue
80
+ });
81
+ }
82
+ return result;
83
+ }
84
+ if (Array.isArray(input)) {
85
+ return deep ? deepSortArray(input) : [...input];
86
+ }
87
+ return _sortKeys(input);
88
+ }
89
+ function isPlainObject(value) {
90
+ if (typeof value !== "object" || value === null) {
91
+ return false;
92
+ }
93
+ const prototype = Object.getPrototypeOf(value);
94
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
95
+ }
96
+ function escapeChar(unsafeChar) {
97
+ return inlineJsEscapeChars[unsafeChar];
98
+ }
99
+ function escapeForInlineJS(input) {
100
+ return input.replace(badInlineJsChars, escapeChar);
101
+ }
102
+ function jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent = 2, prettyPrint = true } = {}) {
103
+ const indentString = " ".repeat(baseIndent);
104
+ jsonIndent = prettyPrint ? jsonIndent : void 0;
105
+ let sorted;
106
+ try {
107
+ if (isPlainObject(input) || Array.isArray(input)) {
108
+ sorted = sortKeys(input, { deep: true });
109
+ }
110
+ } catch (e) {
111
+ console.error("Error sorting Island keys", e);
112
+ }
113
+ return escapeForInlineJS(
114
+ JSON.stringify(sorted ?? input, null, jsonIndent)
115
+ ).replace(/\n/gm, `
116
+ ${indentString}`);
117
+ }
118
+ function resolveIslandPlugin(islandsSet) {
119
+ return {
120
+ enforce: "pre",
121
+ name: "resolve-islands",
122
+ configResolved(config) {
123
+ viteRoot = config.root;
124
+ viteCommand = config.command;
125
+ },
126
+ load(id) {
127
+ if (id.endsWith("?island") || id.endsWith("?client")) {
128
+ const [idWithNoParam] = id.split("?");
129
+ const islandModuleImportPath = `${idWithNoParam}?client-entry`;
130
+ const componentExtension = path.extname(idWithNoParam);
131
+ const componentFilenameWithNoExtension = path.basename(
132
+ idWithNoParam,
133
+ componentExtension
134
+ );
135
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
136
+ const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
137
+ if (islandsSet) {
138
+ islandsSet.add(moduleId);
139
+ }
140
+ return `
141
+ const moduleId = '${moduleId}';
142
+
143
+ const lazyComponent = () => import('${islandModuleImportPath}');
144
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
145
+ lazyComponent.moduleId = moduleId;
146
+
147
+ export default lazyComponent;
148
+ `;
149
+ }
150
+ return null;
151
+ }
152
+ };
153
+ }
154
+ function resolveIslandToPlainModulePlugin(enabled = true) {
155
+ return {
156
+ enforce: "pre",
157
+ name: "resolve-islands-to-plain",
158
+ configResolved(config) {
159
+ viteRoot = config.root;
160
+ viteCommand = config.command;
161
+ },
162
+ async resolveId(id, importer, options) {
163
+ if (enabled && (id.endsWith("?island") || id.endsWith("?client"))) {
164
+ const newId = id.replace("?island", "").replace("?client", "");
165
+ const resolution = await this.resolve(newId, importer, {
166
+ skipSelf: true,
167
+ ...options
168
+ });
169
+ if (resolution) {
170
+ return resolution;
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+ };
176
+ }
177
+ function resolveIslandToPlainModuleNoopPlugin() {
178
+ return resolveIslandToPlainModulePlugin(false);
179
+ }
180
+ function clientIslandEntryPlugin() {
181
+ return {
182
+ enforce: "pre",
183
+ name: "client-island-entry-plugin",
184
+ resolveId(id) {
185
+ if (id === virtualClientRenderIslandModuleId) {
186
+ return virtualClientRenderIslandModuleId;
187
+ }
188
+ return null;
189
+ },
190
+ load(id) {
191
+ if (id.endsWith("?client-entry")) {
192
+ const [idWithNoParam] = id.split("?");
193
+ return `
194
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
195
+ import Component from '${idWithNoParam}';
196
+
197
+ export function render(island) {
198
+ return clientRenderIsland(island, Component)
199
+ }
200
+
201
+ export default Component;
202
+ `;
203
+ }
204
+ if (id === virtualClientRenderIslandModuleId) {
205
+ return clientRenderIsland;
206
+ }
207
+ return null;
208
+ }
209
+ };
210
+ }
211
+ function getEntryPointHash(entryPoint) {
212
+ return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
213
+ }
214
+ function getEntryPointHashWithIndexSuffix(entryPoint, index) {
215
+ const renderIndexSuffix = index != null ? `i${index}` : "";
216
+ return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
217
+ }
218
+ function getCombinedReactUrl() {
219
+ const hsEnv = process.env.HS_ENV;
220
+ const fileVersion = hsEnv === "prod" ? `react-combined.mjs` : "react-combined-qa.mjs";
221
+ return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;
222
+ }
223
+ function getIslandRuntimeConfigUrl() {
224
+ const hsEnv = process.env.HS_ENV;
225
+ const fileVersion = hsEnv === "prod" ? `island-runtime.mjs` : "island-runtime-qa.mjs";
226
+ return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;
227
+ }
228
+ function includesHublDataReference(templateSource) {
229
+ const hublDataPattern = /\{%\s+set\s+(experimentalHublData|hublData)\s*=/;
230
+ return !!templateSource.match(hublDataPattern);
231
+ }
232
+ function getCMSAssetConfig(webRoot2) {
233
+ const cmsAssetsPath = path.join(webRoot2, "cms-assets.json");
234
+ const cmsThemePath = path.join(webRoot2, "theme.json");
235
+ const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;
236
+ const parsedConfig = JSON.parse(
237
+ fs.readFileSync(configPathToUse).toString()
238
+ );
239
+ return parsedConfig;
240
+ }
241
+ function getCMSAssetConfigIfExists(webRoot2) {
242
+ try {
243
+ return getCMSAssetConfig(webRoot2);
244
+ } catch (e) {
245
+ console.error(
246
+ `Error finding or parsing cms-assets.json in ${webRoot2}, but ignoring for now`
247
+ );
248
+ return {};
249
+ }
250
+ }
251
+ function areBuildHealthChecksEnabled(config) {
252
+ var _a, _b;
253
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;
254
+ }
255
+ function doHealthChecksFailTheBuild(config) {
256
+ var _a, _b;
257
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;
258
+ }
259
+ function getServerIncludePrebundleDepPatterns(config) {
260
+ var _a, _b;
261
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];
262
+ }
263
+ function getBuildInfo(buildDir) {
264
+ try {
265
+ const buildInfo = JSON.parse(
266
+ readFileSync(path.join(buildDir, BUILD_INFO_PATH)).toString()
267
+ );
268
+ return buildInfo;
269
+ } catch (e) {
270
+ throw new Error(`Error loading build-info.json, path: ${BUILD_INFO_PATH}`);
271
+ }
272
+ }
273
+ function getBaseAssetUrlFromBuild(buildDir) {
274
+ return getBuildInfo(buildDir).baseAssetUrl;
275
+ }
276
+ function isUngatedFor(gates, gate) {
277
+ return gates.includes(gate);
278
+ }
279
+ function ungatedAtBuildTimeFor(buildDir, gate) {
280
+ try {
281
+ const buildInfo = getBuildInfo(buildDir);
282
+ return isUngatedFor(buildInfo.gates, gate);
283
+ } catch (e) {
284
+ return false;
285
+ }
286
+ }
287
+ function findAllModulesInRoot(webRoot2) {
288
+ const allModuleComponents = findAllComponentsIn(
289
+ webRoot2,
290
+ "./components/modules"
291
+ );
292
+ const moduleNames = Object.keys(allModuleComponents).map(
293
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
294
+ );
295
+ const moduleSubpaths = Object.keys(allModuleComponents);
296
+ const moduleExtensions = Object.values(allModuleComponents).map((path22) => {
297
+ if (!path22)
298
+ return "";
299
+ const extension = path22.split(".").pop() || "";
300
+ return extension;
301
+ });
302
+ const moduleNamesWithExtension = Object.values(allModuleComponents).map(
303
+ (path22) => {
304
+ if (!path22)
305
+ return "";
306
+ const file = path22.replace("components/modules/", "");
307
+ return file.includes("/index.") ? file.split("/index.")[0] : file;
308
+ }
309
+ );
310
+ return {
311
+ moduleNames,
312
+ moduleSubpaths,
313
+ moduleNamesWithExtension,
314
+ moduleExtensions
315
+ };
316
+ }
317
+ function findAllPartialsInRoot(webRoot2) {
318
+ const allPartialComponents = findAllComponentsIn(
319
+ webRoot2,
320
+ "./components/partials"
321
+ );
322
+ const partialNames = Object.keys(allPartialComponents).map(
323
+ (partialSubpath) => partialSubpath.replace("components/partials/", "").replace("/index", "")
324
+ );
325
+ const partialSubpaths = Object.keys(allPartialComponents);
326
+ return { partialNames, partialSubpaths };
327
+ }
328
+ function namespaceModulePropsShape(props) {
329
+ const {
330
+ dataQueryResult,
331
+ hublParameters,
332
+ fieldValues: passedFieldValues,
333
+ hublData,
334
+ experimentalHublData,
335
+ moduleName,
336
+ supplementalFieldValues
337
+ } = props;
338
+ const oldPropsShape = { ...props };
339
+ if (oldPropsShape.dataQueryResult) {
340
+ delete oldPropsShape.dataQueryResult;
341
+ }
342
+ if (oldPropsShape.hublParameters) {
343
+ delete oldPropsShape.hublParameters;
344
+ }
345
+ const fieldValues = passedFieldValues || oldPropsShape;
346
+ return {
347
+ ...fieldValues,
348
+ dataQueryResult,
349
+ fieldValues,
350
+ hublParameters,
351
+ hublData,
352
+ experimentalHublData,
353
+ moduleName,
354
+ supplementalFieldValues
355
+ };
356
+ }
357
+ function setIn(object, nestedKeysArray, value) {
358
+ let curr = object;
359
+ const finalKey = nestedKeysArray.pop();
360
+ for (let index = 0; index < nestedKeysArray.length; index++) {
361
+ const currentKey = nestedKeysArray[index];
362
+ const nextKey = nestedKeysArray[index + 1];
363
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
364
+ if (curr[currentKey] === void 0) {
365
+ curr[currentKey] = [];
366
+ }
367
+ }
368
+ if (curr[currentKey] === void 0) {
369
+ curr[currentKey] = {};
370
+ }
371
+ curr = curr[currentKey];
372
+ }
373
+ if (value !== void 0) {
374
+ curr[finalKey] = value;
375
+ }
376
+ }
377
+ function isStylesheetAsset(staticAsset) {
378
+ return staticAsset.type === "stylesheet";
379
+ }
380
+ var COMPONENT_EXTENSIONS, ENTRY_POINTS_PATH, MODULE_FOLDER_PATH, TEMPLATE_FOLDER_PATH, VIRTUAL_ISLAND_RUNTIME, VIRTUAL_CONFIG_SETUP, CSS_LANGS_RE, collectCssModules, collectCssInDev, badInlineJsChars, inlineJsEscapeChars, viteRoot, viteCommand, clientRenderIsland, virtualClientRenderIslandModuleId, scriptTagToLogServerMessages, getComponentExtension, hasComponentExtension, isStorybookStory, removeComponentExtension, COMBINED_REACT_BASE_PATH, ISLAND_RUNTIME_CONFIG_BASE_PATH, removeIndexFromPath, removeIndexOrTrailingJsFromPath, HEALTHCHECKS_ENABLED_DEFAULT, HEALTHCHECKS_STRICT_DEFAULT, BUILD_INFO_PATH, GATES, ENABLED_FEATURES_GATE_MAP, findAllComponentsIn;
381
+ var init_types_ohevhxjF = __esm({
382
+ "../cms-js-internal/dist/types-ohevhxjF.js"() {
383
+ COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
384
+ ENTRY_POINTS_PATH = "components/partials/";
385
+ MODULE_FOLDER_PATH = "components/modules/";
386
+ TEMPLATE_FOLDER_PATH = "components/templates/";
387
+ VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
388
+ VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
389
+ CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
390
+ collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
391
+ const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
392
+ modulePathToStartWith
393
+ );
394
+ if (!appModulesForPath || appModulesForPath.size === 0) {
395
+ throw new Error(`No modules at: ${modulePathToStartWith}`);
396
+ } else if (appModulesForPath.size > 1) {
397
+ throw new Error(`More than one module at: ${modulePathToStartWith}`);
398
+ }
399
+ const appModule = Array.from(appModulesForPath.values())[0];
400
+ const allServerSideModulesImported = /* @__PURE__ */ new Set();
401
+ const newCssModules = [];
402
+ const moduleQueue = Array.from(appModule.importedModules);
403
+ for (const importedModule of moduleQueue) {
404
+ if (allServerSideModulesImported.has(importedModule.id)) {
405
+ continue;
406
+ }
407
+ allServerSideModulesImported.add(importedModule.id);
408
+ const isCss = CSS_LANGS_RE.test(importedModule.file);
409
+ const moduleModulesToQueue = Array.from(importedModule.importedModules);
410
+ if (isCss && !cssModulesImported.has(importedModule)) {
411
+ cssModulesImported.add(importedModule);
412
+ newCssModules.push(importedModule);
413
+ }
414
+ moduleQueue.push(...moduleModulesToQueue);
415
+ }
416
+ return newCssModules;
417
+ };
418
+ collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
419
+ return `${collectCssModules(
420
+ modulePathToStartWith,
421
+ viteServer,
422
+ cssModulesImported
423
+ ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
424
+ `;
425
+ };
426
+ badInlineJsChars = /[\u2028\u2029<>/]/g;
427
+ inlineJsEscapeChars = {
428
+ "\u2028": "\\u2028",
429
+ "\u2029": "\\u2029",
430
+ "<": "\\u003C",
431
+ ">": "\\u003E",
432
+ "/": "\\u002F"
433
+ };
434
+ 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";
435
+ virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
436
+ scriptTagToLogServerMessages = (messagesForBrowser, groupLabel, nonceAttribute) => {
437
+ if (!messagesForBrowser) {
438
+ return "";
439
+ }
440
+ const consoleLines = [];
441
+ for (const message of messagesForBrowser) {
442
+ let funcString = "console.log";
443
+ if (message.level === "error") {
444
+ funcString = "console.error";
445
+ }
446
+ if (message.level === "warn") {
447
+ funcString = "console.warn";
448
+ }
449
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
450
+ consoleLines.push(` ${funcString}(${argString});`);
451
+ }
452
+ let groupStart = "";
453
+ let groupEnd = "";
454
+ if (groupLabel !== void 0 && groupLabel !== null) {
455
+ groupStart = `
456
+ console.group(${JSON.stringify(groupLabel)});`;
457
+ groupEnd = ` console.groupEnd()
458
+ `;
459
+ }
460
+ return `<script ${nonceAttribute}>${groupStart}
461
+ ${consoleLines.join("\n")}
462
+ ${groupEnd}</script>
463
+ `;
464
+ };
465
+ getComponentExtension = (componentPath) => {
466
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
467
+ (ext) => componentPath.endsWith(ext)
468
+ );
469
+ if (filteredExtensions.length === 1) {
470
+ return filteredExtensions[0];
471
+ }
472
+ return void 0;
473
+ };
474
+ hasComponentExtension = (componentPath) => {
475
+ return !!getComponentExtension(componentPath);
476
+ };
477
+ isStorybookStory = (componentPath) => {
478
+ return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
479
+ };
480
+ removeComponentExtension = (componentPath) => {
481
+ const ext = getComponentExtension(componentPath);
482
+ if (ext == null) {
483
+ return componentPath;
484
+ }
485
+ return componentPath.slice(0, -1 * ext.length);
486
+ };
487
+ COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
488
+ ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
489
+ removeIndexFromPath = (id) => {
490
+ return id.replace(/\/index\.[jt]sx?$/, "");
491
+ };
492
+ removeIndexOrTrailingJsFromPath = (id) => {
493
+ return removeIndexFromPath(id).replace(/\.[jt]sx?$/, "");
494
+ };
495
+ HEALTHCHECKS_ENABLED_DEFAULT = true;
496
+ HEALTHCHECKS_STRICT_DEFAULT = false;
497
+ BUILD_INFO_PATH = "/build-info.json";
498
+ GATES = [
499
+ "CMS:JSRenderer:GetServerSideProps",
500
+ "CMS:JSRenderer:ModuleHubl",
501
+ "CMS:JSRenderer:RemoveCjsPlugin",
502
+ "CMS:JSRenderer:RemoveMockClientEntryPlugin",
503
+ "CMS:JSRenderer:AnalyzeCmsModules"
504
+ ];
505
+ ENABLED_FEATURES_GATE_MAP = {
506
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
507
+ "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
508
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
509
+ };
510
+ findAllComponentsIn = (webRoot2, componentsFolder) => {
511
+ const fullComponentsFolderPath = join(webRoot2, componentsFolder);
512
+ const componentsByName = {};
513
+ if (!existsSync(fullComponentsFolderPath)) {
514
+ return componentsByName;
515
+ }
516
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
517
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
518
+ const subdirPath = join(componentsFolder, fileOrFolderName);
519
+ const isDirectory = lstatSync(fullPath).isDirectory();
520
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
521
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
522
+ componentsByName[subdirPathNoExtension] = subdirPath;
523
+ } else if (isDirectory) {
524
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
525
+ const potentialIndexModule = join(
526
+ subdirPath,
527
+ `index${potentialExtension}`
528
+ );
529
+ const fullPotentialPath = join(
530
+ fullPath,
531
+ `index${potentialExtension}`
532
+ );
533
+ if (existsSync(fullPotentialPath)) {
534
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
535
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
536
+ break;
537
+ }
538
+ }
539
+ }
540
+ });
541
+ return componentsByName;
542
+ };
543
+ }
544
+ });
545
+
546
+ // ../cms-js-internal/dist/index.js
547
+ var dist_exports = {};
548
+ __export(dist_exports, {
549
+ COMPONENT_EXTENSIONS: () => COMPONENT_EXTENSIONS,
550
+ CSS_LANGS_RE: () => CSS_LANGS_RE,
551
+ DndAreaSlot: () => DndAreaSlot,
552
+ ENABLED_FEATURES_GATE_MAP: () => ENABLED_FEATURES_GATE_MAP,
553
+ ENTRY_POINTS_PATH: () => ENTRY_POINTS_PATH,
554
+ GATES: () => GATES,
555
+ GlobalPartialSlot: () => GlobalPartialSlot,
556
+ MODULE_FOLDER_PATH: () => MODULE_FOLDER_PATH,
557
+ ModuleSlot: () => ModuleSlot,
558
+ TEMPLATE_FOLDER_PATH: () => TEMPLATE_FOLDER_PATH,
559
+ VIRTUAL_CONFIG_SETUP: () => VIRTUAL_CONFIG_SETUP,
560
+ VIRTUAL_ISLAND_RUNTIME: () => VIRTUAL_ISLAND_RUNTIME,
561
+ areBuildHealthChecksEnabled: () => areBuildHealthChecksEnabled,
562
+ clientIslandEntryPlugin: () => clientIslandEntryPlugin,
563
+ collectCssInDev: () => collectCssInDev,
564
+ collectCssModules: () => collectCssModules,
565
+ createIslandsGlobalJsForClientInDev: () => createIslandsGlobalJsForClientInDev,
566
+ doHealthChecksFailTheBuild: () => doHealthChecksFailTheBuild,
567
+ escapeForInlineJS: () => escapeForInlineJS,
568
+ findAllComponentsIn: () => findAllComponentsIn,
569
+ findAllModulesInRoot: () => findAllModulesInRoot,
570
+ findAllPartialsInRoot: () => findAllPartialsInRoot,
571
+ findCmsModules: () => findCmsModules,
572
+ getBaseAssetUrlFromBuild: () => getBaseAssetUrlFromBuild,
573
+ getBuildInfo: () => getBuildInfo,
574
+ getCMSAssetConfig: () => getCMSAssetConfig,
575
+ getCMSAssetConfigIfExists: () => getCMSAssetConfigIfExists,
576
+ getCombinedReactUrl: () => getCombinedReactUrl,
577
+ getComponentExtension: () => getComponentExtension,
578
+ getEntryPointHash: () => getEntryPointHash,
579
+ getEntryPointHashWithIndexSuffix: () => getEntryPointHashWithIndexSuffix,
580
+ getIslandRuntimeConfigUrl: () => getIslandRuntimeConfigUrl,
581
+ getIslandUrls: () => getIslandUrls,
582
+ getServerGlobalsToInject: () => getServerGlobalsToInject,
583
+ getServerIncludePrebundleDepPatterns: () => getServerIncludePrebundleDepPatterns,
584
+ hasComponentExtension: () => hasComponentExtension,
585
+ includesHublDataReference: () => includesHublDataReference,
586
+ isStorybookStory: () => isStorybookStory,
587
+ isStylesheetAsset: () => isStylesheetAsset,
588
+ isUngatedFor: () => isUngatedFor,
589
+ jsonStringifyAndEscapeForInlineJS: () => jsonStringifyAndEscapeForInlineJS,
590
+ namespaceModulePropsShape: () => namespaceModulePropsShape,
591
+ noncePlaceholderPlugin: () => noncePlaceholderPlugin,
592
+ removeComponentExtension: () => removeComponentExtension,
593
+ removeIndexFromPath: () => removeIndexFromPath,
594
+ removeIndexOrTrailingJsFromPath: () => removeIndexOrTrailingJsFromPath,
595
+ renderComponentOnServer: () => renderComponentOnServer,
596
+ renderFieldsToJson: () => renderFieldsToJson,
597
+ renderOnServer: () => renderOnServer,
598
+ renderStreamToPromise: () => renderStreamToPromise,
599
+ resolveIslandPlugin: () => resolveIslandPlugin,
600
+ resolveIslandToPlainModuleNoopPlugin: () => resolveIslandToPlainModuleNoopPlugin,
601
+ resolveIslandToPlainModulePlugin: () => resolveIslandToPlainModulePlugin,
602
+ scriptTagToLogServerMessages: () => scriptTagToLogServerMessages,
603
+ serializeIslandDataForInlineScript: () => serializeIslandDataForInlineScript,
604
+ setIn: () => setIn,
605
+ ungatedAtBuildTimeFor: () => ungatedAtBuildTimeFor,
606
+ virtualClientRenderIslandModuleId: () => virtualClientRenderIslandModuleId
607
+ });
608
+ import * as dotProp from "dot-prop";
609
+ import * as parser from "@babel/parser";
610
+ import _traverse from "@babel/traverse";
611
+ import * as t from "@babel/types";
612
+ import { jsx } from "react/jsx-runtime";
613
+ import stream from "stream";
614
+ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
615
+ import * as cmsComponents from "@hubspot/cms-components";
616
+ import { ServerRenderContext } from "@hubspot/cms-components";
617
+ import { isValidElement, cloneElement } from "react";
618
+ function filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {
619
+ if (!supplementalFieldValues) {
620
+ return supplementalFieldValues;
621
+ }
622
+ if (!supplementalFieldValuesRead) {
623
+ return supplementalFieldValues;
624
+ }
625
+ const result = {};
626
+ Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {
627
+ if (hasProperty(supplementalFieldValues, fieldPath)) {
628
+ setProperty(
629
+ result,
630
+ fieldPath,
631
+ getProperty(supplementalFieldValues, fieldPath)
632
+ );
633
+ }
634
+ });
635
+ return result;
636
+ }
637
+ function getIslandUrls(roots, viteDevServer) {
638
+ return roots.map((island) => {
639
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
640
+ island.moduleId
641
+ );
642
+ if (!islandModule) {
643
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
644
+ }
645
+ let wrapperModule;
646
+ if (island.wrapperModuleId) {
647
+ wrapperModule = viteDevServer.moduleGraph.getModuleById(
648
+ island.wrapperModuleId
649
+ );
650
+ }
651
+ const tweakedIsland = {
652
+ ...island,
653
+ url: islandModule.url,
654
+ wrapperUrl: wrapperModule ? wrapperModule.url : void 0
655
+ };
656
+ return tweakedIsland;
657
+ });
658
+ }
659
+ function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
660
+ if (!perServerRequestData.has("sharedStateIDs")) {
661
+ return new Map(perServerRequestData);
662
+ }
663
+ const perServerRequestDataWithUrls = new Map(
664
+ perServerRequestData
665
+ );
666
+ perServerRequestData.get("sharedStateIDs").forEach((id) => {
667
+ const reducer = perServerRequestData.get(id);
668
+ if (reducer.reducerFuncModuleId) {
669
+ const reducerWithUrl = {
670
+ ...reducer,
671
+ reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(
672
+ reducer.reducerFuncModuleId
673
+ ).url
674
+ };
675
+ perServerRequestDataWithUrls.set(id, reducerWithUrl);
676
+ }
677
+ });
678
+ return perServerRequestDataWithUrls;
679
+ }
680
+ function noncePlaceholderPlugin() {
681
+ const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
682
+ return {
683
+ name: "hs-nonce-placeholder",
684
+ enforce: "post",
685
+ apply() {
686
+ return HS_DEPLOYED;
687
+ },
688
+ transformIndexHtml(html) {
689
+ const regex = /<(style|script|link) (.*)>/gi;
690
+ const replacer = (_, p1, p2) => {
691
+ if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
692
+ p1 === "link" && p2.includes('rel="stylesheet"')) {
693
+ const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
694
+ p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
695
+ }
696
+ return `<${p1} ${p2}>`;
697
+ };
698
+ return html.replace(regex, replacer);
699
+ }
700
+ };
701
+ }
702
+ function findCmsModules(buildContentDescriptors = {}) {
703
+ let config;
704
+ return {
705
+ enforce: "pre",
706
+ name: "findCmsModules",
707
+ configResolved(resolvedConfig) {
708
+ config = resolvedConfig;
709
+ },
710
+ transform(code, id) {
711
+ const moduleInfo = this.getModuleInfo(id);
712
+ if (!shouldAnalyzeModule(config, moduleInfo, code))
713
+ return null;
714
+ const contentDescriptors = analyzeSourceCodeUsages(
715
+ this,
716
+ moduleInfo,
717
+ config,
718
+ code
719
+ );
720
+ if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
721
+ return {
722
+ meta: {
723
+ findCmsModules: contentDescriptors
724
+ }
725
+ };
726
+ }
727
+ },
728
+ buildEnd(error) {
729
+ if (error)
730
+ throw error;
731
+ const entryPoints = getEntryPoints(this, config);
732
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
733
+ this,
734
+ entryPoints
735
+ );
736
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
737
+ config,
738
+ entryPointCmsModuleMap
739
+ );
740
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
741
+ this,
742
+ entryPoints
743
+ );
744
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
745
+ config,
746
+ entryPointIslandCmsModuleMap
747
+ );
748
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
749
+ this.error(`
750
+ Error: <Module /> cannot be used within <Island />
751
+ Found invalid usages:
752
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
753
+ `);
754
+ }
755
+ const modulesWithinModules = filterEntryPointsToModules(
756
+ relativeEntryPointCmsModuleMap
757
+ );
758
+ if (Object.keys(modulesWithinModules).length > 0) {
759
+ this.error(`
760
+ Error: <Module /> can only be used in React Partials
761
+ Found invalid usages:
762
+ ${JSON.stringify(modulesWithinModules, null, 2)}
763
+ `);
764
+ }
765
+ Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
766
+ }
767
+ };
768
+ }
769
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
770
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
771
+ ([entryPointPath, cmsModules]) => {
772
+ return [toRelativePath(config, entryPointPath), cmsModules];
773
+ }
774
+ );
775
+ return Object.fromEntries(relativeEntries);
776
+ }
777
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
778
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
779
+ ([entryPointPath, islandContentDescriptors]) => {
780
+ const islandCmsModuleUsage = Object.fromEntries(
781
+ Object.entries(islandContentDescriptors).map(
782
+ ([islandPath, contentDescriptors]) => {
783
+ return [
784
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
785
+ contentDescriptors
786
+ ];
787
+ }
788
+ )
789
+ );
790
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
791
+ }
792
+ );
793
+ return Object.fromEntries(relativeEntries);
794
+ }
795
+ function toRelativePath(config, path3) {
796
+ return path3.replace(`${config.root}/`, "");
797
+ }
798
+ function shouldAnalyzeModule(config, moduleInfo, code) {
799
+ const [fileId, __] = moduleInfo.id.split("?");
800
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
801
+ return (
802
+ // analyze customer code only
803
+ !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
804
+ (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
805
+ );
806
+ }
807
+ function getEntryPoints(ctx, config) {
808
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
809
+ }
810
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
811
+ const entryPointCmsModuleUsage = {};
812
+ for (const entryPoint of entryPoints) {
813
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
814
+ if (result) {
815
+ entryPointCmsModuleUsage[entryPoint.id] = result;
816
+ }
817
+ }
818
+ return entryPointCmsModuleUsage;
819
+ }
820
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
821
+ const entryPointIslandsCmsModuleMap = {};
822
+ for (const entryPoint of entryPoints) {
823
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
824
+ if (result) {
825
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
826
+ }
827
+ }
828
+ return entryPointIslandsCmsModuleMap;
829
+ }
830
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
831
+ const sourceAst = parser.parse(code, {
832
+ sourceType: "module",
833
+ plugins: ["jsx", "typescript"]
834
+ });
835
+ const contentDescriptors = { modules: {}, dndAreas: {} };
836
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
837
+ let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
838
+ traverse(sourceAst, {
839
+ ImportDeclaration(path3) {
840
+ if (t.isStringLiteral(path3.node.source, {
841
+ value: "@hubspot/cms-components"
842
+ })) {
843
+ for (const specifier of path3.node.specifiers) {
844
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
845
+ name: CMS_MODULE_COMPONENT_NAME
846
+ })) {
847
+ moduleComponentLocalImportName = specifier.local.name;
848
+ }
849
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
850
+ name: DND_AREA_COMPONENT_NAME
851
+ })) {
852
+ dndAreaComponentLocalImportName = specifier.local.name;
853
+ }
854
+ }
855
+ }
856
+ },
857
+ JSXOpeningElement(path3) {
858
+ if (t.isJSXIdentifier(path3.node.name, {
859
+ name: moduleComponentLocalImportName
860
+ })) {
861
+ let cmsModuleName;
862
+ let cmsModulePath;
863
+ let cmsModuleLabel;
864
+ for (const prop of path3.node.attributes) {
865
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
866
+ cmsModuleName = prop.value.value;
867
+ continue;
868
+ }
869
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
870
+ cmsModulePath = prop.value.value;
871
+ continue;
872
+ }
873
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
874
+ cmsModuleLabel = prop.value.value;
875
+ continue;
876
+ }
877
+ ctx.error(
878
+ new Error(
879
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
880
+ )
881
+ );
882
+ }
883
+ const cmsModuleProps = {
884
+ name: cmsModuleName,
885
+ path: cmsModulePath
886
+ };
887
+ if (cmsModuleLabel) {
888
+ cmsModuleProps.label = cmsModuleLabel;
889
+ }
890
+ if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
891
+ ctx.error(
892
+ new Error(
893
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
894
+ )
895
+ );
896
+ }
897
+ contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
898
+ }
899
+ if (t.isJSXIdentifier(path3.node.name, {
900
+ name: dndAreaComponentLocalImportName
901
+ })) {
902
+ let dndAreaName;
903
+ for (const prop of path3.node.attributes) {
904
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
905
+ dndAreaName = prop.value.value;
906
+ continue;
907
+ }
908
+ ctx.error(
909
+ new Error(
910
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
911
+ )
912
+ );
913
+ }
914
+ const dndArea = {
915
+ name: dndAreaName
916
+ };
917
+ if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
918
+ ctx.error(
919
+ new Error(
920
+ `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
921
+ )
922
+ );
923
+ }
924
+ contentDescriptors.dndAreas[dndArea.name] = dndArea;
925
+ }
926
+ }
927
+ });
928
+ return contentDescriptors;
929
+ }
930
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
931
+ if (Object.hasOwn(result, moduleId)) {
932
+ return result[moduleId];
933
+ }
934
+ const moduleInfo = ctx.getModuleInfo(moduleId);
935
+ let entryPointContentDescriptors = null;
936
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
937
+ entryPointContentDescriptors = {
938
+ ...entryPointContentDescriptors,
939
+ ...moduleInfo.meta[PLUGIN_NAME]
940
+ };
941
+ }
942
+ for (const importedId of [
943
+ ...moduleInfo.importedIds,
944
+ ...moduleInfo.dynamicallyImportedIds
945
+ ]) {
946
+ if (processed.has(importedId)) {
947
+ continue;
948
+ }
949
+ const importedResult = findCmsModuleUsages(
950
+ ctx,
951
+ importedId,
952
+ processed,
953
+ result
954
+ );
955
+ if (importedResult) {
956
+ entryPointContentDescriptors = {
957
+ ...entryPointContentDescriptors,
958
+ ...importedResult
959
+ };
960
+ }
961
+ }
962
+ if (entryPointContentDescriptors) {
963
+ result[moduleId] = entryPointContentDescriptors;
964
+ }
965
+ processed.add(moduleId);
966
+ return entryPointContentDescriptors;
967
+ }
968
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
969
+ processedIslands.add(moduleId);
970
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
971
+ return islandModuleResults[moduleId];
972
+ }
973
+ const moduleInfo = ctx.getModuleInfo(moduleId);
974
+ let resultForModuleId = {};
975
+ if (moduleInfo.id.endsWith("?client-entry")) {
976
+ const mergedDataDependencies = findCmsModuleUsages(
977
+ ctx,
978
+ moduleInfo.id,
979
+ processed,
980
+ results
981
+ );
982
+ if (mergedDataDependencies) {
983
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
984
+ }
985
+ }
986
+ for (const importedId of [
987
+ ...moduleInfo.importedIds,
988
+ ...moduleInfo.dynamicallyImportedIds
989
+ ]) {
990
+ if (processedIslands.has(importedId)) {
991
+ continue;
992
+ }
993
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
994
+ ctx,
995
+ importedId,
996
+ processedIslands,
997
+ islandModuleResults,
998
+ processed,
999
+ results
1000
+ );
1001
+ if (importerCmsModuleUsageResult) {
1002
+ resultForModuleId = {
1003
+ ...resultForModuleId,
1004
+ ...importerCmsModuleUsageResult
1005
+ };
1006
+ }
1007
+ }
1008
+ if (Object.keys(resultForModuleId).length > 0) {
1009
+ islandModuleResults[moduleId] = resultForModuleId;
1010
+ return resultForModuleId;
1011
+ }
1012
+ return null;
1013
+ }
1014
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
1015
+ return Object.fromEntries(
1016
+ Object.entries(entryPointCmsModuleMap).filter(
1017
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
1018
+ )
1019
+ );
1020
+ }
1021
+ async function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {
1022
+ const { props } = propsAndDeps;
1023
+ const componentDebugName = Component.displayName || Component.name;
1024
+ const supplementalFieldValues = contextOptions == null ? void 0 : contextOptions.supplementalFieldValues;
1025
+ const messagesForBrowser = contextOptions == null ? void 0 : contextOptions.messagesForBrowser;
1026
+ const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
1027
+ environmentConfig,
1028
+ entryPointBasePath,
1029
+ supplementalFieldValues,
1030
+ messagesForBrowser
1031
+ }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);
1032
+ if (getServerSideProps !== void 0 && typeof getServerSideProps === "function") {
1033
+ const gSSPResult = await renderServerSidePropsWithAsyncLocalStoreContext(
1034
+ getServerSideProps,
1035
+ propsAndDeps,
1036
+ renderContext
1037
+ );
1038
+ if (gSSPResult) {
1039
+ props.serverSideProps = gSSPResult.serverSideProps;
1040
+ }
1041
+ }
1042
+ return renderOnServer(
1043
+ /* @__PURE__ */ jsx(Component, { ...props }),
1044
+ renderContext,
1045
+ componentDebugName,
1046
+ renderOptions
1047
+ );
1048
+ }
1049
+ async function renderOnServer(elements, renderContext = bootStrapRenderContext(), debugName, renderOptions) {
1050
+ let html = await renderStreamToPromise(
1051
+ /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }),
1052
+ renderOptions
1053
+ );
1054
+ if (renderContext.messagesForBrowser.length > 0) {
1055
+ html = `${html}${scriptTagToLogServerMessages(
1056
+ renderContext.messagesForBrowser,
1057
+ `Server messages rendering: ${debugName}`
1058
+ )}`;
1059
+ }
1060
+ return { html, renderContext };
1061
+ }
1062
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
1063
+ if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
1064
+ prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
1065
+ }
1066
+ const serializedJson = jsonStringifyAndEscapeForInlineJS(
1067
+ environmentConfig.toJSON(),
1068
+ { baseIndent: 6, prettyPrint }
1069
+ );
1070
+ const globals = [`window.__hsEnvConfig = ${serializedJson};`];
1071
+ if (hsServerPageUrl) {
1072
+ globals.push(
1073
+ `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(
1074
+ hsServerPageUrl
1075
+ )};`
1076
+ );
1077
+ }
1078
+ if (hsBasePath) {
1079
+ globals.push(
1080
+ `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`
1081
+ );
1082
+ }
1083
+ if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {
1084
+ const firstCriticalDevError = criticalDevErrors[0];
1085
+ globals.push(`
1086
+ customElements.whenDefined('vite-error-overlay').then(() => {
1087
+ const ErrorOverlay = customElements.get('vite-error-overlay');
1088
+ const error = new Error(${jsonStringifyAndEscapeForInlineJS(
1089
+ firstCriticalDevError.message
1090
+ )});
1091
+ const overlay = new ErrorOverlay(error);
1092
+
1093
+ document.body.appendChild(overlay);
1094
+ })
1095
+ `);
1096
+ }
1097
+ const nonceAttr = includeNonces && cmsComponents.SCRIPT_NONCE_PLACEHOLDER ? ` nonce="${cmsComponents.SCRIPT_NONCE_PLACEHOLDER}"` : "";
1098
+ return `
1099
+ <script type="text/javascript"${nonceAttr}>
1100
+ ${globals.join("\n ")}
1101
+ </script>
1102
+ `;
1103
+ }
1104
+ function renderFieldsJSX(fieldsJSX) {
1105
+ let moduleJson;
1106
+ const outputCallback = (callbackJson) => {
1107
+ moduleJson = callbackJson;
1108
+ };
1109
+ renderToStaticMarkup(
1110
+ cloneElement(fieldsJSX, {
1111
+ outputCallback
1112
+ })
1113
+ );
1114
+ if (!moduleJson) {
1115
+ throw new Error("couldn't render module fields definition to fields.json");
1116
+ }
1117
+ return moduleJson;
1118
+ }
1119
+ function renderFieldsToJson(fields, moduleName) {
1120
+ let fieldsJSON;
1121
+ try {
1122
+ if (isValidElement(fields)) {
1123
+ fieldsJSON = renderFieldsJSX(fields);
1124
+ } else if (Array.isArray(fields)) {
1125
+ fieldsJSON = fields;
1126
+ } else {
1127
+ throw new Error(
1128
+ `Couldn't recognize \`fields\` value for module ${moduleName}`
1129
+ );
1130
+ }
1131
+ return fieldsJSON;
1132
+ } catch (e2) {
1133
+ e2.message = `Error when rendering fields for ${moduleName}: ${e2.message}`;
1134
+ throw e2;
1135
+ }
1136
+ }
1137
+ function DndAreaSlot(props) {
1138
+ return /* @__PURE__ */ jsx(
1139
+ "div",
1140
+ {
1141
+ suppressHydrationWarning: true,
1142
+ dangerouslySetInnerHTML: {
1143
+ __html: `<!-- hs-dnd-area-placeholder-${props.name} -->`
1144
+ }
1145
+ }
1146
+ );
1147
+ }
1148
+ function ModuleSlot(props) {
1149
+ return /* @__PURE__ */ jsx(
1150
+ "div",
1151
+ {
1152
+ suppressHydrationWarning: true,
1153
+ dangerouslySetInnerHTML: {
1154
+ __html: `<!-- hs-module-placeholder-${props.name} -->`
1155
+ }
1156
+ }
1157
+ );
1158
+ }
1159
+ function GlobalPartialSlot(props) {
1160
+ return /* @__PURE__ */ jsx(
1161
+ "div",
1162
+ {
1163
+ suppressHydrationWarning: true,
1164
+ dangerouslySetInnerHTML: {
1165
+ __html: `<!-- hs-global-partial-placeholder-${props.name} -->`
1166
+ }
1167
+ }
1168
+ );
1169
+ }
1170
+ var setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, traverse, CMS_MODULE_COMPONENT_NAME, DND_AREA_COMPONENT_NAME, PLUGIN_NAME, promiseForNewWritableStream, renderStreamToPromise, createServerRenderContextV22, createServerRenderContext2, renderServerSidePropsWithAsyncLocalStoreContext, bootStrapRenderContext;
1171
+ var init_dist = __esm({
1172
+ "../cms-js-internal/dist/index.js"() {
1173
+ init_types_ohevhxjF();
1174
+ init_types_ohevhxjF();
1175
+ ({ setProperty, getProperty, hasProperty } = dotProp);
1176
+ serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
1177
+ const islandsArrayToSerialize = tweakedIslandsArray.map(
1178
+ ({
1179
+ id,
1180
+ moduleName,
1181
+ moduleId,
1182
+ props,
1183
+ hydrateOn,
1184
+ clientOnly,
1185
+ priority,
1186
+ url,
1187
+ sharedStateID,
1188
+ supplementalFieldValues,
1189
+ wrapperModuleId,
1190
+ wrapperUrl,
1191
+ resolvedDataDependencies
1192
+ }) => {
1193
+ const output = {
1194
+ id,
1195
+ moduleName,
1196
+ moduleId,
1197
+ hydrateOn,
1198
+ clientOnly,
1199
+ priority,
1200
+ props,
1201
+ url
1202
+ };
1203
+ if (resolvedDataDependencies) {
1204
+ output.resolvedDataDependencies = resolvedDataDependencies;
1205
+ }
1206
+ if (sharedStateID) {
1207
+ output.sharedStateID = sharedStateID;
1208
+ }
1209
+ if (wrapperModuleId) {
1210
+ output.wrapperModuleId = wrapperModuleId;
1211
+ }
1212
+ if (wrapperUrl) {
1213
+ output.wrapperUrl = wrapperUrl;
1214
+ }
1215
+ const filteredSupplementalFieldValues = filterOutUnreadSupplementalFieldValues(
1216
+ supplementalFieldValues,
1217
+ perServerRequestData.get("supplementalFieldValuesRead")
1218
+ );
1219
+ if (filteredSupplementalFieldValues) {
1220
+ output.supplementalFieldValues = filteredSupplementalFieldValues;
1221
+ }
1222
+ if (output.clientOnly) {
1223
+ output.supplementalFieldValues = supplementalFieldValues;
1224
+ }
1225
+ return output;
1226
+ }
1227
+ );
1228
+ return jsonStringifyAndEscapeForInlineJS(islandsArrayToSerialize, {
1229
+ baseIndent,
1230
+ jsonIndent: 2,
1231
+ prettyPrint
1232
+ });
1233
+ };
1234
+ writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0, prettyPrint) => {
1235
+ const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x2) => !!x2);
1236
+ if (sharedStateIDs.length > 0) {
1237
+ const indentString = " ".repeat(indent);
1238
+ const stateByID = {};
1239
+ sharedStateIDs.forEach(
1240
+ (id) => stateByID[id] = perServerRequestData.get(id)
1241
+ );
1242
+ const stringifiedState = jsonStringifyAndEscapeForInlineJS(stateByID, {
1243
+ prettyPrint,
1244
+ jsonIndent: 2
1245
+ });
1246
+ return `
1247
+
1248
+ var newState = ${stringifiedState};
1249
+ if(window.__hsSSInit) {
1250
+ window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
1251
+ } else {
1252
+ window.__hsSSInit = newState;
1253
+ }`.replace(/\n/gm, `
1254
+ ${indentString}`);
1255
+ }
1256
+ return "";
1257
+ };
1258
+ createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
1259
+ const islands = getIslandUrls(roots, viteDevServer);
1260
+ const perServerRequestDataWithUrls = getPerServerRequestUrls(
1261
+ perServerRequestData,
1262
+ viteDevServer
1263
+ );
1264
+ return `${" ".repeat(
1265
+ indent
1266
+ )}window.__islands = ${serializeIslandDataForInlineScript(
1267
+ islands,
1268
+ perServerRequestData,
1269
+ indent,
1270
+ prettyPrint
1271
+ )}${writeSharedStateToJsGlobal(
1272
+ islands,
1273
+ perServerRequestDataWithUrls,
1274
+ indent,
1275
+ prettyPrint
1276
+ )}`;
1277
+ };
1278
+ traverse = _traverse.default;
1279
+ CMS_MODULE_COMPONENT_NAME = "Module";
1280
+ DND_AREA_COMPONENT_NAME = "DndArea";
1281
+ PLUGIN_NAME = "findCmsModules";
1282
+ promiseForNewWritableStream = () => {
1283
+ const chunks = [];
1284
+ const writableStream = new stream.Writable();
1285
+ writableStream._write = (chunk, encoding, done) => {
1286
+ chunks.push(Buffer.from(chunk));
1287
+ done();
1288
+ };
1289
+ const streamDonePromise = new Promise((resolve, reject) => {
1290
+ writableStream.on("error", (error) => {
1291
+ reject(error);
1292
+ });
1293
+ writableStream._final = (done) => {
1294
+ resolve(Buffer.concat(chunks).toString("utf8"));
1295
+ done();
1296
+ };
1297
+ });
1298
+ return { streamDonePromise, writableStream };
1299
+ };
1300
+ renderStreamToPromise = async (reactElements, options) => {
1301
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
1302
+ const {
1303
+ pipe
1304
+ /* abort */
1305
+ } = renderToPipeableStream(reactElements, {
1306
+ ...options || {},
1307
+ onShellReady() {
1308
+ },
1309
+ onAllReady() {
1310
+ pipe(writableStream);
1311
+ if (options == null ? void 0 : options.onAllReady) {
1312
+ options.onAllReady();
1313
+ }
1314
+ }
1315
+ });
1316
+ return streamDonePromise;
1317
+ };
1318
+ ({
1319
+ createServerRenderContextV2: createServerRenderContextV22,
1320
+ createServerRenderContext: createServerRenderContext2,
1321
+ renderServerSidePropsWithAsyncLocalStoreContext
1322
+ } = cmsComponents);
1323
+ bootStrapRenderContext = () => {
1324
+ const renderContext = createServerRenderContextV22 ? createServerRenderContextV22(null, {
1325
+ environmentConfig: null,
1326
+ entryPointBasePath: "",
1327
+ supplementalFieldValues: {},
1328
+ messagesForBrowser: []
1329
+ }) : createServerRenderContext2("", null);
1330
+ return renderContext;
1331
+ };
1332
+ }
1333
+ });
1334
+
1335
+ // src/storybook-main/main.ts
1336
+ init_dist();
1337
+ import path2 from "path";
1338
+ import { createRequire } from "module";
1339
+ import { mergeConfig } from "vite";
1340
+ import { withoutVitePlugins } from "@storybook/builder-vite";
1341
+ import { default as react } from "@vitejs/plugin-react";
1342
+ var webRoot = process.env.WEB_ROOT;
1343
+ var storyPath = path2.resolve(process.cwd(), webRoot, "**/*.stories.*");
1344
+ var jsRenderingGates = process.env.GATES ? process.env.GATES.split(",") : [];
1345
+ var main_default = {
1346
+ addons: ["@storybook/addon-essentials"],
1347
+ framework: "@storybook/react-vite",
1348
+ stories: [storyPath],
1349
+ previewHead: (head) => {
1350
+ return `
1351
+ ${head}
1352
+
1353
+ <script type="module">
1354
+ import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
1355
+
1356
+ initConfigSingletonFromJSON(${jsonStringifyAndEscapeForInlineJS(
1357
+ {
1358
+ portalId: process.env.portalId,
1359
+ hublet: process.env.hublet,
1360
+ hsEnv: process.env.hsEnv,
1361
+ hsDeployed: false,
1362
+ hsJSRGates: jsRenderingGates
1363
+ },
1364
+ { prettyPrint: false }
1365
+ )})
1366
+ </script>
1367
+
1368
+ `;
1369
+ },
1370
+ viteFinal: async (config) => {
1371
+ const { resolveIslandPlugin: resolveIslandPlugin2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
1372
+ const viteConfig = {
1373
+ define: {
1374
+ global: "globalThis",
1375
+ "process.env": "{}",
1376
+ "process.platform": '"browser"',
1377
+ "process.version": '"v18.0.0"',
1378
+ "process.versions": "{}",
1379
+ "process.browser": "true",
1380
+ "process.nextTick": "((fn, ...args) => setTimeout(() => fn(...args), 0))"
1381
+ },
1382
+ resolve: {
1383
+ dedupe: [
1384
+ "react",
1385
+ "react-dom",
1386
+ "@hubspot/cms-components",
1387
+ "@hubspot/cms-dev-server"
1388
+ ],
1389
+ alias: {
1390
+ process: "process/browser",
1391
+ buffer: "buffer"
1392
+ }
1393
+ },
1394
+ optimizeDeps: {
1395
+ include: ["react", "react-dom", "react-dom/client", "buffer"],
1396
+ exclude: ["fsevents"]
1397
+ },
1398
+ css: {
1399
+ postcss: webRoot
1400
+ },
1401
+ plugins: [
1402
+ // Provide Node.js globals for browser environment
1403
+ {
1404
+ name: "provide-nodejs-globals",
1405
+ config(__config, { command }) {
1406
+ if (command === "serve") {
1407
+ config.define = config.define || {};
1408
+ config.define.global = "globalThis";
1409
+ config.define.Buffer = "Buffer";
1410
+ }
1411
+ },
1412
+ transformIndexHtml: {
1413
+ order: "pre",
1414
+ handler(html) {
1415
+ return html.replace(
1416
+ "<head>",
1417
+ `<head>
1418
+ <script type="module">
1419
+ import { Buffer } from 'buffer';
1420
+ window.Buffer = Buffer;
1421
+ globalThis.Buffer = Buffer;
1422
+ </script>`
1423
+ );
1424
+ }
1425
+ }
1426
+ },
1427
+ resolveIslandPlugin2(),
1428
+ (() => {
1429
+ const require2 = createRequire(import.meta.url);
1430
+ return react({
1431
+ babel: {
1432
+ plugins: [
1433
+ require2.resolve("babel-plugin-styled-components"),
1434
+ require2.resolve("styled-jsx/babel"),
1435
+ require2.resolve("babel-plugin-macros")
1436
+ ]
1437
+ }
1438
+ });
1439
+ })()
1440
+ ]
1441
+ };
1442
+ const configNoReact = {
1443
+ ...config,
1444
+ // replacing the default usage of `@vite/plugin-react` (it emits multiple
1445
+ // sub-plugins listed here) to add our babel plugin configuration
1446
+ plugins: await withoutVitePlugins(config.plugins, [
1447
+ "vite:react-babel",
1448
+ "vite:react-swc",
1449
+ "vite:react-refresh"
1450
+ ])
1451
+ };
1452
+ return mergeConfig(configNoReact, viteConfig);
1453
+ }
1454
+ };
1455
+ export {
1456
+ main_default as default
1457
+ };