@hubspot/cms-dev-server 1.1.0-prerelease.9 → 1.2.1

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