@hubspot/cms-dev-server 0.17.0 → 0.18.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 (74) hide show
  1. package/dist/generateJsonFromJsx.js +297 -171
  2. package/dist/generateJsonFromJsx.js.map +7 -0
  3. package/dist/index.js +4769 -175
  4. package/dist/index.js.map +7 -0
  5. package/dist/internalSsr.js +260 -151
  6. package/dist/internalSsr.js.map +7 -0
  7. package/dist/island-runtime.js.map +7 -0
  8. package/dist/run.js +1991 -501
  9. package/dist/run.js.map +7 -0
  10. package/dist/storybook/index.js.map +7 -0
  11. package/dist/storybook-main/main.js +261 -152
  12. package/dist/storybook-main/main.js.map +7 -0
  13. package/dist/storybook-main/preview.js.map +7 -0
  14. package/package.json +18 -4
  15. package/types/api/designmanager.d.ts +31 -0
  16. package/types/api/session.d.ts +2 -0
  17. package/types/components/HubLModulesList.d.ts +4 -0
  18. package/types/components/HubLTemplatesList.d.ts +4 -0
  19. package/types/components/ModulesList.d.ts +5 -0
  20. package/types/components/PartialsList.d.ts +4 -0
  21. package/types/createAppServer.d.ts +2 -0
  22. package/types/createDevServer.d.ts +5 -0
  23. package/types/createViteDevServer.d.ts +3 -0
  24. package/types/fileManager.d.ts +4 -0
  25. package/types/index.d.ts +1 -0
  26. package/types/island-runtime.d.ts +2 -0
  27. package/types/lib/configHelpers.d.ts +2 -0
  28. package/types/lib/criticalDevErrorsToServerMessages.d.ts +4 -0
  29. package/types/lib/debug.d.ts +1 -0
  30. package/types/lib/errors.d.ts +6 -0
  31. package/types/lib/fetchModuleGraphQLData.d.ts +24 -0
  32. package/types/lib/fullOriginalUrlFromRequest.d.ts +2 -0
  33. package/types/lib/gates.d.ts +2 -0
  34. package/types/lib/getJSRenderingGates.d.ts +8 -0
  35. package/types/lib/httpsRedirectingServer.d.ts +11 -0
  36. package/types/lib/logColors.d.ts +6 -0
  37. package/types/lib/moduleGraph.d.ts +1 -0
  38. package/types/lib/packagePath.d.ts +1 -0
  39. package/types/lib/pathHelpers.d.ts +3 -0
  40. package/types/lib/previewUtils.d.ts +22 -0
  41. package/types/lib/proxyHelpers.d.ts +29 -0
  42. package/types/lib/renderComponentWithCSS.d.ts +14 -0
  43. package/types/lib/renderHelpers.d.ts +1 -0
  44. package/types/lib/renderModule.d.ts +11 -0
  45. package/types/lib/renderModulePreview.d.ts +5 -0
  46. package/types/lib/renderPartial.d.ts +5 -0
  47. package/types/lib/templates.d.ts +4 -0
  48. package/types/lib/trackUsage.d.ts +3 -0
  49. package/types/lib/validateHSPlatform.d.ts +3 -0
  50. package/types/lib/watchFieldsUpdates.d.ts +22 -0
  51. package/types/proxyPage/constants.d.ts +1 -0
  52. package/types/proxyPage/fetchContentMetadata.d.ts +7 -0
  53. package/types/proxyPage/fetchDomains.d.ts +9 -0
  54. package/types/proxyPage/fetchPreviewInfo.d.ts +6 -0
  55. package/types/proxyPage/proxyPage.d.ts +11 -0
  56. package/types/proxyPage/renderLocalError.d.ts +2 -0
  57. package/types/proxyPage/utils.d.ts +4 -0
  58. package/types/routes/createDevServerRoutes.d.ts +3 -0
  59. package/types/routes/homeRouteHandler.d.ts +3 -0
  60. package/types/routes/hublModuleRouteHandler.d.ts +2 -0
  61. package/types/routes/hublTemplateRouteHandler.d.ts +2 -0
  62. package/types/routes/linksToAllModulesRouteHandler.d.ts +2 -0
  63. package/types/routes/linksToAllPartialsRouteHandler.d.ts +2 -0
  64. package/types/routes/module.d.ts +3 -0
  65. package/types/routes/modulePreviewRouteHandler.d.ts +3 -0
  66. package/types/routes/partial.d.ts +2 -0
  67. package/types/routes/proxyPageResourceRedirect.d.ts +2 -0
  68. package/types/routes/proxyPageRouteHandler.d.ts +2 -0
  69. package/types/routes/proxyPathPageResourceRedirect.d.ts +2 -0
  70. package/types/routes/proxyPathPageRouteHandler.d.ts +2 -0
  71. package/types/routes/proxyServerlessHandler.d.ts +2 -0
  72. package/types/routes/remoteFsDirtyHandler.d.ts +2 -0
  73. package/types/shadowDevServer/createShadowDevServerRoutes.d.ts +2 -0
  74. package/types/shadowDevServer/startShadowDevServer.d.ts +2 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/storybook/moduleStory.tsx", "../../../cms-js-internal/dist/basicUtils.js", "../../../cms-js-internal/dist/index.js", "../../src/storybook/getFieldsArgTypes.ts", "../../src/storybook/getNestedFieldObjectForArgs.ts"],
