@hubspot/cms-dev-server 0.14.5 → 0.14.6

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.
@@ -8,63 +8,11 @@ var __export = (target, all) => {
8
8
  __defProp(target, name, { get: all[name], enumerable: true });
9
9
  };
10
10
 
11
- // ../cms-js-internal/dist/index.js
12
- var dist_exports = {};
13
- __export(dist_exports, {
14
- COMPONENT_EXTENSIONS: () => COMPONENT_EXTENSIONS,
15
- CSS_LANGS_RE: () => CSS_LANGS_RE,
16
- ENABLED_FEATURES_GATE_MAP: () => ENABLED_FEATURES_GATE_MAP,
17
- ENTRY_POINTS_PATH: () => ENTRY_POINTS_PATH,
18
- GATES: () => GATES,
19
- MODULE_FOLDER_PATH: () => MODULE_FOLDER_PATH,
20
- VIRTUAL_CONFIG_SETUP: () => VIRTUAL_CONFIG_SETUP,
21
- VIRTUAL_ISLAND_RUNTIME: () => VIRTUAL_ISLAND_RUNTIME,
22
- clientIslandEntryPlugin: () => clientIslandEntryPlugin,
23
- collectCssInDev: () => collectCssInDev,
24
- collectCssModules: () => collectCssModules,
25
- createIslandsGlobalJsForClientInDev: () => createIslandsGlobalJsForClientInDev,
26
- escapeForInlineJS: () => escapeForInlineJS,
27
- findAllComponentsIn: () => findAllComponentsIn,
28
- findAllModulesInRoot: () => findAllModulesInRoot,
29
- findAllPartialsInRoot: () => findAllPartialsInRoot,
30
- getCombinedReactUrl: () => getCombinedReactUrl,
31
- getComponentExtension: () => getComponentExtension,
32
- getEntryPointHash: () => getEntryPointHash,
33
- getEntryPointHashWithIndexSuffix: () => getEntryPointHashWithIndexSuffix,
34
- getIslandRuntimeConfigUrl: () => getIslandRuntimeConfigUrl,
35
- getIslandUrls: () => getIslandUrls,
36
- getServerGlobalsToInject: () => getServerGlobalsToInject,
37
- hasComponentExtension: () => hasComponentExtension,
38
- includesHublDataReference: () => includesHublDataReference,
39
- isStorybookStory: () => isStorybookStory,
40
- isStylesheetAsset: () => isStylesheetAsset,
41
- isUngatedFor: () => isUngatedFor,
42
- jsonStringifyAndEscapeForInlineJS: () => jsonStringifyAndEscapeForInlineJS,
43
- namespaceModulePropsShape: () => namespaceModulePropsShape,
44
- noncePlaceholderPlugin: () => noncePlaceholderPlugin,
45
- removeComponentExtension: () => removeComponentExtension,
46
- renderComponentOnServer: () => renderComponentOnServer,
47
- renderFieldsToJson: () => renderFieldsToJson,
48
- renderOnServer: () => renderOnServer,
49
- renderStreamToPromise: () => renderStreamToPromise,
50
- resolveIslandPlugin: () => resolveIslandPlugin,
51
- scriptTagToLogServerMessages: () => scriptTagToLogServerMessages,
52
- serializeIslandDataForInlineScript: () => serializeIslandDataForInlineScript,
53
- setIn: () => setIn,
54
- ungatedAtBuildTimeFor: () => ungatedAtBuildTimeFor,
55
- virtualClientRenderIslandModuleId: () => virtualClientRenderIslandModuleId
56
- });
57
- import * as dotProp from "dot-prop";
11
+ // ../cms-js-internal/dist/basicUtils.js
58
12
  import path from "path";
59
- import * as jsxRuntime from "react/jsx-runtime";
60
- import stream from "stream";
61
- import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
62
- import * as cmsComponents from "@hubspot/cms-components";
63
- import { ServerRenderContext } from "@hubspot/cms-components";
64
13
  import { createHash } from "crypto";
65
- import { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
14
+ import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
66
15
  import { join } from "path/posix";
67
- import { isValidElement, cloneElement } from "react";
68
16
  function createPreloadLink(assetPath, basePath = "") {
69
17
  if (assetPath && assetPath[0] !== "/") {
70
18
  assetPath = `/${assetPath}`;
@@ -102,68 +50,6 @@ function jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent =
102
50
  ${indentString}`
103
51
  );
104
52
  }
105
- function filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {
106
- if (!supplementalFieldValues) {
107
- return supplementalFieldValues;
108
- }
109
- if (!supplementalFieldValuesRead) {
110
- return supplementalFieldValues;
111
- }
112
- const result = {};
113
- Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {
114
- if (hasProperty(supplementalFieldValues, fieldPath)) {
115
- setProperty(
116
- result,
117
- fieldPath,
118
- getProperty(supplementalFieldValues, fieldPath)
119
- );
120
- }
121
- });
122
- return result;
123
- }
124
- function getIslandUrls(roots, viteDevServer) {
125
- return roots.map((island) => {
126
- const islandModule = viteDevServer.moduleGraph.getModuleById(
127
- island.moduleId
128
- );
129
- if (!islandModule) {
130
- throw new Error(`Unknown island moduleId: ${island.moduleId}`);
131
- }
132
- let wrapperModule;
133
- if (island.wrapperModuleId) {
134
- wrapperModule = viteDevServer.moduleGraph.getModuleById(
135
- island.wrapperModuleId
136
- );
137
- }
138
- const tweakedIsland = {
139
- ...island,
140
- url: islandModule.url,
141
- wrapperUrl: wrapperModule ? wrapperModule.url : void 0
142
- };
143
- return tweakedIsland;
144
- });
145
- }
146
- function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
147
- if (!perServerRequestData.has("sharedStateIDs")) {
148
- return new Map(perServerRequestData);
149
- }
150
- const perServerRequestDataWithUrls = new Map(
151
- perServerRequestData
152
- );
153
- perServerRequestData.get("sharedStateIDs").forEach((id) => {
154
- const reducer = perServerRequestData.get(id);
155
- if (reducer.reducerFuncModuleId) {
156
- const reducerWithUrl = {
157
- ...reducer,
158
- reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(
159
- reducer.reducerFuncModuleId
160
- ).url
161
- };
162
- perServerRequestDataWithUrls.set(id, reducerWithUrl);
163
- }
164
- });
165
- return perServerRequestDataWithUrls;
166
- }
167
53
  function resolveIslandPlugin(islandsSet) {
168
54
  return {
169
55
  enforce: "pre",
@@ -200,28 +86,32 @@ function resolveIslandPlugin(islandsSet) {
200
86
  }
201
87
  };
202
88
  }
203
- function noncePlaceholderPlugin() {
204
- const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
89
+ function resolveIslandToPlainModulePlugin(enabled = true) {
205
90
  return {
206
- name: "hs-nonce-placeholder",
207
- enforce: "post",
208
- apply() {
209
- return HS_DEPLOYED;
91
+ enforce: "pre",
92
+ name: "resolve-islands-to-plain",
93
+ configResolved(config) {
94
+ viteRoot = config.root;
95
+ viteCommand = config.command;
210
96
  },
211
- transformIndexHtml(html) {
212
- const regex = /<(style|script|link) (.*)>/gi;
213
- const replacer = (_, p1, p2) => {
214
- if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
215
- p1 === "link" && p2.includes('rel="stylesheet"')) {
216
- const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
217
- p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
97
+ async resolveId(id, importer, options) {
98
+ if (enabled && (id.endsWith("?island") || id.endsWith("?client"))) {
99
+ const newId = id.replace("?island", "").replace("?client", "");
100
+ const resolution = await this.resolve(newId, importer, {
101
+ skipSelf: true,
102
+ ...options
103
+ });
104
+ if (resolution) {
105
+ return resolution;
218
106
  }
219
- return `<${p1} ${p2}>`;
220
- };
221
- return html.replace(regex, replacer);
107
+ }
108
+ return null;
222
109
  }
223
110
  };
224
111
  }
112
+ function resolveIslandToPlainModuleNoopPlugin() {
113
+ return resolveIslandToPlainModulePlugin(false);
114
+ }
225
115
  function clientIslandEntryPlugin() {
226
116
  return {
227
117
  enforce: "pre",
@@ -253,37 +143,6 @@ function clientIslandEntryPlugin() {
253
143
  }
254
144
  };
255
145
  }
256
- async function renderComponentOnServer(Component, props, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions) {
257
- const componentDebugName = Component.displayName || Component.name;
258
- return renderOnServer(
259
- /* @__PURE__ */ jsx2(Component, { ...props }),
260
- pageUrl,
261
- environmentConfig,
262
- entryPointBasePath,
263
- contextOptions,
264
- componentDebugName,
265
- renderOptions
266
- );
267
- }
268
- async function renderOnServer(elements, pageUrl, environmentConfig, entryPointBasePath, contextOptions, debugName, renderOptions) {
269
- const supplementalFieldValues = contextOptions ? contextOptions.supplementalFieldValues : void 0;
270
- const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
271
- environmentConfig,
272
- entryPointBasePath,
273
- supplementalFieldValues
274
- }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);
275
- let html = await renderStreamToPromise(
276
- /* @__PURE__ */ jsx2(ServerRenderContext.Provider, { value: renderContext, children: elements }),
277
- renderOptions
278
- );
279
- if (renderContext.messagesForBrowser.length > 0) {
280
- html = `${html}${scriptTagToLogServerMessages(
281
- renderContext.messagesForBrowser,
282
- `Server messages rendering: ${debugName}`
283
- )}`;
284
- }
285
- return { html, renderContext };
286
- }
287
146
  function getEntryPointHash(entryPoint) {
288
147
  return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
289
148
  }
@@ -305,6 +164,32 @@ function includesHublDataReference(templateSource) {
305
164
  const hublDataPattern = /\{%\s+set\s+(experimentalHublData|hublData)\s*=/;
306
165
  return !!templateSource.match(hublDataPattern);
307
166
  }
167
+ function getCMSAssetConfig(webRoot2) {
168
+ const cmsAssetsPath = path.join(webRoot2, "cms-assets.json");
169
+ return JSON.parse(fs.readFileSync(cmsAssetsPath).toString());
170
+ }
171
+ function getCMSAssetConfigIfExists(webRoot2) {
172
+ try {
173
+ return getCMSAssetConfig(webRoot2);
174
+ } catch (e) {
175
+ console.error(
176
+ `Error finding or parsing cms-assets.json in ${webRoot2}, but ignoring for now`
177
+ );
178
+ return {};
179
+ }
180
+ }
181
+ function areBuildHealthChecksEnabled(config) {
182
+ var _a, _b;
183
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;
184
+ }
185
+ function doHealthChecksFailTheBuild(config) {
186
+ var _a, _b;
187
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;
188
+ }
189
+ function getServerIncludePrebundleDepPatterns(config) {
190
+ var _a, _b;
191
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];
192
+ }
308
193
  function isUngatedFor(gates, gate) {
309
194
  return gates.includes(gate);
310
195
  }
@@ -342,48 +227,6 @@ function findAllPartialsInRoot(webRoot2) {
342
227
  const partialSubpaths = Object.keys(allPartialComponents);
343
228
  return { partialNames, partialSubpaths };
344
229
  }
345
- function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
346
- if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
347
- prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
348
- }
349
- const serializedJson = jsonStringifyAndEscapeForInlineJS(
350
- environmentConfig.toJSON(),
351
- { baseIndent: 6, prettyPrint }
352
- );
353
- const globals = [`window.__hsEnvConfig = ${serializedJson};`];
354
- if (hsServerPageUrl) {
355
- globals.push(
356
- `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(
357
- hsServerPageUrl
358
- )};`
359
- );
360
- }
361
- if (hsBasePath) {
362
- globals.push(
363
- `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`
364
- );
365
- }
366
- if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {
367
- const firstCriticalDevError = criticalDevErrors[0];
368
- globals.push(`
369
- customElements.whenDefined('vite-error-overlay').then(() => {
370
- const ErrorOverlay = customElements.get('vite-error-overlay');
371
- const error = new Error(${jsonStringifyAndEscapeForInlineJS(
372
- firstCriticalDevError.message
373
- )});
374
- const overlay = new ErrorOverlay(error);
375
-
376
- document.body.appendChild(overlay);
377
- })
378
- `);
379
- }
380
- const nonceAttr = includeNonces && cmsComponents.STYLE_NONCE_PLACEHOLDER ? ` nonce="${cmsComponents.STYLE_NONCE_PLACEHOLDER}"` : "";
381
- return `
382
- <script type="text/javascript"${nonceAttr}>
383
- ${globals.join("\n ")}
384
- </script>
385
- `;
386
- }
387
230
  function namespaceModulePropsShape(props) {
388
231
  const {
389
232
  dataQueryResult,
@@ -433,45 +276,12 @@ function setIn(object, nestedKeysArray, value) {
433
276
  curr[finalKey] = value;
434
277
  }
435
278
  }
436
- function renderFieldsJSX(fieldsJSX) {
437
- let moduleJson;
438
- const outputCallback = (callbackJson) => {
439
- moduleJson = callbackJson;
440
- };
441
- renderToStaticMarkup(
442
- cloneElement(fieldsJSX, {
443
- outputCallback
444
- })
445
- );
446
- if (!moduleJson) {
447
- throw new Error("couldn't render module fields definition to fields.json");
448
- }
449
- return moduleJson;
450
- }
451
- function renderFieldsToJson(fields, moduleName) {
452
- let fieldsJSON;
453
- try {
454
- if (isValidElement(fields)) {
455
- fieldsJSON = renderFieldsJSX(fields);
456
- } else if (Array.isArray(fields)) {
457
- fieldsJSON = fields;
458
- } else {
459
- throw new Error(
460
- `Couldn't recognize \`fields\` value for module ${moduleName}`
461
- );
462
- }
463
- return fieldsJSON;
464
- } catch (e) {
465
- e.message = `Error when rendering fields for ${moduleName}: ${e.message}`;
466
- throw e;
467
- }
468
- }
469
279
  function isStylesheetAsset(staticAsset) {
470
280
  return staticAsset.type === "stylesheet";
471
281
  }