4
+ "sourcesContent": ["import React, { useEffect } from 'react';\nimport {\n renderFieldsToJson,\n namespaceModulePropsShape,\n} from '@hubspot/cms-js-internal';\nimport { ModuleProps } from '@hubspot/cms-components';\nimport getFieldsArgTypes from './getFieldsArgTypes.js';\nimport getNestedFieldObjectForArgs from './getNestedFieldObjectForArgs.js';\nimport { Args, ArgTypes, ModuleStory } from './types.js';\n\nfunction moduleArgs(argTypes: ArgTypes) {\n const args = {};\n for (const argKey in argTypes) {\n if (Object.hasOwnProperty.call(argTypes, argKey)) {\n args[argKey] = argTypes[argKey].defaultValue;\n }\n }\n\n return args;\n}\n\nexport function moduleStory(\n ModuleComponent: (\n moduleProps: ModuleProps\n ) => React.ReactElement<any, any> | null,\n fields: JSX.Element,\n storyArgs: Args\n): ModuleStory {\n const fieldsJSON = renderFieldsToJson(fields, ModuleComponent.name);\n const argTypes = getFieldsArgTypes(fieldsJSON);\n\n const args = { ...moduleArgs(argTypes), ...storyArgs };\n\n return {\n render: (_args: Args) => {\n const fieldValues = getNestedFieldObjectForArgs(_args);\n const props = namespaceModulePropsShape(fieldValues);\n\n return <ModuleComponent {...props} />;\n },\n argTypes,\n args,\n };\n}\n\nexport function moduleStoryWithIsland(\n moduleName: string,\n fields: JSX.Element,\n storyArgs: Args\n): ModuleStory {\n if (typeof moduleName !== 'string') {\n throw new Error(\n \"moduleStoryWithIsland takes a `moduleName` that matches the file or folder name for the module as a string for the first argument, and the module's Fields JSX as the second parameter\"\n );\n }\n\n if (!fields) {\n throw new Error(\n \"moduleStoryWithIsland requires a second parameter of the module's fields configuration\"\n );\n }\n\n const fieldsJSON = renderFieldsToJson(fields, moduleName);\n const argTypes = getFieldsArgTypes(fieldsJSON);\n const args = { ...moduleArgs(argTypes), ...storyArgs };\n\n return {\n argTypes,\n args,\n render: (_args: Args) => {\n const fieldValues = getNestedFieldObjectForArgs(_args);\n const fieldValuesString = JSON.stringify(fieldValues);\n\n const domain = `${\n window.location.protocol\n }//${window.location.hostname.replace('storybook.', '')}:3000`;\n\n const fieldValuesJson = encodeURIComponent(fieldValuesString);\n const iframeSrc = `${domain}/module/${moduleName}?fields=${fieldValuesJson}`;\n\n useEffect(() => {\n const existingElement = document.querySelector('#hs-module-iframe');\n if (existingElement) {\n existingElement.setAttribute('src', iframeSrc);\n return () => {\n existingElement.remove();\n };\n }\n\n const iframeElement = document.createElement('iframe');\n iframeElement.setAttribute('src', iframeSrc);\n iframeElement.setAttribute('id', 'hs-module-iframe');\n iframeElement.setAttribute(\n 'style',\n `border: none;width: 100%;height: 100%;overflow: auto;position: absolute;left: 0;top: 0;`\n );\n\n document.querySelector('#storybook-root').appendChild(iframeElement);\n\n return () => {\n iframeElement.remove();\n };\n }, [iframeSrc]);\n\n return <div />;\n },\n };\n}\n", "import path from \"path\";\nimport { createHash } from \"crypto\";\nimport fs, { readFileSync, existsSync, readdirSync, lstatSync } from \"fs\";\nimport { join } from \"path/posix\";\nconst COMPONENT_EXTENSIONS = [\".jsx\", \".tsx\", \".js\", \".ts\"];\nconst ENTRY_POINTS_PATH = \"components/partials/\";\nconst MODULE_FOLDER_PATH = \"components/modules/\";\nconst VIRTUAL_ISLAND_RUNTIME = \"virtual:island-runtime\";\nconst VIRTUAL_CONFIG_SETUP = \"virtual:config-setup\";\nconst CSS_LANGS_RE = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/;\nconst collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {\n const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(\n modulePathToStartWith\n );\n if (!appModulesForPath || appModulesForPath.size === 0) {\n throw new Error(`No modules at: ${modulePathToStartWith}`);\n } else if (appModulesForPath.size > 1) {\n throw new Error(`More than one module at: ${modulePathToStartWith}`);\n }\n const appModule = Array.from(appModulesForPath.values())[0];\n const allServerSideModulesImported = /* @__PURE__ */ new Set();\n const newCssModules = [];\n const moduleQueue = Array.from(appModule.importedModules);\n for (const importedModule of moduleQueue) {\n if (allServerSideModulesImported.has(importedModule.id)) {\n continue;\n }\n allServerSideModulesImported.add(importedModule.id);\n const isCss = CSS_LANGS_RE.test(importedModule.file);\n const moduleModulesToQueue = Array.from(importedModule.importedModules);\n if (isCss && !cssModulesImported.has(importedModule)) {\n cssModulesImported.add(importedModule);\n newCssModules.push(importedModule);\n }\n moduleQueue.push(...moduleModulesToQueue);\n }\n return newCssModules;\n};\nfunction createPreloadLink(assetPath, basePath = \"\") {\n if (assetPath && assetPath[0] !== \"/\") {\n assetPath = `/${assetPath}`;\n }\n if (assetPath.endsWith(\".js\")) {\n return `<link rel=\"modulepreload\" crossorigin href=\"${basePath}${assetPath}\">`;\n } else if (CSS_LANGS_RE.test(assetPath)) {\n return `<link rel=\"stylesheet\" href=\"${basePath}${assetPath}?css\">`;\n } else if (assetPath.endsWith(\".woff\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"font\" type=\"font/woff\" crossorigin>`;\n } else if (assetPath.endsWith(\".woff2\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"font\" type=\"font/woff2\" crossorigin>`;\n } else if (assetPath.endsWith(\".gif\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/gif\">`;\n } else if (assetPath.endsWith(\".jpg\") || assetPath.endsWith(\".jpeg\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/jpeg\">`;\n } else if (assetPath.endsWith(\".png\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/png\">`;\n } else {\n throw new Error(`Unknown preload type for ${assetPath}`);\n }\n}\nconst collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {\n return `${collectCssModules(\n modulePathToStartWith,\n viteServer,\n cssModulesImported\n ).map((cssModule) => createPreloadLink(cssModule.url)).join(\"\\n\")}\n`;\n};\nconst badInlineJsChars = /[\\u2028\\u2029<>/]/g;\nconst inlineJsEscapeChars = {\n \"\\u2028\": \"\\\\u2028\",\n \"\\u2029\": \"\\\\u2029\",\n \"<\": \"\\\\u003C\",\n \">\": \"\\\\u003E\",\n \"/\": \"\\\\u002F\"\n};\nfunction escapeChar(unsafeChar) {\n return inlineJsEscapeChars[unsafeChar];\n}\nfunction escapeForInlineJS(input) {\n return input.replace(badInlineJsChars, escapeChar);\n}\nfunction jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent = 2, prettyPrint = true } = {}) {\n const indentString = \" \".repeat(baseIndent);\n jsonIndent = prettyPrint ? jsonIndent : void 0;\n return escapeForInlineJS(JSON.stringify(input, null, jsonIndent)).replace(\n /\\n/gm,\n `\n${indentString}`\n );\n}\nlet viteRoot;\nlet viteCommand;\nfunction resolveIslandPlugin(islandsSet) {\n return {\n enforce: \"pre\",\n name: \"resolve-islands\",\n configResolved(config) {\n viteRoot = config.root;\n viteCommand = config.command;\n },\n load(id) {\n if (id.endsWith(\"?island\") || id.endsWith(\"?client\")) {\n const [idWithNoParam] = id.split(\"?\");\n const islandModuleImportPath = `${idWithNoParam}?client-entry`;\n const componentExtension = path.extname(idWithNoParam);\n const componentFilenameWithNoExtension = path.basename(\n idWithNoParam,\n componentExtension\n );\n const modulePath = idWithNoParam.replace(`${viteRoot}/`, \"\");\n const moduleId = (viteCommand === \"serve\" ? idWithNoParam : modulePath).concat(\"?client-entry\");\n if (islandsSet) {\n islandsSet.add(moduleId);\n }\n return `\n const moduleId = '${moduleId}';\n\n const lazyComponent = () => import('${islandModuleImportPath}');\n lazyComponent.moduleName = '${componentFilenameWithNoExtension}';\n lazyComponent.moduleId = moduleId;\n\n export default lazyComponent;\n `;\n }\n return null;\n }\n };\n}\nfunction resolveIslandToPlainModulePlugin(enabled = true) {\n return {\n enforce: \"pre\",\n name: \"resolve-islands-to-plain\",\n configResolved(config) {\n viteRoot = config.root;\n viteCommand = config.command;\n },\n async resolveId(id, importer, options) {\n if (enabled && (id.endsWith(\"?island\") || id.endsWith(\"?client\"))) {\n const newId = id.replace(\"?island\", \"\").replace(\"?client\", \"\");\n const resolution = await this.resolve(newId, importer, {\n skipSelf: true,\n ...options\n });\n if (resolution) {\n return resolution;\n }\n }\n return null;\n }\n };\n}\nfunction resolveIslandToPlainModuleNoopPlugin() {\n return resolveIslandToPlainModulePlugin(false);\n}\nconst 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\";\nconst virtualClientRenderIslandModuleId = \"virtual:clientRenderIsland.tsx\";\nfunction clientIslandEntryPlugin() {\n return {\n enforce: \"pre\",\n name: \"client-island-entry-plugin\",\n resolveId(id) {\n if (id === virtualClientRenderIslandModuleId) {\n return virtualClientRenderIslandModuleId;\n }\n return null;\n },\n load(id) {\n if (id.endsWith(\"?client-entry\")) {\n const [idWithNoParam] = id.split(\"?\");\n return `\n import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';\n import Component from '${idWithNoParam}';\n\n export function render(island) {\n return clientRenderIsland(island, Component)\n }\n\n export default Component;\n `;\n }\n if (id === virtualClientRenderIslandModuleId) {\n return clientRenderIsland;\n }\n return null;\n }\n };\n}\nconst scriptTagToLogServerMessages = (messagesForBrowser, groupLabel, nonceAttribute) => {\n if (!messagesForBrowser) {\n return \"\";\n }\n const consoleLines = [];\n for (const message of messagesForBrowser) {\n let funcString = \"console.log\";\n if (message.level === \"error\") {\n funcString = \"console.error\";\n }\n if (message.level === \"warn\") {\n funcString = \"console.warn\";\n }\n const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(\", \");\n consoleLines.push(` ${funcString}(${argString});`);\n }\n let groupStart = \"\";\n let groupEnd = \"\";\n if (groupLabel !== void 0 && groupLabel !== null) {\n groupStart = `\n console.group(${JSON.stringify(groupLabel)});`;\n groupEnd = ` console.groupEnd()\n`;\n }\n return `<script ${nonceAttribute}>${groupStart}\n${consoleLines.join(\"\\n\")}\n${groupEnd}<\\/script>\n`;\n};\nconst getComponentExtension = (componentPath) => {\n const filteredExtensions = COMPONENT_EXTENSIONS.filter(\n (ext) => componentPath.endsWith(ext)\n );\n if (filteredExtensions.length === 1) {\n return filteredExtensions[0];\n }\n return void 0;\n};\nconst hasComponentExtension = (componentPath) => {\n return !!getComponentExtension(componentPath);\n};\nconst isStorybookStory = (componentPath) => {\n return !!path.basename(componentPath, path.extname(componentPath)).endsWith(\".stories\");\n};\nconst removeComponentExtension = (componentPath) => {\n const ext = getComponentExtension(componentPath);\n if (ext == null) {\n return componentPath;\n }\n return componentPath.slice(0, -1 * ext.length);\n};\nfunction getEntryPointHash(entryPoint) {\n return createHash(\"md5\").update(entryPoint).digest(\"hex\").slice(0, 6);\n}\nfunction getEntryPointHashWithIndexSuffix(entryPoint, index) {\n const renderIndexSuffix = index != null ? `i${index}` : \"\";\n return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;\n}\nconst COMBINED_REACT_BASE_PATH = \"https://static.hsappstatic.net/cms-js-static/ex/js/react/v18\";\nconst ISLAND_RUNTIME_CONFIG_BASE_PATH = \"https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1\";\nfunction getCombinedReactUrl() {\n const hsEnv = process.env.HS_ENV;\n const fileVersion = hsEnv === \"prod\" ? `react-combined.mjs` : \"react-combined-qa.mjs\";\n return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;\n}\nfunction getIslandRuntimeConfigUrl() {\n const hsEnv = process.env.HS_ENV;\n const fileVersion = hsEnv === \"prod\" ? `island-runtime.mjs` : \"island-runtime-qa.mjs\";\n return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;\n}\nfunction includesHublDataReference(templateSource) {\n const hublDataPattern = /\\{%\\s+set\\s+(experimentalHublData|hublData)\\s*=/;\n return !!templateSource.match(hublDataPattern);\n}\nconst removeIndexFromPath = (id) => {\n return id.replace(/\\/index\\.[jt]sx?$/, \"\");\n};\nconst removeIndexOrTrailingJsFromPath = (id) => {\n return removeIndexFromPath(id).replace(/\\.[jt]sx?$/, \"\");\n};\nconst HEALTHCHECKS_ENABLED_DEFAULT = true;\nconst HEALTHCHECKS_STRICT_DEFAULT = false;\nfunction getCMSAssetConfig(webRoot) {\n const cmsAssetsPath = path.join(webRoot, \"cms-assets.json\");\n const cmsThemePath = path.join(webRoot, \"theme.json\");\n const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;\n const parsedConfig = JSON.parse(\n fs.readFileSync(configPathToUse).toString()\n );\n return parsedConfig;\n}\nfunction getCMSAssetConfigIfExists(webRoot) {\n try {\n return getCMSAssetConfig(webRoot);\n } catch (e) {\n console.error(\n `Error finding or parsing cms-assets.json in ${webRoot}, but ignoring for now`\n );\n return {};\n }\n}\nfunction areBuildHealthChecksEnabled(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;\n}\nfunction doHealthChecksFailTheBuild(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;\n}\nfunction getServerIncludePrebundleDepPatterns(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];\n}\nconst BUILD_INFO_PATH = \"/build-info.json\";\nfunction getBuildInfo(buildDir) {\n try {\n const buildInfo = JSON.parse(\n readFileSync(path.join(buildDir, BUILD_INFO_PATH)).toString()\n );\n return buildInfo;\n } catch (e) {\n throw new Error(`Error loading build-info.json, path: ${BUILD_INFO_PATH}`);\n }\n}\nfunction getBaseAssetUrlFromBuild(buildDir) {\n return getBuildInfo(buildDir).baseAssetUrl;\n}\nconst GATES = [\n \"CMS:JSRenderer:GetServerSideProps\",\n \"CMS:JSRenderer:ModuleHubl\",\n \"CMS:JSRenderer:RemoveCjsPlugin\",\n \"CMS:JSRenderer:RemoveMockClientEntryPlugin\",\n \"CMS:JSRenderer:AnalyzeCmsModules\"\n];\nconst ENABLED_FEATURES_GATE_MAP = {\n \"cms:jsr:getServerSideProps\": \"CMS:JSRenderer:GetServerSideProps\",\n \"cms:jsr:RemoveCjsPlugin\": \"CMS:JSRenderer:RemoveCjsPlugin\",\n \"cms:jsr:analyzeCmsModules\": \"CMS:JSRenderer:AnalyzeCmsModules\"\n};\nfunction isUngatedFor(gates, gate) {\n return gates.includes(gate);\n}\nfunction ungatedAtBuildTimeFor(buildDir, gate) {\n try {\n const buildInfo = getBuildInfo(buildDir);\n return isUngatedFor(buildInfo.gates, gate);\n } catch (e) {\n return false;\n }\n}\nconst findAllComponentsIn = (webRoot, componentsFolder) => {\n const fullComponentsFolderPath = join(webRoot, componentsFolder);\n const componentsByName = {};\n if (!existsSync(fullComponentsFolderPath)) {\n return componentsByName;\n }\n readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {\n const fullPath = join(fullComponentsFolderPath, fileOrFolderName);\n const subdirPath = join(componentsFolder, fileOrFolderName);\n const isDirectory = lstatSync(fullPath).isDirectory();\n if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {\n const subdirPathNoExtension = removeComponentExtension(subdirPath);\n componentsByName[subdirPathNoExtension] = subdirPath;\n } else if (isDirectory) {\n for (const potentialExtension of COMPONENT_EXTENSIONS) {\n const potentialIndexModule = join(\n subdirPath,\n `index${potentialExtension}`\n );\n const fullPotentialPath = join(\n fullPath,\n `index${potentialExtension}`\n );\n if (existsSync(fullPotentialPath)) {\n const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);\n componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;\n break;\n }\n }\n }\n });\n return componentsByName;\n};\nfunction findAllModulesInRoot(webRoot) {\n const allModuleComponents = findAllComponentsIn(\n webRoot,\n \"./components/modules\"\n );\n const moduleNames = Object.keys(allModuleComponents).map(\n (moduleSubpath) => moduleSubpath.replace(\"components/modules/\", \"\").replace(\"/index\", \"\")\n );\n const moduleSubpaths = Object.keys(allModuleComponents);\n return { moduleNames, moduleSubpaths };\n}\nfunction findAllPartialsInRoot(webRoot) {\n const allPartialComponents = findAllComponentsIn(\n webRoot,\n \"./components/partials\"\n );\n const partialNames = Object.keys(allPartialComponents).map(\n (partialSubpath) => partialSubpath.replace(\"components/partials/\", \"\").replace(\"/index\", \"\")\n );\n const partialSubpaths = Object.keys(allPartialComponents);\n return { partialNames, partialSubpaths };\n}\nfunction namespaceModulePropsShape(props) {\n const {\n dataQueryResult,\n hublParameters,\n fieldValues: passedFieldValues,\n hublData,\n experimentalHublData,\n moduleName,\n supplementalFieldValues\n } = props;\n const oldPropsShape = { ...props };\n if (oldPropsShape.dataQueryResult) {\n delete oldPropsShape.dataQueryResult;\n }\n if (oldPropsShape.hublParameters) {\n delete oldPropsShape.hublParameters;\n }\n const fieldValues = passedFieldValues || oldPropsShape;\n return {\n ...fieldValues,\n dataQueryResult,\n fieldValues,\n hublParameters,\n hublData,\n experimentalHublData,\n moduleName,\n supplementalFieldValues\n };\n}\nfunction setIn(object, nestedKeysArray, value) {\n let curr = object;\n const finalKey = nestedKeysArray.pop();\n for (let index = 0; index < nestedKeysArray.length; index++) {\n const currentKey = nestedKeysArray[index];\n const nextKey = nestedKeysArray[index + 1];\n if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {\n if (curr[currentKey] === void 0) {\n curr[currentKey] = [];\n }\n }\n if (curr[currentKey] === void 0) {\n curr[currentKey] = {};\n }\n curr = curr[currentKey];\n }\n if (value !== void 0) {\n curr[finalKey] = value;\n }\n}\nfunction isStylesheetAsset(staticAsset) {\n return staticAsset.type === \"stylesheet\";\n}\nexport {\n COMPONENT_EXTENSIONS,\n CSS_LANGS_RE,\n ENABLED_FEATURES_GATE_MAP,\n ENTRY_POINTS_PATH,\n GATES,\n MODULE_FOLDER_PATH,\n VIRTUAL_CONFIG_SETUP,\n VIRTUAL_ISLAND_RUNTIME,\n getBaseAssetUrlFromBuild as a,\n areBuildHealthChecksEnabled,\n clientIslandEntryPlugin,\n collectCssInDev,\n collectCssModules,\n doHealthChecksFailTheBuild,\n escapeForInlineJS,\n findAllComponentsIn,\n findAllModulesInRoot,\n findAllPartialsInRoot,\n getBuildInfo as g,\n getCMSAssetConfig,\n getCMSAssetConfigIfExists,\n getCombinedReactUrl,\n getComponentExtension,\n getEntryPointHash,\n getEntryPointHashWithIndexSuffix,\n getIslandRuntimeConfigUrl,\n getServerIncludePrebundleDepPatterns,\n hasComponentExtension,\n includesHublDataReference,\n isStorybookStory,\n isStylesheetAsset,\n isUngatedFor,\n jsonStringifyAndEscapeForInlineJS,\n namespaceModulePropsShape,\n removeComponentExtension,\n removeIndexFromPath,\n removeIndexOrTrailingJsFromPath,\n resolveIslandPlugin,\n resolveIslandToPlainModuleNoopPlugin,\n resolveIslandToPlainModulePlugin,\n scriptTagToLogServerMessages,\n setIn,\n ungatedAtBuildTimeFor,\n virtualClientRenderIslandModuleId\n};\n", "import { jsonStringifyAndEscapeForInlineJS, scriptTagToLogServerMessages } from \"./basicUtils.js\";\nimport { COMPONENT_EXTENSIONS, CSS_LANGS_RE, ENABLED_FEATURES_GATE_MAP, ENTRY_POINTS_PATH, GATES, MODULE_FOLDER_PATH, VIRTUAL_CONFIG_SETUP, VIRTUAL_ISLAND_RUNTIME, areBuildHealthChecksEnabled, clientIslandEntryPlugin, collectCssInDev, collectCssModules, doHealthChecksFailTheBuild, escapeForInlineJS, findAllComponentsIn, findAllModulesInRoot, findAllPartialsInRoot, a, g, getCMSAssetConfig, getCMSAssetConfigIfExists, getCombinedReactUrl, getComponentExtension, getEntryPointHash, getEntryPointHashWithIndexSuffix, getIslandRuntimeConfigUrl, getServerIncludePrebundleDepPatterns, hasComponentExtension, includesHublDataReference, isStorybookStory, isStylesheetAsset, isUngatedFor, namespaceModulePropsShape, removeComponentExtension, removeIndexFromPath, removeIndexOrTrailingJsFromPath, resolveIslandPlugin, resolveIslandToPlainModuleNoopPlugin, resolveIslandToPlainModulePlugin, setIn, ungatedAtBuildTimeFor, virtualClientRenderIslandModuleId } from \"./basicUtils.js\";\nimport * as dotProp from \"dot-prop\";\nimport * as parser from \"@babel/parser\";\nimport _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\nimport { jsx } from \"react/jsx-runtime\";\nimport stream from \"stream\";\nimport { renderToPipeableStream, renderToStaticMarkup } from \"react-dom/server\";\nimport * as cmsComponents from \"@hubspot/cms-components\";\nimport { ServerRenderContext } from \"@hubspot/cms-components\";\nimport { isValidElement, cloneElement } from \"react\";\nimport \"path\";\nimport \"crypto\";\nimport \"fs\";\nimport \"path/posix\";\nconst { setProperty, getProperty, hasProperty } = dotProp;\nconst serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {\n const islandsArrayToSerialize = tweakedIslandsArray.map(\n ({\n id,\n moduleName,\n moduleId,\n props,\n hydrateOn,\n clientOnly,\n priority,\n url,\n sharedStateID,\n supplementalFieldValues,\n wrapperModuleId,\n wrapperUrl\n }) => {\n const output = {\n id,\n moduleName,\n moduleId,\n hydrateOn,\n clientOnly,\n priority,\n props,\n url\n };\n if (sharedStateID) {\n output.sharedStateID = sharedStateID;\n }\n if (wrapperModuleId) {\n output.wrapperModuleId = wrapperModuleId;\n }\n if (wrapperUrl) {\n output.wrapperUrl = wrapperUrl;\n }\n const filteredSupplementalFieldValues = filterOutUnreadSupplementalFieldValues(\n supplementalFieldValues,\n perServerRequestData.get(\"supplementalFieldValuesRead\")\n );\n if (filteredSupplementalFieldValues) {\n output.supplementalFieldValues = filteredSupplementalFieldValues;\n }\n return output;\n }\n );\n return jsonStringifyAndEscapeForInlineJS(islandsArrayToSerialize, {\n baseIndent,\n jsonIndent: 2,\n prettyPrint\n });\n};\nfunction filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {\n if (!supplementalFieldValues) {\n return supplementalFieldValues;\n }\n if (!supplementalFieldValuesRead) {\n return supplementalFieldValues;\n }\n const result = {};\n Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {\n if (hasProperty(supplementalFieldValues, fieldPath)) {\n setProperty(\n result,\n fieldPath,\n getProperty(supplementalFieldValues, fieldPath)\n );\n }\n });\n return result;\n}\nconst writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0, prettyPrint) => {\n const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x) => !!x);\n if (sharedStateIDs.length > 0) {\n const indentString = \" \".repeat(indent);\n const stateByID = {};\n sharedStateIDs.forEach(\n (id) => stateByID[id] = perServerRequestData.get(id)\n );\n const stringifiedState = jsonStringifyAndEscapeForInlineJS(stateByID, {\n prettyPrint,\n jsonIndent: 2\n });\n return `\n\nvar newState = ${stringifiedState};\nif(window.__hsSSInit) {\n window.__hsSSInit = Object.assign(window.__hsSSInit, newState);\n} else {\n window.__hsSSInit = newState;\n}`.replace(/\\n/gm, `\n${indentString}`);\n }\n return \"\";\n};\nfunction getIslandUrls(roots, viteDevServer) {\n return roots.map((island) => {\n const islandModule = viteDevServer.moduleGraph.getModuleById(\n island.moduleId\n );\n if (!islandModule) {\n throw new Error(`Unknown island moduleId: ${island.moduleId}`);\n }\n let wrapperModule;\n if (island.wrapperModuleId) {\n wrapperModule = viteDevServer.moduleGraph.getModuleById(\n island.wrapperModuleId\n );\n }\n const tweakedIsland = {\n ...island,\n url: islandModule.url,\n wrapperUrl: wrapperModule ? wrapperModule.url : void 0\n };\n return tweakedIsland;\n });\n}\nfunction getPerServerRequestUrls(perServerRequestData, viteDevServer) {\n if (!perServerRequestData.has(\"sharedStateIDs\")) {\n return new Map(perServerRequestData);\n }\n const perServerRequestDataWithUrls = new Map(\n perServerRequestData\n );\n perServerRequestData.get(\"sharedStateIDs\").forEach((id) => {\n const reducer = perServerRequestData.get(id);\n if (reducer.reducerFuncModuleId) {\n const reducerWithUrl = {\n ...reducer,\n reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(\n reducer.reducerFuncModuleId\n ).url\n };\n perServerRequestDataWithUrls.set(id, reducerWithUrl);\n }\n });\n return perServerRequestDataWithUrls;\n}\nconst createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {\n const islands = getIslandUrls(roots, viteDevServer);\n const perServerRequestDataWithUrls = getPerServerRequestUrls(\n perServerRequestData,\n viteDevServer\n );\n return `${\" \".repeat(\n indent\n )}window.__islands = ${serializeIslandDataForInlineScript(\n islands,\n perServerRequestData,\n indent,\n prettyPrint\n )}${writeSharedStateToJsGlobal(\n islands,\n perServerRequestDataWithUrls,\n indent,\n prettyPrint\n )}`;\n};\nfunction noncePlaceholderPlugin() {\n const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === \"true\";\n return {\n name: \"hs-nonce-placeholder\",\n enforce: \"post\",\n apply() {\n return HS_DEPLOYED;\n },\n transformIndexHtml(html) {\n const regex = /<(style|script|link) (.*)>/gi;\n const replacer = (_, p1, p2) => {\n if (p1 === \"style\" || p1 === \"script\" || // if link, only nonce for stylesheet\n p1 === \"link\" && p2.includes('rel=\"stylesheet\"')) {\n const noncePlaceholderValue = p1 === \"script\" ? \"hs-random-nonce\" : \"hs-random-style-nonce\";\n p2 = `nonce=\"${noncePlaceholderValue}\" ${p2}`;\n }\n return `<${p1} ${p2}>`;\n };\n return html.replace(regex, replacer);\n }\n };\n}\nconst traverse = _traverse.default;\nconst CMS_MODULE_COMPONENT_NAME = \"UnstableModule\";\nfunction findCmsModules(cmsModules = {}) {\n let config;\n return {\n enforce: \"pre\",\n name: \"findCmsModules\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n transform(code, id) {\n const moduleInfo = this.getModuleInfo(id);\n const isExternal = config.command === \"serve\" ? false : moduleInfo.isExternal;\n if (isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME)) {\n return null;\n }\n const localCmsModules = {};\n const sourceAst = parser.parse(code, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"]\n });\n let unstableModuleLocalName = CMS_MODULE_COMPONENT_NAME;\n const pluginError = this.error.bind(this);\n traverse(sourceAst, {\n ImportDeclaration(path) {\n if (!t.isStringLiteral(path.node.source, {\n value: \"@hubspot/cms-components\"\n })) {\n return null;\n }\n for (const specifier of path.node.specifiers) {\n if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {\n name: CMS_MODULE_COMPONENT_NAME\n })) {\n unstableModuleLocalName = specifier.local.name;\n }\n }\n },\n JSXOpeningElement(path) {\n if (!t.isJSXIdentifier(path.node.name, {\n name: unstableModuleLocalName\n }) || path.node.attributes.length !== 2) {\n return null;\n }\n let cmsModuleName;\n let cmsModulePath;\n for (const prop of path.node.attributes) {\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"name\" }) && t.isStringLiteral(prop.value)) {\n cmsModuleName = prop.value.value;\n continue;\n }\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"path\" }) && t.isStringLiteral(prop.value)) {\n cmsModulePath = prop.value.value;\n continue;\n }\n pluginError(\n new Error(\n `Error: ${id.replace(config.root, \"\")}:${prop.loc.start.line} \"name\" and \"path\" must be primitive strings`\n )\n );\n }\n const cmsModuleProps = {\n name: cmsModuleName,\n path: cmsModulePath\n };\n if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {\n pluginError(\n new Error(\n `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`\n )\n );\n }\n localCmsModules[cmsModuleProps.name] = cmsModuleProps;\n }\n });\n return {\n meta: {\n findCmsModules: localCmsModules\n }\n };\n },\n buildEnd(error) {\n if (error)\n throw error;\n const modulesWithCmsModuleUsage = Array.of(\n ...this.getModuleIds()\n ).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => this.getModuleInfo(moduleId)).filter(\n (moduleInfo) => Object.hasOwn(moduleInfo.meta, \"findCmsModules\")\n );\n const moduleToEntryPoints = {};\n for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {\n moduleToEntryPoints[moduleWithCmsModuleUsage.id] = findEntryPoints(\n this,\n moduleWithCmsModuleUsage\n );\n }\n for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {\n const usageInModuleEntryPoint = moduleToEntryPoints[moduleWithCmsModuleUsage.id].find((entryPoint) => entryPoint.id.includes(\"/components/modules\"));\n if (usageInModuleEntryPoint) {\n this.error(`\n Error: <${CMS_MODULE_COMPONENT_NAME} /> can only be used in Partials.\n Module: ${usageInModuleEntryPoint.id === moduleWithCmsModuleUsage.id ? usageInModuleEntryPoint.id.replace(config.root, \"\") : `imports: ${moduleWithCmsModuleUsage.id.replace(\n config.root,\n \"\"\n )}, which`} contains a <${CMS_MODULE_COMPONENT_NAME} />\n `);\n }\n }\n const root = config.root;\n for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {\n const islandsContainingCmsModuleUsage = checkModuleTreeForIslands(\n this,\n moduleWithCmsModuleUsage\n );\n if (islandsContainingCmsModuleUsage.length > 0) {\n throw new Error(`\n <${CMS_MODULE_COMPONENT_NAME} /> cannot be used within islands.\n ${formatIslandImporter(\n moduleWithCmsModuleUsage.id,\n root\n )} uses <${CMS_MODULE_COMPONENT_NAME} /> and is used by islands:\n ${islandsContainingCmsModuleUsage.map(\n (islandModuleInfo) => formatIslandImporter(islandModuleInfo.id, root)\n ).join(\", \")}\n `);\n }\n }\n for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {\n const entryPoints = moduleToEntryPoints[moduleWithCmsModuleUsage.id];\n for (const entryPoint of entryPoints) {\n const relativeEntryPoint = entryPoint.id.replace(root, \"\");\n if (!Object.hasOwn(cmsModules, relativeEntryPoint)) {\n cmsModules[relativeEntryPoint] = {};\n }\n for (const [cmsModuleName, cmsModuleValue] of Object.entries(\n moduleWithCmsModuleUsage.meta.findCmsModules\n )) {\n if (Object.hasOwn(cmsModules[relativeEntryPoint], cmsModuleName)) {\n this.error(`Error: duplicate module name: ${cmsModuleName}`);\n }\n cmsModules[relativeEntryPoint][cmsModuleName] = cmsModuleValue;\n }\n }\n }\n }\n };\n}\nfunction findEntryPoints(ctx, moduleInfo) {\n if (moduleInfo.isEntry) {\n return [moduleInfo];\n }\n const result = [];\n for (const importer of moduleInfo.importers) {\n const importerModuleInfo = ctx.getModuleInfo(importer);\n const entryPoints = findEntryPoints(ctx, importerModuleInfo);\n result.push(...entryPoints);\n }\n return result;\n}\nfunction checkModuleTreeForIslands(ctx, module) {\n if (module.id.endsWith(\"?client-entry\")) {\n return [module];\n }\n const importerResults = [];\n for (const importer of module.importers) {\n const importerInfo = ctx.getModuleInfo(importer);\n const importerResult = checkModuleTreeForIslands(ctx, importerInfo);\n importerResults.push(importerResult);\n }\n return importerResults.flat();\n}\nfunction formatIslandImporter(id, root) {\n return id.replace(root, \"\").replace(\"?client-entry\", \"\");\n}\nconst promiseForNewWritableStream = () => {\n const chunks = [];\n const writableStream = new stream.Writable();\n writableStream._write = (chunk, encoding, done) => {\n chunks.push(Buffer.from(chunk));\n done();\n };\n const streamDonePromise = new Promise((resolve, reject) => {\n writableStream.on(\"error\", (error) => {\n reject(error);\n });\n writableStream._final = (done) => {\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n done();\n };\n });\n return { streamDonePromise, writableStream };\n};\nconst renderStreamToPromise = async (reactElements, options) => {\n const { streamDonePromise, writableStream } = promiseForNewWritableStream();\n const {\n pipe\n /* abort */\n } = renderToPipeableStream(reactElements, {\n ...options || {},\n onShellReady() {\n },\n onAllReady() {\n pipe(writableStream);\n if (options == null ? void 0 : options.onAllReady) {\n options.onAllReady();\n }\n }\n });\n return streamDonePromise;\n};\nconst {\n createServerRenderContextV2,\n createServerRenderContext,\n renderServerSidePropsWithAsyncLocalStoreContext\n} = cmsComponents;\nconst bootStrapRenderContext = () => {\n const renderContext = createServerRenderContextV2 ? createServerRenderContextV2(null, {\n environmentConfig: null,\n entryPointBasePath: \"\",\n supplementalFieldValues: {},\n messagesForBrowser: []\n }) : createServerRenderContext(\"\", null);\n return renderContext;\n};\nasync function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {\n const { props } = propsAndDeps;\n const componentDebugName = Component.displayName || Component.name;\n const supplementalFieldValues = contextOptions == null ? void 0 : contextOptions.supplementalFieldValues;\n const messagesForBrowser = contextOptions == null ? void 0 : contextOptions.messagesForBrowser;\n const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {\n environmentConfig,\n entryPointBasePath,\n supplementalFieldValues,\n messagesForBrowser\n }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);\n if (getServerSideProps !== void 0 && typeof getServerSideProps === \"function\") {\n const gSSPResult = await renderServerSidePropsWithAsyncLocalStoreContext(\n getServerSideProps,\n propsAndDeps,\n renderContext\n );\n if (gSSPResult) {\n props.serverSideProps = gSSPResult.serverSideProps;\n }\n }\n return renderOnServer(\n /* @__PURE__ */ jsx(Component, { ...props }),\n renderContext,\n componentDebugName,\n renderOptions\n );\n}\nasync function renderOnServer(elements, renderContext = bootStrapRenderContext(), debugName, renderOptions) {\n let html = await renderStreamToPromise(\n /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }),\n renderOptions\n );\n if (renderContext.messagesForBrowser.length > 0) {\n html = `${html}${scriptTagToLogServerMessages(\n renderContext.messagesForBrowser,\n `Server messages rendering: ${debugName}`\n )}`;\n }\n return { html, renderContext };\n}\nfunction getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {\n if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {\n prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);\n }\n const serializedJson = jsonStringifyAndEscapeForInlineJS(\n environmentConfig.toJSON(),\n { baseIndent: 6, prettyPrint }\n );\n const globals = [`window.__hsEnvConfig = ${serializedJson};`];\n if (hsServerPageUrl) {\n globals.push(\n `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(\n hsServerPageUrl\n )};`\n );\n }\n if (hsBasePath) {\n globals.push(\n `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`\n );\n }\n if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {\n const firstCriticalDevError = criticalDevErrors[0];\n globals.push(`\n customElements.whenDefined('vite-error-overlay').then(() => {\n const ErrorOverlay = customElements.get('vite-error-overlay');\n const error = new Error(${jsonStringifyAndEscapeForInlineJS(\n firstCriticalDevError.message\n )});\n const overlay = new ErrorOverlay(error);\n\n document.body.appendChild(overlay);\n })\n `);\n }\n const nonceAttr = includeNonces && cmsComponents.SCRIPT_NONCE_PLACEHOLDER ? ` nonce=\"${cmsComponents.SCRIPT_NONCE_PLACEHOLDER}\"` : \"\";\n return `\n <script type=\"text/javascript\"${nonceAttr}>\n ${globals.join(\"\\n \")}\n <\\/script>\n `;\n}\nfunction renderFieldsJSX(fieldsJSX) {\n let moduleJson;\n const outputCallback = (callbackJson) => {\n moduleJson = callbackJson;\n };\n renderToStaticMarkup(\n cloneElement(fieldsJSX, {\n outputCallback\n })\n );\n if (!moduleJson) {\n throw new Error(\"couldn't render module fields definition to fields.json\");\n }\n return moduleJson;\n}\nfunction renderFieldsToJson(fields, moduleName) {\n let fieldsJSON;\n try {\n if (isValidElement(fields)) {\n fieldsJSON = renderFieldsJSX(fields);\n } else if (Array.isArray(fields)) {\n fieldsJSON = fields;\n } else {\n throw new Error(\n `Couldn't recognize \\`fields\\` value for module ${moduleName}`\n );\n }\n return fieldsJSON;\n } catch (e) {\n e.message = `Error when rendering fields for ${moduleName}: ${e.message}`;\n throw e;\n }\n}\nexport {\n COMPONENT_EXTENSIONS,\n CSS_LANGS_RE,\n ENABLED_FEATURES_GATE_MAP,\n ENTRY_POINTS_PATH,\n GATES,\n MODULE_FOLDER_PATH,\n VIRTUAL_CONFIG_SETUP,\n VIRTUAL_ISLAND_RUNTIME,\n areBuildHealthChecksEnabled,\n clientIslandEntryPlugin,\n collectCssInDev,\n collectCssModules,\n createIslandsGlobalJsForClientInDev,\n doHealthChecksFailTheBuild,\n escapeForInlineJS,\n findAllComponentsIn,\n findAllModulesInRoot,\n findAllPartialsInRoot,\n findCmsModules,\n a as getBaseAssetUrlFromBuild,\n g as getBuildInfo,\n getCMSAssetConfig,\n getCMSAssetConfigIfExists,\n getCombinedReactUrl,\n getComponentExtension,\n getEntryPointHash,\n getEntryPointHashWithIndexSuffix,\n getIslandRuntimeConfigUrl,\n getIslandUrls,\n getServerGlobalsToInject,\n getServerIncludePrebundleDepPatterns,\n hasComponentExtension,\n includesHublDataReference,\n isStorybookStory,\n isStylesheetAsset,\n isUngatedFor,\n jsonStringifyAndEscapeForInlineJS,\n namespaceModulePropsShape,\n noncePlaceholderPlugin,\n removeComponentExtension,\n removeIndexFromPath,\n removeIndexOrTrailingJsFromPath,\n renderComponentOnServer,\n renderFieldsToJson,\n renderOnServer,\n renderStreamToPromise,\n resolveIslandPlugin,\n resolveIslandToPlainModuleNoopPlugin,\n resolveIslandToPlainModulePlugin,\n scriptTagToLogServerMessages,\n serializeIslandDataForInlineScript,\n setIn,\n ungatedAtBuildTimeFor,\n virtualClientRenderIslandModuleId\n};\n", "import { Field } from '@hubspot/cms-components/fields';\nimport { ArgTypes } from './types.js';\n\nexport default function getFieldsArgTypes(\n fieldsJson: Field[],\n currentPathSegments: string[] = []\n): ArgTypes {\n let resultArgTypes: ArgTypes = {};\n for (const field of fieldsJson) {\n // storybook doesn't support nested controls, so emulate our nested\n // structure with group1.group2.field structure\n const fullFieldName = [...currentPathSegments, field.name].join('.');\n\n // should this definition of fieldType => argType live next to fields in cms-components?\n switch (field.type) {\n case 'group': {\n if (!field.children) {\n continue;\n }\n\n const groupResult = getFieldsArgTypes(field.children, [\n ...currentPathSegments,\n field.name,\n ]);\n\n resultArgTypes = {\n ...resultArgTypes,\n ...groupResult,\n };\n break;\n }\n case 'boolean': {\n resultArgTypes[fullFieldName] = {\n control: 'boolean',\n defaultValue: field.default,\n };\n break;\n }\n case 'text': {\n resultArgTypes[fullFieldName] = {\n control: 'text',\n defaultValue: field.default,\n };\n break;\n }\n case 'number': {\n resultArgTypes[fullFieldName] = {\n control: 'number',\n defaultValue: field.default,\n };\n break;\n }\n case 'choice': {\n const options = field.choices\n ? field.choices.map((choice) => choice[1])\n : [];\n\n resultArgTypes[fullFieldName] = {\n control: 'select',\n defaultValue: field.default,\n options,\n };\n break;\n }\n default: {\n resultArgTypes[fullFieldName] = {\n control: 'object',\n defaultValue: field.default,\n };\n break;\n }\n }\n }\n return resultArgTypes;\n}\n", "import { Args } from './types.js';\n\ntype FieldValues = {\n [fieldNameOrGroupName: string]: FieldValues;\n};\n\n// default values come through via `defaultValue` in the story's argTypes, we\n// need to re-nest them to match the field structure\nexport default function getNestedFieldObjectForArgs(_args: Args): FieldValues {\n const result: FieldValues = {};\n for (const argPath in _args) {\n if (Object.prototype.hasOwnProperty.call(_args, argPath)) {\n const argPathSegments = argPath.split('.');\n const nestedSegments = argPathSegments.slice(0, -1);\n const fieldName = argPathSegments[argPathSegments.length - 1];\n const fieldValue = _args[argPath];\n\n let currentNest = result;\n for (const segment of nestedSegments) {\n if (!Object.prototype.hasOwnProperty.call(currentNest, segment)) {\n currentNest[segment] = {};\n }\n currentNest = currentNest[segment];\n }\n currentNest[fieldName] = fieldValue;\n }\n }\n\n return result;\n}\n"],
5
+ "mappings": "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",
6
+ "names": ["createServerRenderContextV2", "createServerRenderContext"]
7
+ }
@@ -415,12 +415,16 @@ ${groupEnd}</script>
415
415
  "CMS:JSRenderer:ModuleHubl",
416
416
  "CMS:JSRenderer:RemoveCjsPlugin",
417
417
  "CMS:JSRenderer:RemoveMockClientEntryPlugin",
418
- "CMS:JSRenderer:AnalyzeCmsModules"
418
+ "CMS:JSRenderer:AnalyzeCmsModules",
419
+ "CMS:JSRenderer:ClientOnlySupplementalFieldSerialization",
420
+ "CMS:React:UnifiedThemePreview"
419
421
  ];
420
422
  ENABLED_FEATURES_GATE_MAP = {
421
423
  "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
422
424
  "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
423
- "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
425
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules",
426
+ "cms:jsr:clientOnlySupplementalFieldSerialization": "CMS:JSRenderer:ClientOnlySupplementalFieldSerialization",
427
+ "cms:react:unifiedThemePreview": "CMS:React:UnifiedThemePreview"
424
428
  };
425
429
  findAllComponentsIn = (webRoot2, componentsFolder) => {
426
430
  const fullComponentsFolderPath = join(webRoot2, componentsFolder);
@@ -620,80 +624,14 @@ function findCmsModules(cmsModules = {}) {
620
624
  },
621
625
  transform(code, id) {
622
626
  const moduleInfo = this.getModuleInfo(id);
623
- const isExternal = config.command === "serve" ? false : moduleInfo.isExternal;
624
- if (isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME)) {
627
+ if (shouldSkipModule(config, moduleInfo, code))
625
628
  return null;
626
- }
627
- const localCmsModules = {};
628
- const sourceAst = parser.parse(code, {
629
- sourceType: "module",
630
- plugins: ["jsx", "typescript"]
631
- });
632
- let moduleLocalImportName = CMS_MODULE_COMPONENT_NAME;
633
- let moduleUsed = false;
634
- const pluginError = this.error.bind(this);
635
- traverse(sourceAst, {
636
- ImportDeclaration(path3) {
637
- if (!t.isStringLiteral(path3.node.source, {
638
- value: "@hubspot/cms-components"
639
- })) {
640
- return null;
641
- }
642
- for (const specifier of path3.node.specifiers) {
643
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
644
- name: CMS_MODULE_COMPONENT_NAME
645
- })) {
646
- moduleLocalImportName = specifier.local.name;
647
- }
648
- }
649
- },
650
- JSXOpeningElement(path3) {
651
- if (!t.isJSXIdentifier(path3.node.name, {
652
- name: moduleLocalImportName
653
- })) {
654
- return null;
655
- }
656
- moduleUsed = true;
657
- let cmsModuleName;
658
- let cmsModulePath;
659
- let cmsModuleLabel;
660
- for (const prop of path3.node.attributes) {
661
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
662
- cmsModuleName = prop.value.value;
663
- continue;
664
- }
665
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
666
- cmsModulePath = prop.value.value;
667
- continue;
668
- }
669
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
670
- cmsModuleLabel = prop.value.value;
671
- continue;
672
- }
673
- pluginError(
674
- new Error(
675
- `Error: ${id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
676
- )
677
- );
678
- return null;
679
- }
680
- const cmsModuleProps = {
681
- name: cmsModuleName,
682
- path: cmsModulePath
683
- };
684
- if (cmsModuleLabel) {
685
- cmsModuleProps.label = cmsModuleLabel;
686
- }
687
- if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {
688
- pluginError(
689
- new Error(
690
- `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
691
- )
692
- );
693
- }
694
- localCmsModules[cmsModuleProps.name] = cmsModuleProps;
695
- }
696
- });
629
+ const { localCmsModules, moduleUsed } = analyzeSourceCodeUsages(
630
+ this,
631
+ moduleInfo,
632
+ config,
633
+ code
634
+ );
697
635
  if (!moduleUsed) {
698
636
  return null;
699
637
  }