472
- var COMPONENT_EXTENSIONS, ENTRY_POINTS_PATH, MODULE_FOLDER_PATH, VIRTUAL_ISLAND_RUNTIME, VIRTUAL_CONFIG_SETUP, CSS_LANGS_RE, collectCssModules, collectCssInDev, badInlineJsChars, inlineJsEscapeChars, setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, viteRoot, viteCommand, clientRenderIsland, virtualClientRenderIslandModuleId, jsx2, promiseForNewWritableStream, renderStreamToPromise, scriptTagToLogServerMessages, getComponentExtension, hasComponentExtension, isStorybookStory, removeComponentExtension, COMBINED_REACT_BASE_PATH, ISLAND_RUNTIME_CONFIG_BASE_PATH, GATES, ENABLED_FEATURES_GATE_MAP, BUILD_INFO_PATH, findAllComponentsIn;
473
- var init_dist = __esm({
474
- "../cms-js-internal/dist/index.js"() {
282
+ var COMPONENT_EXTENSIONS, ENTRY_POINTS_PATH, MODULE_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, GATES, ENABLED_FEATURES_GATE_MAP, BUILD_INFO_PATH, findAllComponentsIn;
283
+ var init_basicUtils = __esm({
284
+ "../cms-js-internal/dist/basicUtils.js"() {
475
285
  COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
476
286
  ENTRY_POINTS_PATH = "components/partials/";
477
287
  MODULE_FOLDER_PATH = "components/modules/";
@@ -522,6 +332,373 @@ var init_dist = __esm({
522
332
  ">": "\\u003E",
523
333
  "/": "\\u002F"
524
334
  };
335
+ 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";
336
+ virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
337
+ scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
338
+ if (!messagesForBrowser) {
339
+ return "";
340
+ }
341
+ const consoleLines = [];
342
+ for (const message of messagesForBrowser) {
343
+ let funcString = "console.log";
344
+ if (message.level === "error") {
345
+ funcString = "console.error";
346
+ }
347
+ if (message.level === "warn") {
348
+ funcString = "console.warn";
349
+ }
350
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
351
+ consoleLines.push(` ${funcString}(${argString});`);
352
+ }
353
+ let groupStart = "";
354
+ let groupEnd = "";
355
+ if (groupLabel !== void 0 && groupLabel !== null) {
356
+ groupStart = `
357
+ console.group(${JSON.stringify(groupLabel)});`;
358
+ groupEnd = ` console.groupEnd()
359
+ `;
360
+ }
361
+ return `<script>${groupStart}
362
+ ${consoleLines.join("\n")}
363
+ ${groupEnd}</script>
364
+ `;
365
+ };
366
+ getComponentExtension = (componentPath) => {
367
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
368
+ (ext) => componentPath.endsWith(ext)
369
+ );
370
+ if (filteredExtensions.length === 1) {
371
+ return filteredExtensions[0];
372
+ }
373
+ return void 0;
374
+ };
375
+ hasComponentExtension = (componentPath) => {
376
+ return !!getComponentExtension(componentPath);
377
+ };
378
+ isStorybookStory = (componentPath) => {
379
+ return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
380
+ };
381
+ removeComponentExtension = (componentPath) => {
382
+ const ext = getComponentExtension(componentPath);
383
+ if (ext == null) {
384
+ return componentPath;
385
+ }
386
+ return componentPath.slice(0, -1 * ext.length);
387
+ };
388
+ COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
389
+ ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
390
+ removeIndexFromPath = (id) => {
391
+ return id.replace(/\/index\.[jt]sx?$/, "");
392
+ };
393
+ removeIndexOrTrailingJsFromPath = (id) => {
394
+ return removeIndexFromPath(id).replace(/\.[jt]sx?$/, "");
395
+ };
396
+ HEALTHCHECKS_ENABLED_DEFAULT = true;
397
+ HEALTHCHECKS_STRICT_DEFAULT = false;
398
+ GATES = [
399
+ "CMS:JSRenderer:GetServerSideProps",
400
+ "CMS:JSRenderer:ModuleHubl",
401
+ "CMS:JSRenderer:RemoveCjsPlugin",
402
+ "CMS:JSRenderer:RemoveMockClientEntryPlugin"
403
+ ];
404
+ ENABLED_FEATURES_GATE_MAP = {
405
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
406
+ "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin"
407
+ };
408
+ BUILD_INFO_PATH = "/build-info.json";
409
+ findAllComponentsIn = (webRoot2, componentsFolder) => {
410
+ const fullComponentsFolderPath = join(webRoot2, componentsFolder);
411
+ const componentsByName = {};
412
+ if (!existsSync(fullComponentsFolderPath)) {
413
+ return componentsByName;
414
+ }
415
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
416
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
417
+ const subdirPath = join(componentsFolder, fileOrFolderName);
418
+ const isDirectory = lstatSync(fullPath).isDirectory();
419
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
420
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
421
+ componentsByName[subdirPathNoExtension] = subdirPath;
422
+ } else if (isDirectory) {
423
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
424
+ const potentialIndexModule = join(
425
+ subdirPath,
426
+ `index${potentialExtension}`
427
+ );
428
+ const fullPotentialPath = join(
429
+ fullPath,
430
+ `index${potentialExtension}`
431
+ );
432
+ if (existsSync(fullPotentialPath)) {
433
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
434
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
435
+ break;
436
+ }
437
+ }
438
+ }
439
+ });
440
+ return componentsByName;
441
+ };
442
+ }
443
+ });
444
+
445
+ // ../cms-js-internal/dist/index.js
446
+ var dist_exports = {};
447
+ __export(dist_exports, {
448
+ COMPONENT_EXTENSIONS: () => COMPONENT_EXTENSIONS,
449
+ CSS_LANGS_RE: () => CSS_LANGS_RE,
450
+ ENABLED_FEATURES_GATE_MAP: () => ENABLED_FEATURES_GATE_MAP,
451
+ ENTRY_POINTS_PATH: () => ENTRY_POINTS_PATH,
452
+ GATES: () => GATES,
453
+ MODULE_FOLDER_PATH: () => MODULE_FOLDER_PATH,
454
+ VIRTUAL_CONFIG_SETUP: () => VIRTUAL_CONFIG_SETUP,
455
+ VIRTUAL_ISLAND_RUNTIME: () => VIRTUAL_ISLAND_RUNTIME,
456
+ areBuildHealthChecksEnabled: () => areBuildHealthChecksEnabled,
457
+ clientIslandEntryPlugin: () => clientIslandEntryPlugin,
458
+ collectCssInDev: () => collectCssInDev,
459
+ collectCssModules: () => collectCssModules,
460
+ createIslandsGlobalJsForClientInDev: () => createIslandsGlobalJsForClientInDev,
461
+ doHealthChecksFailTheBuild: () => doHealthChecksFailTheBuild,
462
+ escapeForInlineJS: () => escapeForInlineJS,
463
+ findAllComponentsIn: () => findAllComponentsIn,
464
+ findAllModulesInRoot: () => findAllModulesInRoot,
465
+ findAllPartialsInRoot: () => findAllPartialsInRoot,
466
+ getCMSAssetConfig: () => getCMSAssetConfig,
467
+ getCMSAssetConfigIfExists: () => getCMSAssetConfigIfExists,
468
+ getCombinedReactUrl: () => getCombinedReactUrl,
469
+ getComponentExtension: () => getComponentExtension,
470
+ getEntryPointHash: () => getEntryPointHash,
471
+ getEntryPointHashWithIndexSuffix: () => getEntryPointHashWithIndexSuffix,
472
+ getIslandRuntimeConfigUrl: () => getIslandRuntimeConfigUrl,
473
+ getIslandUrls: () => getIslandUrls,
474
+ getServerGlobalsToInject: () => getServerGlobalsToInject,
475
+ getServerIncludePrebundleDepPatterns: () => getServerIncludePrebundleDepPatterns,
476
+ hasComponentExtension: () => hasComponentExtension,
477
+ includesHublDataReference: () => includesHublDataReference,
478
+ isStorybookStory: () => isStorybookStory,
479
+ isStylesheetAsset: () => isStylesheetAsset,
480
+ isUngatedFor: () => isUngatedFor,
481
+ jsonStringifyAndEscapeForInlineJS: () => jsonStringifyAndEscapeForInlineJS,
482
+ namespaceModulePropsShape: () => namespaceModulePropsShape,
483
+ noncePlaceholderPlugin: () => noncePlaceholderPlugin,
484
+ removeComponentExtension: () => removeComponentExtension,
485
+ removeIndexFromPath: () => removeIndexFromPath,
486
+ removeIndexOrTrailingJsFromPath: () => removeIndexOrTrailingJsFromPath,
487
+ renderComponentOnServer: () => renderComponentOnServer,
488
+ renderFieldsToJson: () => renderFieldsToJson,
489
+ renderOnServer: () => renderOnServer,
490
+ renderStreamToPromise: () => renderStreamToPromise,
491
+ resolveIslandPlugin: () => resolveIslandPlugin,
492
+ resolveIslandToPlainModuleNoopPlugin: () => resolveIslandToPlainModuleNoopPlugin,
493
+ resolveIslandToPlainModulePlugin: () => resolveIslandToPlainModulePlugin,
494
+ scriptTagToLogServerMessages: () => scriptTagToLogServerMessages,
495
+ serializeIslandDataForInlineScript: () => serializeIslandDataForInlineScript,
496
+ setIn: () => setIn,
497
+ ungatedAtBuildTimeFor: () => ungatedAtBuildTimeFor,
498
+ virtualClientRenderIslandModuleId: () => virtualClientRenderIslandModuleId
499
+ });
500
+ import * as dotProp from "dot-prop";
501
+ import * as jsxRuntime from "react/jsx-runtime";
502
+ import stream from "stream";
503
+ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
504
+ import * as cmsComponents from "@hubspot/cms-components";
505
+ import { ServerRenderContext } from "@hubspot/cms-components";
506
+ import { isValidElement, cloneElement } from "react";
507
+ function filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {
508
+ if (!supplementalFieldValues) {
509
+ return supplementalFieldValues;
510
+ }
511
+ if (!supplementalFieldValuesRead) {
512
+ return supplementalFieldValues;
513
+ }
514
+ const result = {};
515
+ Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {
516
+ if (hasProperty(supplementalFieldValues, fieldPath)) {
517
+ setProperty(
518
+ result,
519
+ fieldPath,
520
+ getProperty(supplementalFieldValues, fieldPath)
521
+ );
522
+ }
523
+ });
524
+ return result;
525
+ }
526
+ function getIslandUrls(roots, viteDevServer) {
527
+ return roots.map((island) => {
528
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
529
+ island.moduleId
530
+ );
531
+ if (!islandModule) {
532
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
533
+ }
534
+ let wrapperModule;
535
+ if (island.wrapperModuleId) {
536
+ wrapperModule = viteDevServer.moduleGraph.getModuleById(
537
+ island.wrapperModuleId
538
+ );
539
+ }
540
+ const tweakedIsland = {
541
+ ...island,
542
+ url: islandModule.url,
543
+ wrapperUrl: wrapperModule ? wrapperModule.url : void 0
544
+ };
545
+ return tweakedIsland;
546
+ });
547
+ }
548
+ function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
549
+ if (!perServerRequestData.has("sharedStateIDs")) {
550
+ return new Map(perServerRequestData);
551
+ }
552
+ const perServerRequestDataWithUrls = new Map(
553
+ perServerRequestData
554
+ );
555
+ perServerRequestData.get("sharedStateIDs").forEach((id) => {
556
+ const reducer = perServerRequestData.get(id);
557
+ if (reducer.reducerFuncModuleId) {
558
+ const reducerWithUrl = {
559
+ ...reducer,
560
+ reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(
561
+ reducer.reducerFuncModuleId
562
+ ).url
563
+ };
564
+ perServerRequestDataWithUrls.set(id, reducerWithUrl);
565
+ }
566
+ });
567
+ return perServerRequestDataWithUrls;
568
+ }
569
+ function noncePlaceholderPlugin() {
570
+ const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
571
+ return {
572
+ name: "hs-nonce-placeholder",
573
+ enforce: "post",
574
+ apply() {
575
+ return HS_DEPLOYED;
576
+ },
577
+ transformIndexHtml(html) {
578
+ const regex = /<(style|script|link) (.*)>/gi;
579
+ const replacer = (_, p1, p2) => {
580
+ if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
581
+ p1 === "link" && p2.includes('rel="stylesheet"')) {
582
+ const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
583
+ p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
584
+ }
585
+ return `<${p1} ${p2}>`;
586
+ };
587
+ return html.replace(regex, replacer);
588
+ }
589
+ };
590
+ }
591
+ async function renderComponentOnServer(Component, props, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions) {
592
+ const componentDebugName = Component.displayName || Component.name;
593
+ return renderOnServer(
594
+ /* @__PURE__ */ jsx2(Component, { ...props }),
595
+ pageUrl,
596
+ environmentConfig,
597
+ entryPointBasePath,
598
+ contextOptions,
599
+ componentDebugName,
600
+ renderOptions
601
+ );
602
+ }
603
+ async function renderOnServer(elements, pageUrl, environmentConfig, entryPointBasePath, contextOptions, debugName, renderOptions) {
604
+ const supplementalFieldValues = contextOptions ? contextOptions.supplementalFieldValues : void 0;
605
+ const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
606
+ environmentConfig,
607
+ entryPointBasePath,
608
+ supplementalFieldValues
609
+ }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);
610
+ let html = await renderStreamToPromise(
611
+ /* @__PURE__ */ jsx2(ServerRenderContext.Provider, { value: renderContext, children: elements }),
612
+ renderOptions
613
+ );
614
+ if (renderContext.messagesForBrowser.length > 0) {
615
+ html = `${html}${scriptTagToLogServerMessages(
616
+ renderContext.messagesForBrowser,
617
+ `Server messages rendering: ${debugName}`
618
+ )}`;
619
+ }
620
+ return { html, renderContext };
621
+ }
622
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
623
+ if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
624
+ prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
625
+ }
626
+ const serializedJson = jsonStringifyAndEscapeForInlineJS(
627
+ environmentConfig.toJSON(),
628
+ { baseIndent: 6, prettyPrint }
629
+ );
630
+ const globals = [`window.__hsEnvConfig = ${serializedJson};`];
631
+ if (hsServerPageUrl) {
632
+ globals.push(
633
+ `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(
634
+ hsServerPageUrl
635
+ )};`
636
+ );
637
+ }
638
+ if (hsBasePath) {
639
+ globals.push(
640
+ `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`
641
+ );
642
+ }
643
+ if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {
644
+ const firstCriticalDevError = criticalDevErrors[0];
645
+ globals.push(`
646
+ customElements.whenDefined('vite-error-overlay').then(() => {
647
+ const ErrorOverlay = customElements.get('vite-error-overlay');
648
+ const error = new Error(${jsonStringifyAndEscapeForInlineJS(
649
+ firstCriticalDevError.message
650
+ )});
651
+ const overlay = new ErrorOverlay(error);
652
+
653
+ document.body.appendChild(overlay);
654
+ })
655
+ `);
656
+ }
657
+ const nonceAttr = includeNonces && cmsComponents.STYLE_NONCE_PLACEHOLDER ? ` nonce="${cmsComponents.STYLE_NONCE_PLACEHOLDER}"` : "";
658
+ return `
659
+ <script type="text/javascript"${nonceAttr}>
660
+ ${globals.join("\n ")}
661
+ </script>
662
+ `;
663
+ }
664
+ function renderFieldsJSX(fieldsJSX) {
665
+ let moduleJson;
666
+ const outputCallback = (callbackJson) => {
667
+ moduleJson = callbackJson;
668
+ };
669
+ renderToStaticMarkup(
670
+ cloneElement(fieldsJSX, {
671
+ outputCallback
672
+ })
673
+ );
674
+ if (!moduleJson) {
675
+ throw new Error("couldn't render module fields definition to fields.json");
676
+ }
677
+ return moduleJson;
678
+ }
679
+ function renderFieldsToJson(fields, moduleName) {
680
+ let fieldsJSON;
681
+ try {
682
+ if (isValidElement(fields)) {
683
+ fieldsJSON = renderFieldsJSX(fields);
684
+ } else if (Array.isArray(fields)) {
685
+ fieldsJSON = fields;
686
+ } else {
687
+ throw new Error(
688
+ `Couldn't recognize \`fields\` value for module ${moduleName}`
689
+ );
690
+ }
691
+ return fieldsJSON;
692
+ } catch (e) {
693
+ e.message = `Error when rendering fields for ${moduleName}: ${e.message}`;
694
+ throw e;
695
+ }
696
+ }
697
+ var setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, jsx2, promiseForNewWritableStream, renderStreamToPromise;
698
+ var init_dist = __esm({
699
+ "../cms-js-internal/dist/index.js"() {
700
+ init_basicUtils();
701
+ init_basicUtils();
525
702
  ({ setProperty, getProperty, hasProperty } = dotProp);
526
703
  serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
527
704
  const islandsArrayToSerialize = tweakedIslandsArray.map(
@@ -618,8 +795,6 @@ ${indentString}`);
618
795
  prettyPrint
619
796
  )}`;
620
797
  };
621
- 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";
622
- virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
623
798
  jsx2 = jsxRuntime.jsx;
624
799
  promiseForNewWritableStream = () => {
625
800
  const chunks = [];
@@ -657,103 +832,6 @@ ${indentString}`);
657
832
  });
658
833
  return streamDonePromise;
659
834
  };
660
- scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
661
- if (!messagesForBrowser) {
662
- return "";
663
- }
664
- const consoleLines = [];
665
- for (const message of messagesForBrowser) {
666
- let funcString = "console.log";
667
- if (message.level === "error") {
668
- funcString = "console.error";
669
- }
670
- if (message.level === "warn") {
671
- funcString = "console.warn";
672
- }
673
- const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
674
- consoleLines.push(` ${funcString}(${argString});`);
675
- }
676
- let groupStart = "";
677
- let groupEnd = "";
678
- if (groupLabel !== void 0 && groupLabel !== null) {
679
- groupStart = `
680
- console.group(${JSON.stringify(groupLabel)});`;
681
- groupEnd = ` console.groupEnd()
682
- `;
683
- }
684
- return `<script>${groupStart}
685
- ${consoleLines.join("\n")}
686
- ${groupEnd}</script>
687
- `;
688
- };
689
- getComponentExtension = (componentPath) => {
690
- const filteredExtensions = COMPONENT_EXTENSIONS.filter(
691
- (ext) => componentPath.endsWith(ext)
692
- );
693
- if (filteredExtensions.length === 1) {
694
- return filteredExtensions[0];
695
- }
696
- return void 0;
697
- };
698
- hasComponentExtension = (componentPath) => {
699
- return !!getComponentExtension(componentPath);
700
- };
701
- isStorybookStory = (componentPath) => {
702
- return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
703
- };
704
- removeComponentExtension = (componentPath) => {
705
- const ext = getComponentExtension(componentPath);
706
- if (ext == null) {
707
- return componentPath;
708
- }
709
- return componentPath.slice(0, -1 * ext.length);
710
- };
711
- COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
712
- ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
713
- GATES = [
714
- "CMS:JSRenderer:GetServerSideProps",
715
- "CMS:JSRenderer:ModuleHubl",
716
- "CMS:JSRenderer:RemoveCjsPlugin",
717
- "CMS:JSRenderer:RemoveMockClientEntryPlugin"
718
- ];
719
- ENABLED_FEATURES_GATE_MAP = {
720
- "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
721
- "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin"
722
- };
723
- BUILD_INFO_PATH = "/build-info.json";
724
- findAllComponentsIn = (webRoot2, componentsFolder) => {
725
- const fullComponentsFolderPath = join(webRoot2, componentsFolder);
726
- const componentsByName = {};
727
- if (!existsSync(fullComponentsFolderPath)) {
728
- return componentsByName;
729
- }
730
- readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
731
- const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
732
- const subdirPath = join(componentsFolder, fileOrFolderName);
733
- const isDirectory = lstatSync(fullPath).isDirectory();
734
- if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
735
- const subdirPathNoExtension = removeComponentExtension(subdirPath);
736
- componentsByName[subdirPathNoExtension] = subdirPath;
737
- } else if (isDirectory) {
738
- for (const potentialExtension of COMPONENT_EXTENSIONS) {
739
- const potentialIndexModule = join(
740
- subdirPath,
741
- `index${potentialExtension}`
742
- );
743
- const fullPotentialPath = join(
744
- fullPath,
745
- `index${potentialExtension}`
746
- );
747
- if (existsSync(fullPotentialPath)) {
748
- const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
749
- componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
750
- break;
751
- }
752
- }
753
- }
754
- });
755
- return componentsByName;
756
- };
757
835
  }
758
836
  });
759
837