@@ -706,95 +644,261 @@ function findCmsModules(cmsModules = {}) {
706
644
  buildEnd(error) {
707
645
  if (error)
708
646
  throw error;
709
- const modulesWithCmsModuleUsage = Array.of(
710
- ...this.getModuleIds()
711
- ).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => this.getModuleInfo(moduleId)).filter(
712
- (moduleInfo) => Object.hasOwn(moduleInfo.meta, "findCmsModules")
647
+ const entryPoints = getEntryPoints(this, config);
648
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
649
+ this,
650
+ entryPoints
713
651
  );
714
- const moduleToEntryPoints = {};
715
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
716
- moduleToEntryPoints[moduleWithCmsModuleUsage.id] = findEntryPoints(
717
- this,
718
- moduleWithCmsModuleUsage
719
- );
720
- }
721
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
722
- const usageInModuleEntryPoint = moduleToEntryPoints[moduleWithCmsModuleUsage.id].find((entryPoint) => entryPoint.id.includes("/components/modules"));
723
- if (usageInModuleEntryPoint) {
724
- this.error(`
725
- Error: <${CMS_MODULE_COMPONENT_NAME} /> can only be used in Partials.
726
- Module: ${usageInModuleEntryPoint.id === moduleWithCmsModuleUsage.id ? usageInModuleEntryPoint.id.replace(config.root, "") : `imports: ${moduleWithCmsModuleUsage.id.replace(
727
- config.root,
728
- ""
729
- )}, which`} contains a <${CMS_MODULE_COMPONENT_NAME} />
652
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
653
+ config,
654
+ entryPointCmsModuleMap
655
+ );
656
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
657
+ this,
658
+ entryPoints
659
+ );
660
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
661
+ config,
662
+ entryPointIslandCmsModuleMap
663
+ );
664
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
665
+ this.error(`
666
+ Error: <Module /> cannot be used within <Island />
667
+ Found invalid usages:
668
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
730
669
  `);
731
- }
732
670
  }
733
- const root = config.root;
734
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
735
- const islandsContainingCmsModuleUsage = checkModuleTreeForIslands(
736
- this,
737
- moduleWithCmsModuleUsage
738
- );
739
- if (islandsContainingCmsModuleUsage.length > 0) {
740
- throw new Error(`
741
- <${CMS_MODULE_COMPONENT_NAME} /> cannot be used within islands.
742
- ${formatIslandImporter(
743
- moduleWithCmsModuleUsage.id,
744
- root
745
- )} uses <${CMS_MODULE_COMPONENT_NAME} /> and is used by islands:
746
- ${islandsContainingCmsModuleUsage.map(
747
- (islandModuleInfo) => formatIslandImporter(islandModuleInfo.id, root)
748
- ).join(", ")}
749
- `);
750
- }
671
+ const modulesWithinModules = filterEntryPointsToModules(
672
+ relativeEntryPointCmsModuleMap
673
+ );
674
+ if (Object.keys(modulesWithinModules).length > 0) {
675
+ this.error(`
676
+ Error: <Module /> can only be used in React Partials
677
+ Found invalid usages:
678
+ ${JSON.stringify(modulesWithinModules, null, 2)}
679
+ `);
751
680
  }
752
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
753
- const entryPoints = moduleToEntryPoints[moduleWithCmsModuleUsage.id];
754
- for (const entryPoint of entryPoints) {
755
- const relativeEntryPoint = entryPoint.id.replace(root, "");
756
- if (!Object.hasOwn(cmsModules, relativeEntryPoint)) {
757
- cmsModules[relativeEntryPoint] = {};
758
- }
759
- for (const [cmsModuleName, cmsModuleValue] of Object.entries(
760
- moduleWithCmsModuleUsage.meta.findCmsModules
761
- )) {
762
- if (Object.hasOwn(cmsModules[relativeEntryPoint], cmsModuleName)) {
763
- this.error(`Error: duplicate module name: ${cmsModuleName}`);
764
- }
765
- cmsModules[relativeEntryPoint][cmsModuleName] = cmsModuleValue;
681
+ Object.assign(cmsModules, relativeEntryPointCmsModuleMap);
682
+ }
683
+ };
684
+ }
685
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
686
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
687
+ ([entryPointPath, cmsModules]) => {
688
+ return [toRelativePath(config, entryPointPath), cmsModules];
689
+ }
690
+ );
691
+ return Object.fromEntries(relativeEntries);
692
+ }
693
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
694
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
695
+ ([entryPointPath, islandCmsModules]) => {
696
+ const islandCmsModuleUsage = Object.fromEntries(
697
+ Object.entries(islandCmsModules).map(([islandPath, cmsModule]) => {
698
+ return [
699
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
700
+ cmsModule
701
+ ];
702
+ })
703
+ );
704
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
705
+ }
706
+ );
707
+ return Object.fromEntries(relativeEntries);
708
+ }
709
+ function toRelativePath(config, path3) {
710
+ return path3.replace(config.root, "");
711
+ }
712
+ function shouldSkipModule(config, moduleInfo, code) {
713
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
714
+ return isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME);
715
+ }
716
+ function getEntryPoints(ctx, config) {
717
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
718
+ }
719
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
720
+ const entryPointCmsModuleUsage = {};
721
+ for (const entryPoint of entryPoints) {
722
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
723
+ if (result) {
724
+ entryPointCmsModuleUsage[entryPoint.id] = result;
725
+ }
726
+ }
727
+ return entryPointCmsModuleUsage;
728
+ }
729
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
730
+ const entryPointIslandsCmsModuleMap = {};
731
+ for (const entryPoint of entryPoints) {
732
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
733
+ if (result) {
734
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
735
+ }
736
+ }
737
+ return entryPointIslandsCmsModuleMap;
738
+ }
739
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
740
+ const sourceAst = parser.parse(code, {
741
+ sourceType: "module",
742
+ plugins: ["jsx", "typescript"]
743
+ });
744
+ const localCmsModules = {};
745
+ let moduleUsed = false;
746
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
747
+ traverse(sourceAst, {
748
+ ImportDeclaration(path3) {
749
+ if (t.isStringLiteral(path3.node.source, {
750
+ value: "@hubspot/cms-components"
751
+ })) {
752
+ for (const specifier of path3.node.specifiers) {
753
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
754
+ name: CMS_MODULE_COMPONENT_NAME
755
+ })) {
756
+ moduleComponentLocalImportName = specifier.local.name;
766
757
  }
767
758
  }
768
759
  }
760
+ },
761
+ JSXOpeningElement(path3) {
762
+ if (!t.isJSXIdentifier(path3.node.name, {
763
+ name: moduleComponentLocalImportName
764
+ })) {
765
+ return null;
766
+ }
767
+ moduleUsed = true;
768
+ let cmsModuleName;
769
+ let cmsModulePath;
770
+ let cmsModuleLabel;
771
+ for (const prop of path3.node.attributes) {
772
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
773
+ cmsModuleName = prop.value.value;
774
+ continue;
775
+ }
776
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
777
+ cmsModulePath = prop.value.value;
778
+ continue;
779
+ }
780
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
781
+ cmsModuleLabel = prop.value.value;
782
+ continue;
783
+ }
784
+ ctx.error(
785
+ new Error(
786
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
787
+ )
788
+ );
789
+ }
790
+ const cmsModuleProps = {
791
+ name: cmsModuleName,
792
+ path: cmsModulePath
793
+ };
794
+ if (cmsModuleLabel) {
795
+ cmsModuleProps.label = cmsModuleLabel;
796
+ }
797
+ if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {
798
+ ctx.error(
799
+ new Error(
800
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
801
+ )
802
+ );
803
+ }
804
+ localCmsModules[cmsModuleProps.name] = cmsModuleProps;
769
805
  }
806
+ });
807
+ return {
808
+ moduleUsed,
809
+ localCmsModules
770
810
  };
771
811
  }
772
- function findEntryPoints(ctx, moduleInfo) {
773
- if (moduleInfo.isEntry) {
774
- return [moduleInfo];
812
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
813
+ if (Object.hasOwn(result, moduleId)) {
814
+ return result[moduleId];
775
815
  }
776
- const result = [];
777
- for (const importer of moduleInfo.importers) {
778
- const importerModuleInfo = ctx.getModuleInfo(importer);
779
- const entryPoints = findEntryPoints(ctx, importerModuleInfo);
780
- result.push(...entryPoints);
816
+ const moduleInfo = ctx.getModuleInfo(moduleId);
817
+ let entryPointModules = null;
818
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
819
+ entryPointModules = {
820
+ ...entryPointModules,
821
+ ...moduleInfo.meta[PLUGIN_NAME]
822
+ };
781
823
  }
782
- return result;
824
+ for (const importedId of [
825
+ ...moduleInfo.importedIds,
826
+ ...moduleInfo.dynamicallyImportedIds
827
+ ]) {
828
+ if (processed.has(importedId)) {
829
+ continue;
830
+ }
831
+ const importedResult = findCmsModuleUsages(
832
+ ctx,
833
+ importedId,
834
+ processed,
835
+ result
836
+ );
837
+ if (importedResult) {
838
+ entryPointModules = {
839
+ ...entryPointModules,
840
+ ...importedResult
841
+ };
842
+ }
843
+ }
844
+ if (entryPointModules) {
845
+ result[moduleId] = entryPointModules;
846
+ }
847
+ processed.add(moduleId);
848
+ return entryPointModules;
783
849
  }
784
- function checkModuleTreeForIslands(ctx, module) {
785
- if (module.id.endsWith("?client-entry")) {
786
- return [module];
850
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
851
+ processedIslands.add(moduleId);
852
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
853
+ return islandModuleResults[moduleId];
787
854
  }
788
- const importerResults = [];
789
- for (const importer of module.importers) {
790
- const importerInfo = ctx.getModuleInfo(importer);
791
- const importerResult = checkModuleTreeForIslands(ctx, importerInfo);
792
- importerResults.push(importerResult);
855
+ const moduleInfo = ctx.getModuleInfo(moduleId);
856
+ let resultForModuleId = {};
857
+ if (moduleInfo.id.endsWith("?client-entry")) {
858
+ const mergedDataDependencies = findCmsModuleUsages(
859
+ ctx,
860
+ moduleInfo.id,
861
+ processed,
862
+ results
863
+ );
864
+ if (mergedDataDependencies) {
865
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
866
+ }
793
867
  }
794
- return importerResults.flat();
868
+ for (const importedId of [
869
+ ...moduleInfo.importedIds,
870
+ ...moduleInfo.dynamicallyImportedIds
871
+ ]) {
872
+ if (processedIslands.has(importedId)) {
873
+ continue;
874
+ }
875
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
876
+ ctx,
877
+ importedId,
878
+ processedIslands,
879
+ islandModuleResults,
880
+ processed,
881
+ results
882
+ );
883
+ if (importerCmsModuleUsageResult) {
884
+ resultForModuleId = {
885
+ ...resultForModuleId,
886
+ ...importerCmsModuleUsageResult
887
+ };
888
+ }
889
+ }
890
+ if (Object.keys(resultForModuleId).length > 0) {
891
+ islandModuleResults[moduleId] = resultForModuleId;
892
+ return resultForModuleId;
893
+ }
894
+ return null;
795
895
  }
796
- function formatIslandImporter(id, root) {
797
- return id.replace(root, "").replace("?client-entry", "");
896
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
897
+ return Object.fromEntries(
898
+ Object.entries(entryPointCmsModuleMap).filter(
899
+ ([entryPoint]) => entryPoint.startsWith("/components/modules/")
900
+ )
901
+ );
798
902
  }
799
903
  async function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {
800
904
  const { props } = propsAndDeps;
@@ -912,13 +1016,13 @@ function renderFieldsToJson(fields, moduleName) {
912
1016
  throw e;
913
1017
  }
914
1018
  }
915
- var setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, traverse, CMS_MODULE_COMPONENT_NAME, promiseForNewWritableStream, renderStreamToPromise, createServerRenderContextV22, createServerRenderContext2, renderServerSidePropsWithAsyncLocalStoreContext, bootStrapRenderContext;
1019
+ var setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, traverse, CMS_MODULE_COMPONENT_NAME, PLUGIN_NAME, promiseForNewWritableStream, renderStreamToPromise, createServerRenderContextV22, createServerRenderContext2, renderServerSidePropsWithAsyncLocalStoreContext, bootStrapRenderContext;
916
1020
  var init_dist = __esm({
917
1021
  "../cms-js-internal/dist/index.js"() {
918
1022
  init_basicUtils();
919
1023
  init_basicUtils();
920
1024
  ({ setProperty, getProperty, hasProperty } = dotProp);
921
- serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
1025
+ serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {
922
1026
  const islandsArrayToSerialize = tweakedIslandsArray.map(
923
1027
  ({
924
1028
  id,
@@ -960,6 +1064,9 @@ var init_dist = __esm({
960
1064
  if (filteredSupplementalFieldValues) {
961
1065
  output.supplementalFieldValues = filteredSupplementalFieldValues;
962
1066
  }
1067
+ if (isUngatedForClientOnlySupplementalFieldSerialization && output.clientOnly) {
1068
+ output.supplementalFieldValues = supplementalFieldValues;
1069
+ }
963
1070
  return output;
964
1071
  }
965
1072
  );
@@ -993,7 +1100,7 @@ ${indentString}`);
993
1100
  }
994
1101
  return "";
995
1102
  };
996
- createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
1103
+ createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {
997
1104
  const islands = getIslandUrls(roots, viteDevServer);
998
1105
  const perServerRequestDataWithUrls = getPerServerRequestUrls(
999
1106
  perServerRequestData,
@@ -1005,7 +1112,8 @@ ${indentString}`);
1005
1112
  islands,
1006
1113
  perServerRequestData,
1007
1114
  indent,
1008
- prettyPrint
1115
+ prettyPrint,
1116
+ isUngatedForClientOnlySupplementalFieldSerialization
1009
1117
  )}${writeSharedStateToJsGlobal(
1010
1118
  islands,
1011
1119
  perServerRequestDataWithUrls,
@@ -1015,6 +1123,7 @@ ${indentString}`);
1015
1123
  };
1016
1124
  traverse = _traverse.default;
1017
1125
  CMS_MODULE_COMPONENT_NAME = "Module";
1126
+ PLUGIN_NAME = "findCmsModules";
1018
1127
  promiseForNewWritableStream = () => {
1019
1128
  const chunks = [];
1020
1129
  const writableStream = new stream.Writable();